code
stringlengths 82
53.2k
| code_codestyle
int64 0
721
| style_context
stringlengths 91
41.9k
| style_context_codestyle
int64 0
699
| label
int64 0
1
|
|---|---|---|---|---|
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_tf
if is_tf_available():
import tensorflow as tf
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from transformers import GradientAccumulator, create_optimizer
@require_tf
class lowercase__ ( unittest.TestCase ):
def A_ ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] ):
self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) )
for a, b in zip(UpperCAmelCase_ , UpperCAmelCase_ ):
self.assertAlmostEqual(UpperCAmelCase_ , UpperCAmelCase_ , delta=UpperCAmelCase_ )
def A_ ( self : Dict ):
SCREAMING_SNAKE_CASE__ = GradientAccumulator()
accumulator([tf.constant([1.0, 2.0] )] )
accumulator([tf.constant([-2.0, 1.0] )] )
accumulator([tf.constant([-1.0, 2.0] )] )
with self.assertRaises(UpperCAmelCase_ ):
accumulator([tf.constant([1.0, 1.0] ), tf.constant([2.0, 2.0] )] )
self.assertEqual(accumulator.step , 3 )
self.assertEqual(len(accumulator.gradients ) , 1 )
self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2 )
accumulator.reset()
self.assertEqual(accumulator.step , 0 )
self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2 )
def A_ ( self : str ):
SCREAMING_SNAKE_CASE__ = None
ops.enable_eager_execution_internal()
SCREAMING_SNAKE_CASE__ = tf.config.list_physical_devices('CPU' )
if len(UpperCAmelCase_ ) == 1:
tf.config.set_logical_device_configuration(
physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] )
SCREAMING_SNAKE_CASE__ = tf.config.list_logical_devices(device_type='CPU' )
SCREAMING_SNAKE_CASE__ = tf.distribute.MirroredStrategy(devices=devices[:2] )
with strategy.scope():
SCREAMING_SNAKE_CASE__ = GradientAccumulator()
SCREAMING_SNAKE_CASE__ = tf.Variable([4.0, 3.0] )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = create_optimizer(5e-5 , 10 , 5 )
SCREAMING_SNAKE_CASE__ = tf.Variable([0.0, 0.0] , trainable=UpperCAmelCase_ )
def accumulate_on_replica(UpperCAmelCase_ : Any ):
accumulator([gradient] )
def apply_on_replica():
optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) )
@tf.function
def accumulate(UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple ):
with strategy.scope():
SCREAMING_SNAKE_CASE__ = strategy.experimental_local_results(UpperCAmelCase_ )
local_variables[0].assign(UpperCAmelCase_ )
local_variables[1].assign(UpperCAmelCase_ )
strategy.run(UpperCAmelCase_ , args=(gradient_placeholder,) )
@tf.function
def apply_grad():
with strategy.scope():
strategy.run(UpperCAmelCase_ )
def _check_local_values(UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple ):
SCREAMING_SNAKE_CASE__ = strategy.experimental_local_results(accumulator._gradients[0] )
self.assertListAlmostEqual(values[0].value() , UpperCAmelCase_ , tol=1e-2 )
self.assertListAlmostEqual(values[1].value() , UpperCAmelCase_ , tol=1e-2 )
accumulate([1.0, 2.0] , [-1.0, 1.0] )
accumulate([3.0, -1.0] , [-1.0, -1.0] )
accumulate([-2.0, 2.0] , [3.0, -2.0] )
self.assertEqual(accumulator.step , 3 )
_check_local_values([2.0, 3.0] , [1.0, -2.0] )
apply_grad()
self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2 )
accumulator.reset()
self.assertEqual(accumulator.step , 0 )
_check_local_values([0.0, 0.0] , [0.0, 0.0] )
| 472
|
import argparse
import requests
import torch
# pip3 install salesforce-lavis
# I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch)
# also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml
# same for Vicuna-13b
from lavis.models import load_model_and_preprocess
from PIL import Image
from transformers import (
AutoTokenizer,
BlipImageProcessor,
InstructBlipConfig,
InstructBlipForConditionalGeneration,
InstructBlipProcessor,
InstructBlipQFormerConfig,
InstructBlipVisionConfig,
LlamaConfig,
LlamaTokenizerFast,
TaConfig,
TaTokenizerFast,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
def _lowercase ( ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = 'https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg'
SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ).convert('RGB' )
return image
def _lowercase ( UpperCamelCase_ ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = []
# fmt: off
# vision encoder
rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding') )
rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding') )
rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight') )
rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias') )
rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight') )
rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias') )
for i in range(config.vision_config.num_hidden_layers ):
rename_keys.append((F'visual_encoder.blocks.{i}.norm1.weight', F'vision_model.encoder.layers.{i}.layer_norm1.weight') )
rename_keys.append((F'visual_encoder.blocks.{i}.norm1.bias', F'vision_model.encoder.layers.{i}.layer_norm1.bias') )
rename_keys.append((F'visual_encoder.blocks.{i}.norm2.weight', F'vision_model.encoder.layers.{i}.layer_norm2.weight') )
rename_keys.append((F'visual_encoder.blocks.{i}.norm2.bias', F'vision_model.encoder.layers.{i}.layer_norm2.bias') )
rename_keys.append((F'visual_encoder.blocks.{i}.attn.qkv.weight', F'vision_model.encoder.layers.{i}.self_attn.qkv.weight') )
rename_keys.append((F'visual_encoder.blocks.{i}.attn.proj.weight', F'vision_model.encoder.layers.{i}.self_attn.projection.weight',) )
rename_keys.append((F'visual_encoder.blocks.{i}.attn.proj.bias', F'vision_model.encoder.layers.{i}.self_attn.projection.bias') )
rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc1.weight', F'vision_model.encoder.layers.{i}.mlp.fc1.weight') )
rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc1.bias', F'vision_model.encoder.layers.{i}.mlp.fc1.bias') )
rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc2.weight', F'vision_model.encoder.layers.{i}.mlp.fc2.weight') )
rename_keys.append((F'visual_encoder.blocks.{i}.mlp.fc2.bias', F'vision_model.encoder.layers.{i}.mlp.fc2.bias') )
# QFormer
rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.embeddings.layernorm.weight') )
rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.embeddings.layernorm.bias') )
# fmt: on
return rename_keys
def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = val
def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> str:
'''simple docstring'''
for i in range(config.vision_config.num_hidden_layers ):
# read in original q and v biases
SCREAMING_SNAKE_CASE__ = state_dict.pop(F'visual_encoder.blocks.{i}.attn.q_bias' )
SCREAMING_SNAKE_CASE__ = state_dict.pop(F'visual_encoder.blocks.{i}.attn.v_bias' )
# next, set bias in the state dict
SCREAMING_SNAKE_CASE__ = torch.cat((q_bias, torch.zeros_like(UpperCamelCase_ , requires_grad=UpperCamelCase_ ), v_bias) )
SCREAMING_SNAKE_CASE__ = qkv_bias
def _lowercase ( UpperCamelCase_ ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = 364 if 'coco' in model_name else 224
SCREAMING_SNAKE_CASE__ = InstructBlipVisionConfig(image_size=UpperCamelCase_ ).to_dict()
# make sure the models have proper bos_token_id and eos_token_id set (important for generation)
# seems like flan-T5 models don't have bos_token_id properly set?
if "t5-xl" in model_name:
SCREAMING_SNAKE_CASE__ = TaConfig.from_pretrained('google/flan-t5-xl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict()
elif "t5-xxl" in model_name:
SCREAMING_SNAKE_CASE__ = TaConfig.from_pretrained('google/flan-t5-xxl' , dense_act_fn='gelu' , bos_token_id=1 ).to_dict()
elif "vicuna-7b" in model_name:
SCREAMING_SNAKE_CASE__ = LlamaConfig.from_pretrained('decapoda-research/llama-7b-hf' , vocab_size=32001 ).to_dict()
elif "vicuna-13b" in model_name:
SCREAMING_SNAKE_CASE__ = LlamaConfig.from_pretrained('decapoda-research/llama-13b-hf' , vocab_size=32001 ).to_dict()
else:
raise ValueError('Model name not supported' )
# the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1
SCREAMING_SNAKE_CASE__ = InstructBlipQFormerConfig(vocab_size=30523 ).to_dict()
SCREAMING_SNAKE_CASE__ = InstructBlipConfig(vision_config=UpperCamelCase_ , text_config=UpperCamelCase_ , qformer_config=UpperCamelCase_ )
return config, image_size
@torch.no_grad()
def _lowercase ( UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=False ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained('bert-base-uncased' , truncation_side='left' )
qformer_tokenizer.add_special_tokens({'bos_token': '[DEC]'} )
if "t5" in model_name:
SCREAMING_SNAKE_CASE__ = TaTokenizerFast.from_pretrained('google/flan-t5-xl' , truncation_side='left' )
elif "vicuna" in model_name:
# the following was used in the original implementation:
# tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left")
# tokenizer.add_special_tokens({"pad_token": "[PAD]"})
# tokenizer.add_special_tokens({"bos_token": "</s>"})
# tokenizer.add_special_tokens({"eos_token": "</s>"})
# tokenizer.add_special_tokens({"unk_token": "</s>"})
SCREAMING_SNAKE_CASE__ = LlamaTokenizerFast.from_pretrained(
'huggyllama/llama-7b' , truncation_side='left' , bos_token='</s>' , unk_token='</s>' )
tokenizer.add_special_tokens({'pad_token': '[PAD]'} )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_blipa_config(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = InstructBlipForConditionalGeneration(UpperCamelCase_ ).eval()
SCREAMING_SNAKE_CASE__ = {
'instructblip-vicuna-7b': ('blip2_vicuna_instruct', 'vicuna7b'),
'instructblip-vicuna-13b': ('blip2_vicuna_instruct', 'vicuna13b'),
'instructblip-flan-t5-xl': ('blip2_t5_instruct', 'flant5xl'),
'instructblip-flan-t5-xxl': ('blip2_t5_instruct', 'flant5xxl'),
}
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model_name_to_original[model_name]
# load original model
print('Loading original model...' )
SCREAMING_SNAKE_CASE__ = 'cuda:1' if torch.cuda.is_available() else 'cpu'
SCREAMING_SNAKE_CASE__ = 'cuda:2' if torch.cuda.is_available() else 'cpu'
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = load_model_and_preprocess(
name=UpperCamelCase_ , model_type=UpperCamelCase_ , is_eval=UpperCamelCase_ , device=UpperCamelCase_ )
original_model.eval()
print('Done!' )
# update state dict keys
SCREAMING_SNAKE_CASE__ = original_model.state_dict()
SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase_ )
for src, dest in rename_keys:
rename_key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# some keys can be renamed efficiently
for key, val in state_dict.copy().items():
SCREAMING_SNAKE_CASE__ = state_dict.pop(UpperCamelCase_ )
if key.startswith('Qformer.bert' ):
SCREAMING_SNAKE_CASE__ = key.replace('Qformer.bert' , 'qformer' )
if "attention.self" in key:
SCREAMING_SNAKE_CASE__ = key.replace('self' , 'attention' )
if "llm_proj" in key:
SCREAMING_SNAKE_CASE__ = key.replace('llm_proj' , 'language_projection' )
if "t5_proj" in key:
SCREAMING_SNAKE_CASE__ = key.replace('t5_proj' , 'language_projection' )
if key.startswith('llm_model' ):
SCREAMING_SNAKE_CASE__ = key.replace('llm_model' , 'language_model' )
if key.startswith('t5' ):
SCREAMING_SNAKE_CASE__ = key.replace('t5' , 'language' )
SCREAMING_SNAKE_CASE__ = val
# read in qv biases
read_in_q_v_bias(UpperCamelCase_ , UpperCamelCase_ )
# note: weights get loaded in torch.float32 by default
hf_model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = load_demo_image()
SCREAMING_SNAKE_CASE__ = 'What is unusual about this image?'
# create processor
SCREAMING_SNAKE_CASE__ = BlipImageProcessor(
size={'height': image_size, 'width': image_size} , image_mean=UpperCamelCase_ , image_std=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = InstructBlipProcessor(
image_processor=UpperCamelCase_ , tokenizer=UpperCamelCase_ , qformer_tokenizer=UpperCamelCase_ , )
SCREAMING_SNAKE_CASE__ = processor(images=UpperCamelCase_ , text=UpperCamelCase_ , return_tensors='pt' ).to(UpperCamelCase_ )
# make sure processor creates exact same pixel values
SCREAMING_SNAKE_CASE__ = vis_processors['eval'](UpperCamelCase_ ).unsqueeze(0 ).to(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = inputs.pixel_values
assert torch.allclose(original_pixel_values.to(pixel_values.device ) , UpperCamelCase_ )
original_model.to(UpperCamelCase_ )
hf_model.to(UpperCamelCase_ )
with torch.no_grad():
if "vicuna" in model_name:
SCREAMING_SNAKE_CASE__ = original_model({'image': original_pixel_values, 'text_input': [prompt]} ).logits
SCREAMING_SNAKE_CASE__ = hf_model(**UpperCamelCase_ ).logits
else:
SCREAMING_SNAKE_CASE__ = original_model(
{'image': original_pixel_values, 'text_input': [prompt], 'text_output': ['\n']} ).logits
SCREAMING_SNAKE_CASE__ = tokenizer('\n' , return_tensors='pt' ).input_ids.to(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 )
SCREAMING_SNAKE_CASE__ = hf_model(**UpperCamelCase_ , labels=UpperCamelCase_ ).logits
print('First values of original logits:' , original_logits[0, :3, :3] )
print('First values of HF logits:' , logits[0, :3, :3] )
# assert values
assert original_logits.shape == logits.shape
SCREAMING_SNAKE_CASE__ = 1e-4 if 'vicuna' in model_name else 1e-5
assert torch.allclose(original_logits.to(logits.device ) , UpperCamelCase_ , atol=UpperCamelCase_ )
print('Looks ok!' )
print('Generating with original model...' )
SCREAMING_SNAKE_CASE__ = original_model.generate({'image': original_pixel_values, 'prompt': prompt} , num_beams=5 )
# important: we need to cast the weights of the HF model to the appropriate type
print('Generating with HF model...' )
SCREAMING_SNAKE_CASE__ = hf_model.generate(
**UpperCamelCase_ , do_sample=UpperCamelCase_ , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , )
if "vicuna" in model_name:
# convert output id 0 to 2 (eos_token_id)
# TODO add this in the generate method?
SCREAMING_SNAKE_CASE__ = 2
print('Original generation:' , UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = processor.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = [text.strip() for text in output_text]
print('HF generation:' , UpperCamelCase_ )
if pytorch_dump_folder_path is not None:
processor.save_pretrained(UpperCamelCase_ )
hf_model.save_pretrained(UpperCamelCase_ )
if push_to_hub:
processor.push_to_hub(F'Salesforce/{model_name}' )
hf_model.push_to_hub(F'Salesforce/{model_name}' )
if __name__ == "__main__":
__snake_case = argparse.ArgumentParser()
__snake_case = [
"""instructblip-vicuna-7b""",
"""instructblip-vicuna-13b""",
"""instructblip-flan-t5-xl""",
"""instructblip-flan-t5-xxl""",
]
parser.add_argument(
"""--model_name""",
default="""instructblip-flan-t5-xl""",
choices=choices,
type=str,
help="""Path to hf config.json of model to convert""",
)
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument(
"""--push_to_hub""",
action="""store_true""",
help="""Whether to push the model and processor to the hub after converting""",
)
__snake_case = parser.parse_args()
convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 472
| 1
|
'''simple docstring'''
from collections.abc import Callable
import numpy as np
def _A ( A__ , A__ , A__ , A__ , A__ ):
"""simple docstring"""
__lowercase = int(np.ceil((x_end - xa) / step_size ) )
__lowercase = np.zeros((n + 1,) )
__lowercase = ya
__lowercase = xa
for k in range(A__ ):
__lowercase = y[k] + step_size * ode_func(A__ , y[k] )
__lowercase = y[k] + (
(step_size / 2) * (ode_func(A__ , y[k] ) + ode_func(x + step_size , A__ ))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 718
|
'''simple docstring'''
import hashlib
import unittest
from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
else:
class lowercase_ :
"""simple docstring"""
@staticmethod
def SCREAMING_SNAKE_CASE ( *lowercase__ : Union[str, Any] ,**lowercase__ : Tuple ):
pass
def _A ( A__ ):
"""simple docstring"""
__lowercase = hashlib.mda(image.tobytes() )
return m.hexdigest()
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class lowercase_ (unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = MODEL_FOR_DEPTH_ESTIMATION_MAPPING
def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : int ,lowercase__ : List[str] ,lowercase__ : int ):
__lowercase = DepthEstimationPipeline(model=lowercase__ ,image_processor=lowercase__ )
return depth_estimator, [
"./tests/fixtures/tests_samples/COCO/000000039769.png",
"./tests/fixtures/tests_samples/COCO/000000039769.png",
]
def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : List[str] ,lowercase__ : List[str] ):
__lowercase = depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} ,lowercase__ )
import datasets
__lowercase = datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' ,'''image''' ,split='''test''' )
__lowercase = depth_estimator(
[
Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ),
'''http://images.cocodataset.org/val2017/000000039769.jpg''',
# RGBA
dataset[0]['''file'''],
# LA
dataset[1]['''file'''],
# L
dataset[2]['''file'''],
] )
self.assertEqual(
[
{'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )},
{'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )},
{'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )},
{'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )},
{'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )},
] ,lowercase__ ,)
@require_tf
@unittest.skip('''Depth estimation is not implemented in TF''' )
def SCREAMING_SNAKE_CASE ( self : Dict ):
pass
@slow
@require_torch
def SCREAMING_SNAKE_CASE ( self : List[str] ):
__lowercase = '''Intel/dpt-large'''
__lowercase = pipeline('''depth-estimation''' ,model=lowercase__ )
__lowercase = depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' )
__lowercase = hashimage(outputs['''depth'''] )
# This seems flaky.
# self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) ,2_9.3_0_4 )
self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) ,2.6_6_2 )
@require_torch
def SCREAMING_SNAKE_CASE ( self : List[Any] ):
# This is highly irregular to have no small tests.
self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
| 624
| 0
|
"""simple docstring"""
import unittest
from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
else:
class _lowerCAmelCase :
"""simple docstring"""
@staticmethod
def snake_case ( *__UpperCAmelCase , **__UpperCAmelCase ):
'''simple docstring'''
pass
@is_pipeline_test
@require_vision
@require_torch
class _lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
__magic_name__ :int = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :List[Any] = pipeline(
'zero-shot-object-detection' , model='hf-internal-testing/tiny-random-owlvit-object-detection' )
lowerCAmelCase__ :int = [
{
'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
'candidate_labels': ['cat', 'remote', 'couch'],
}
]
return object_detector, examples
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :Union[str, Any] = object_detector(examples[0] , threshold=0.0 )
lowerCAmelCase__ :Optional[Any] = len(__UpperCAmelCase )
self.assertGreater(__UpperCAmelCase , 0 )
self.assertEqual(
__UpperCAmelCase , [
{
'score': ANY(__UpperCAmelCase ),
'label': ANY(__UpperCAmelCase ),
'box': {'xmin': ANY(__UpperCAmelCase ), 'ymin': ANY(__UpperCAmelCase ), 'xmax': ANY(__UpperCAmelCase ), 'ymax': ANY(__UpperCAmelCase )},
}
for i in range(__UpperCAmelCase )
] , )
@require_tf
@unittest.skip('Zero Shot Object Detection not implemented in TF' )
def snake_case ( self ):
'''simple docstring'''
pass
@require_torch
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :int = pipeline(
'zero-shot-object-detection' , model='hf-internal-testing/tiny-random-owlvit-object-detection' )
lowerCAmelCase__ :str = object_detector(
'./tests/fixtures/tests_samples/COCO/000000039769.png' , candidate_labels=['cat', 'remote', 'couch'] , threshold=0.64 , )
self.assertEqual(
nested_simplify(__UpperCAmelCase , decimals=4 ) , [
{'score': 0.72_35, 'label': 'cat', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
{'score': 0.72_18, 'label': 'remote', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
{'score': 0.71_84, 'label': 'couch', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
{'score': 0.67_48, 'label': 'remote', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
{'score': 0.66_56, 'label': 'cat', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
{'score': 0.66_14, 'label': 'couch', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
{'score': 0.64_56, 'label': 'remote', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
{'score': 0.6_42, 'label': 'remote', 'box': {'xmin': 6_7, 'ymin': 2_7_4, 'xmax': 9_3, 'ymax': 2_9_7}},
{'score': 0.64_19, 'label': 'cat', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
] , )
lowerCAmelCase__ :Any = object_detector(
[
{
'image': './tests/fixtures/tests_samples/COCO/000000039769.png',
'candidate_labels': ['cat', 'remote', 'couch'],
}
] , threshold=0.64 , )
self.assertEqual(
nested_simplify(__UpperCAmelCase , decimals=4 ) , [
[
{'score': 0.72_35, 'label': 'cat', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
{'score': 0.72_18, 'label': 'remote', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
{'score': 0.71_84, 'label': 'couch', 'box': {'xmin': 2_0_4, 'ymin': 1_6_7, 'xmax': 2_3_2, 'ymax': 1_9_0}},
{'score': 0.67_48, 'label': 'remote', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
{'score': 0.66_56, 'label': 'cat', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
{'score': 0.66_14, 'label': 'couch', 'box': {'xmin': 5_7_1, 'ymin': 8_3, 'xmax': 5_9_8, 'ymax': 1_0_3}},
{'score': 0.64_56, 'label': 'remote', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
{'score': 0.6_42, 'label': 'remote', 'box': {'xmin': 6_7, 'ymin': 2_7_4, 'xmax': 9_3, 'ymax': 2_9_7}},
{'score': 0.64_19, 'label': 'cat', 'box': {'xmin': 4_9_4, 'ymin': 1_0_5, 'xmax': 5_2_1, 'ymax': 1_2_7}},
]
] , )
@require_torch
@slow
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :int = pipeline('zero-shot-object-detection' )
lowerCAmelCase__ :str = object_detector(
'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , )
self.assertEqual(
nested_simplify(__UpperCAmelCase , decimals=4 ) , [
{'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
{'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
{'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
{'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 3_3_5, 'ymin': 7_4, 'xmax': 3_7_1, 'ymax': 1_8_7}},
{'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_4_2, 'ymax': 4_7_6}},
] , )
lowerCAmelCase__ :Any = object_detector(
[
{
'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
'candidate_labels': ['cat', 'remote', 'couch'],
},
{
'image': 'http://images.cocodataset.org/val2017/000000039769.jpg',
'candidate_labels': ['cat', 'remote', 'couch'],
},
] , )
self.assertEqual(
nested_simplify(__UpperCAmelCase , decimals=4 ) , [
[
{'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
{'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
{'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
{'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 3_3_5, 'ymin': 7_4, 'xmax': 3_7_1, 'ymax': 1_8_7}},
{'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_4_2, 'ymax': 4_7_6}},
],
[
{'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
{'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
{'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
{'score': 0.14_74, 'label': 'remote', 'box': {'xmin': 3_3_5, 'ymin': 7_4, 'xmax': 3_7_1, 'ymax': 1_8_7}},
{'score': 0.12_08, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 6_4_2, 'ymax': 4_7_6}},
],
] , )
@require_tf
@unittest.skip('Zero Shot Object Detection not implemented in TF' )
def snake_case ( self ):
'''simple docstring'''
pass
@require_torch
@slow
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :str = 0.2
lowerCAmelCase__ :Optional[Any] = pipeline('zero-shot-object-detection' )
lowerCAmelCase__ :Optional[Any] = object_detector(
'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , threshold=__UpperCAmelCase , )
self.assertEqual(
nested_simplify(__UpperCAmelCase , decimals=4 ) , [
{'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
{'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
{'score': 0.25_37, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 5_5, 'xmax': 3_1_5, 'ymax': 4_7_2}},
] , )
@require_torch
@slow
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = 2
lowerCAmelCase__ :Tuple = pipeline('zero-shot-object-detection' )
lowerCAmelCase__ :str = object_detector(
'http://images.cocodataset.org/val2017/000000039769.jpg' , candidate_labels=['cat', 'remote', 'couch'] , top_k=__UpperCAmelCase , )
self.assertEqual(
nested_simplify(__UpperCAmelCase , decimals=4 ) , [
{'score': 0.28_68, 'label': 'cat', 'box': {'xmin': 3_2_4, 'ymin': 2_0, 'xmax': 6_4_0, 'ymax': 3_7_3}},
{'score': 0.2_77, 'label': 'remote', 'box': {'xmin': 4_0, 'ymin': 7_2, 'xmax': 1_7_7, 'ymax': 1_1_5}},
] , )
| 93
|
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetaImageProcessor
class _lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=3_0 , __UpperCAmelCase=4_0_0 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=[0.5, 0.5, 0.5] , __UpperCAmelCase=[0.5, 0.5, 0.5] , __UpperCAmelCase=True , __UpperCAmelCase=1 / 2_5_5 , __UpperCAmelCase=True , ):
'''simple docstring'''
lowerCAmelCase__ :Any = size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
lowerCAmelCase__ :List[Any] = parent
lowerCAmelCase__ :int = batch_size
lowerCAmelCase__ :Union[str, Any] = num_channels
lowerCAmelCase__ :Any = min_resolution
lowerCAmelCase__ :Dict = max_resolution
lowerCAmelCase__ :Dict = do_resize
lowerCAmelCase__ :Optional[Any] = size
lowerCAmelCase__ :List[str] = do_normalize
lowerCAmelCase__ :str = image_mean
lowerCAmelCase__ :Tuple = image_std
lowerCAmelCase__ :Dict = do_rescale
lowerCAmelCase__ :Tuple = rescale_factor
lowerCAmelCase__ :Optional[int] = do_pad
def snake_case ( self ):
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase=False ):
'''simple docstring'''
if not batched:
lowerCAmelCase__ :str = image_inputs[0]
if isinstance(__UpperCAmelCase , Image.Image ):
lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = image.size
else:
lowerCAmelCase__ , lowerCAmelCase__ :str = image.shape[1], image.shape[2]
if w < h:
lowerCAmelCase__ :int = int(self.size['shortest_edge'] * h / w )
lowerCAmelCase__ :List[str] = self.size['shortest_edge']
elif w > h:
lowerCAmelCase__ :Union[str, Any] = self.size['shortest_edge']
lowerCAmelCase__ :Any = int(self.size['shortest_edge'] * w / h )
else:
lowerCAmelCase__ :int = self.size['shortest_edge']
lowerCAmelCase__ :Union[str, Any] = self.size['shortest_edge']
else:
lowerCAmelCase__ :Optional[Any] = []
for image in image_inputs:
lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
lowerCAmelCase__ :List[str] = max(__UpperCAmelCase , key=lambda __UpperCAmelCase : item[0] )[0]
lowerCAmelCase__ :List[Any] = max(__UpperCAmelCase , key=lambda __UpperCAmelCase : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class _lowerCAmelCase ( a , unittest.TestCase ):
"""simple docstring"""
__magic_name__ :Any = DetaImageProcessor if is_vision_available() else None
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :int = DetaImageProcessingTester(self )
@property
def snake_case ( self ):
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Tuple = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__UpperCAmelCase , 'image_mean' ) )
self.assertTrue(hasattr(__UpperCAmelCase , 'image_std' ) )
self.assertTrue(hasattr(__UpperCAmelCase , 'do_normalize' ) )
self.assertTrue(hasattr(__UpperCAmelCase , 'do_resize' ) )
self.assertTrue(hasattr(__UpperCAmelCase , 'do_rescale' ) )
self.assertTrue(hasattr(__UpperCAmelCase , 'do_pad' ) )
self.assertTrue(hasattr(__UpperCAmelCase , 'size' ) )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Dict = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3} )
self.assertEqual(image_processor.do_pad , __UpperCAmelCase )
def snake_case ( self ):
'''simple docstring'''
pass
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowerCAmelCase__ :Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(__UpperCAmelCase , Image.Image )
# Test not batched input
lowerCAmelCase__ :Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = self.image_processor_tester.get_expected_values(__UpperCAmelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
lowerCAmelCase__ , lowerCAmelCase__ :Tuple = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase )
lowerCAmelCase__ :Optional[Any] = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
lowerCAmelCase__ :Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(__UpperCAmelCase , np.ndarray )
# Test not batched input
lowerCAmelCase__ :List[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = self.image_processor_tester.get_expected_values(__UpperCAmelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
lowerCAmelCase__ :Tuple = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values
lowerCAmelCase__ , lowerCAmelCase__ :List[str] = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
lowerCAmelCase__ :List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase )
for image in image_inputs:
self.assertIsInstance(__UpperCAmelCase , torch.Tensor )
# Test not batched input
lowerCAmelCase__ :Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
lowerCAmelCase__ , lowerCAmelCase__ :Optional[int] = self.image_processor_tester.get_expected_values(__UpperCAmelCase )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
lowerCAmelCase__ :str = image_processing(__UpperCAmelCase , return_tensors='pt' ).pixel_values
lowerCAmelCase__ , lowerCAmelCase__ :List[Any] = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f:
lowerCAmelCase__ :Dict = json.loads(f.read() )
lowerCAmelCase__ :int = {'image_id': 3_9_7_6_9, 'annotations': target}
# encode them
lowerCAmelCase__ :int = DetaImageProcessor()
lowerCAmelCase__ :List[Any] = image_processing(images=__UpperCAmelCase , annotations=__UpperCAmelCase , return_tensors='pt' )
# verify pixel values
lowerCAmelCase__ :str = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['pixel_values'].shape , __UpperCAmelCase )
lowerCAmelCase__ :Optional[int] = torch.tensor([0.27_96, 0.31_38, 0.34_81] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __UpperCAmelCase , atol=1E-4 ) )
# verify area
lowerCAmelCase__ :Dict = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __UpperCAmelCase ) )
# verify boxes
lowerCAmelCase__ :Tuple = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __UpperCAmelCase )
lowerCAmelCase__ :Dict = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __UpperCAmelCase , atol=1E-3 ) )
# verify image_id
lowerCAmelCase__ :Any = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __UpperCAmelCase ) )
# verify is_crowd
lowerCAmelCase__ :Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __UpperCAmelCase ) )
# verify class_labels
lowerCAmelCase__ :Optional[Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __UpperCAmelCase ) )
# verify orig_size
lowerCAmelCase__ :str = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __UpperCAmelCase ) )
# verify size
lowerCAmelCase__ :Any = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __UpperCAmelCase ) )
@slow
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f:
lowerCAmelCase__ :Dict = json.loads(f.read() )
lowerCAmelCase__ :Dict = {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}
lowerCAmelCase__ :Union[str, Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' )
# encode them
lowerCAmelCase__ :Dict = DetaImageProcessor(format='coco_panoptic' )
lowerCAmelCase__ :Optional[int] = image_processing(images=__UpperCAmelCase , annotations=__UpperCAmelCase , masks_path=__UpperCAmelCase , return_tensors='pt' )
# verify pixel values
lowerCAmelCase__ :str = torch.Size([1, 3, 8_0_0, 1_0_6_6] )
self.assertEqual(encoding['pixel_values'].shape , __UpperCAmelCase )
lowerCAmelCase__ :Union[str, Any] = torch.tensor([0.27_96, 0.31_38, 0.34_81] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __UpperCAmelCase , atol=1E-4 ) )
# verify area
lowerCAmelCase__ :Tuple = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __UpperCAmelCase ) )
# verify boxes
lowerCAmelCase__ :int = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __UpperCAmelCase )
lowerCAmelCase__ :Optional[Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __UpperCAmelCase , atol=1E-3 ) )
# verify image_id
lowerCAmelCase__ :Optional[int] = torch.tensor([3_9_7_6_9] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __UpperCAmelCase ) )
# verify is_crowd
lowerCAmelCase__ :Tuple = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __UpperCAmelCase ) )
# verify class_labels
lowerCAmelCase__ :List[str] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __UpperCAmelCase ) )
# verify masks
lowerCAmelCase__ :Optional[int] = 8_2_2_8_7_3
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __UpperCAmelCase )
# verify orig_size
lowerCAmelCase__ :Optional[int] = torch.tensor([4_8_0, 6_4_0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __UpperCAmelCase ) )
# verify size
lowerCAmelCase__ :Union[str, Any] = torch.tensor([8_0_0, 1_0_6_6] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __UpperCAmelCase ) )
| 93
| 1
|
'''simple docstring'''
def _UpperCamelCase ( __UpperCamelCase ) -> float:
return 10 - x * x
def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> float:
# Bolzano theory in order to find if there is a root between a and b
if equation(__UpperCamelCase ) * equation(__UpperCamelCase ) >= 0:
raise ValueError('Wrong space!' )
lowerCamelCase_ = a
while (b - a) >= 0.01:
# Find middle point
lowerCamelCase_ = (a + b) / 2
# Check if middle point is root
if equation(__UpperCamelCase ) == 0.0:
break
# Decide the side to repeat the steps
if equation(__UpperCamelCase ) * equation(__UpperCamelCase ) < 0:
lowerCamelCase_ = c
else:
lowerCamelCase_ = c
return c
if __name__ == "__main__":
import doctest
doctest.testmod()
print(bisection(-2, 5))
print(bisection(0, 6))
| 711
|
'''simple docstring'''
from __future__ import annotations
from typing import Generic, TypeVar
A_ = TypeVar("T")
class UpperCAmelCase ( Generic[T] ):
'''simple docstring'''
def __init__( self , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
lowerCamelCase_ = data
lowerCamelCase_ = self
lowerCamelCase_ = 0
class UpperCAmelCase ( Generic[T] ):
'''simple docstring'''
def __init__( self ) -> None:
'''simple docstring'''
lowerCamelCase_ = {}
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
lowerCamelCase_ = DisjointSetTreeNode(SCREAMING_SNAKE_CASE_ )
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> DisjointSetTreeNode[T]:
'''simple docstring'''
lowerCamelCase_ = self.map[data]
if elem_ref != elem_ref.parent:
lowerCamelCase_ = self.find_set(elem_ref.parent.data )
return elem_ref.parent
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
if nodea.rank > nodea.rank:
lowerCamelCase_ = nodea
else:
lowerCamelCase_ = nodea
if nodea.rank == nodea.rank:
nodea.rank += 1
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
self.link(self.find_set(SCREAMING_SNAKE_CASE_ ) , self.find_set(SCREAMING_SNAKE_CASE_ ) )
class UpperCAmelCase ( Generic[T] ):
'''simple docstring'''
def __init__( self ) -> None:
'''simple docstring'''
lowerCamelCase_ = {}
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
if node not in self.connections:
lowerCamelCase_ = {}
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> None:
'''simple docstring'''
self.add_node(SCREAMING_SNAKE_CASE_ )
self.add_node(SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = weight
lowerCamelCase_ = weight
def UpperCamelCase( self ) -> GraphUndirectedWeighted[T]:
'''simple docstring'''
lowerCamelCase_ = []
lowerCamelCase_ = set()
for start in self.connections:
for end in self.connections[start]:
if (start, end) not in seen:
seen.add((end, start) )
edges.append((start, end, self.connections[start][end]) )
edges.sort(key=lambda SCREAMING_SNAKE_CASE_ : x[2] )
# creating the disjoint set
lowerCamelCase_ = DisjointSetTree[T]()
for node in self.connections:
disjoint_set.make_set(SCREAMING_SNAKE_CASE_ )
# MST generation
lowerCamelCase_ = 0
lowerCamelCase_ = 0
lowerCamelCase_ = GraphUndirectedWeighted[T]()
while num_edges < len(self.connections ) - 1:
lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = edges[index]
index += 1
lowerCamelCase_ = disjoint_set.find_set(SCREAMING_SNAKE_CASE_ )
lowerCamelCase_ = disjoint_set.find_set(SCREAMING_SNAKE_CASE_ )
if parent_u != parent_v:
num_edges += 1
graph.add_edge(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
disjoint_set.union(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
return graph
| 384
| 0
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase_ : Dict = {
'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'],
'processing_git': ['GitProcessor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase_ : Optional[Any] = [
'GIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'GitForCausalLM',
'GitModel',
'GitPreTrainedModel',
'GitVisionModel',
]
if TYPE_CHECKING:
from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig
from .processing_git import GitProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_git import (
GIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GitForCausalLM,
GitModel,
GitPreTrainedModel,
GitVisionModel,
)
else:
import sys
UpperCamelCase_ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 461
|
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
snake_case : List[str] = logging.get_logger(__name__)
snake_case : List[str] = {
'microsoft/resnet-50': 'https://huggingface.co/microsoft/resnet-50/blob/main/config.json',
}
class __lowercase ( UpperCamelCase , UpperCamelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = "resnet"
SCREAMING_SNAKE_CASE : List[Any] = ["basic", "bottleneck"]
def __init__( self , A_=3 , A_=64 , A_=[256, 512, 1024, 2048] , A_=[3, 4, 6, 3] , A_="bottleneck" , A_="relu" , A_=False , A_=None , A_=None , **A_ , )-> Union[str, Any]:
super().__init__(**A_ )
if layer_type not in self.layer_types:
raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' )
_SCREAMING_SNAKE_CASE = num_channels
_SCREAMING_SNAKE_CASE = embedding_size
_SCREAMING_SNAKE_CASE = hidden_sizes
_SCREAMING_SNAKE_CASE = depths
_SCREAMING_SNAKE_CASE = layer_type
_SCREAMING_SNAKE_CASE = hidden_act
_SCREAMING_SNAKE_CASE = downsample_in_first_stage
_SCREAMING_SNAKE_CASE = ['stem'] + [F'''stage{idx}''' for idx in range(1 , len(A_ ) + 1 )]
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = get_aligned_output_features_output_indices(
out_features=A_ , out_indices=A_ , stage_names=self.stage_names )
class __lowercase ( UpperCamelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = version.parse("1.11" )
@property
def __magic_name__ ( self )-> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def __magic_name__ ( self )-> float:
return 1e-3
| 605
| 0
|
def UpperCAmelCase_( a__ , a__ ):
"""simple docstring"""
_validate_point(a__ )
_validate_point(a__ )
if len(a__ ) != len(a__ ):
raise ValueError('''Both points must be in the same n-dimensional space''' )
return float(sum(abs(a - b ) for a, b in zip(a__ , a__ ) ) )
def UpperCAmelCase_( a__ ):
"""simple docstring"""
if point:
if isinstance(a__ , a__ ):
for item in point:
if not isinstance(a__ , (int, float) ):
SCREAMING_SNAKE_CASE : Union[str, Any] = (
'''Expected a list of numbers as input, found '''
F"""{type(a__ ).__name__}"""
)
raise TypeError(a__ )
else:
SCREAMING_SNAKE_CASE : str = F"""Expected a list of numbers as input, found {type(a__ ).__name__}"""
raise TypeError(a__ )
else:
raise ValueError('''Missing an input''' )
def UpperCAmelCase_( a__ , a__ ):
"""simple docstring"""
_validate_point(a__ )
_validate_point(a__ )
if len(a__ ) != len(a__ ):
raise ValueError('''Both points must be in the same n-dimensional space''' )
return float(sum(abs(x - y ) for x, y in zip(a__ , a__ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 333
|
def UpperCAmelCase_( a__ ):
"""simple docstring"""
return 10 - x * x
def UpperCAmelCase_( a__ , a__ ):
"""simple docstring"""
if equation(a__ ) * equation(a__ ) >= 0:
raise ValueError('''Wrong space!''' )
SCREAMING_SNAKE_CASE : Union[str, Any] = a
while (b - a) >= 0.01:
# Find middle point
SCREAMING_SNAKE_CASE : Optional[Any] = (a + b) / 2
# Check if middle point is root
if equation(a__ ) == 0.0:
break
# Decide the side to repeat the steps
if equation(a__ ) * equation(a__ ) < 0:
SCREAMING_SNAKE_CASE : Optional[int] = c
else:
SCREAMING_SNAKE_CASE : int = c
return c
if __name__ == "__main__":
import doctest
doctest.testmod()
print(bisection(-2, 5))
print(bisection(0, 6))
| 333
| 1
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
_a : List[Any] = logging.get_logger(__name__)
_a : List[Any] = {
"""google/bit-50""": """https://huggingface.co/google/bit-50/resolve/main/config.json""",
}
class _UpperCAmelCase ( _A , _A ):
"""simple docstring"""
A = '''bit'''
A = ['''preactivation''', '''bottleneck''']
A = ['''SAME''', '''VALID''']
def __init__( self , _lowerCAmelCase=3 , _lowerCAmelCase=64 , _lowerCAmelCase=[256, 512, 1_024, 2_048] , _lowerCAmelCase=[3, 4, 6, 3] , _lowerCAmelCase="preactivation" , _lowerCAmelCase="relu" , _lowerCAmelCase=None , _lowerCAmelCase=32 , _lowerCAmelCase=0.0 , _lowerCAmelCase=False , _lowerCAmelCase=32 , _lowerCAmelCase=1 , _lowerCAmelCase=None , _lowerCAmelCase=None , **_lowerCAmelCase , ):
'''simple docstring'''
super().__init__(**_lowerCAmelCase )
if layer_type not in self.layer_types:
raise ValueError(f'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' )
if global_padding is not None:
if global_padding.upper() in self.supported_padding:
lowerCAmelCase__ :Optional[int] = global_padding.upper()
else:
raise ValueError(f'''Padding strategy {global_padding} not supported''' )
lowerCAmelCase__ :Optional[int] = num_channels
lowerCAmelCase__ :List[str] = embedding_size
lowerCAmelCase__ :Union[str, Any] = hidden_sizes
lowerCAmelCase__ :Union[str, Any] = depths
lowerCAmelCase__ :Optional[Any] = layer_type
lowerCAmelCase__ :Optional[int] = hidden_act
lowerCAmelCase__ :Tuple = global_padding
lowerCAmelCase__ :str = num_groups
lowerCAmelCase__ :Union[str, Any] = drop_path_rate
lowerCAmelCase__ :Tuple = embedding_dynamic_padding
lowerCAmelCase__ :Tuple = output_stride
lowerCAmelCase__ :int = width_factor
lowerCAmelCase__ :str = ["stem"] + [f'''stage{idx}''' for idx in range(1 , len(_lowerCAmelCase ) + 1 )]
lowerCAmelCase__ ,lowerCAmelCase__ :str = get_aligned_output_features_output_indices(
out_features=_lowerCAmelCase , out_indices=_lowerCAmelCase , stage_names=self.stage_names )
| 145
|
from __future__ import annotations
def snake_case__ ( UpperCAmelCase : list[float] , UpperCAmelCase : Any ):
print(F'''Vertex\tShortest Distance from vertex {src}''' )
for i, d in enumerate(UpperCAmelCase ):
print(F'''{i}\t\t{d}''' )
def snake_case__ ( UpperCAmelCase : list[dict[str, int]] , UpperCAmelCase : list[float] , UpperCAmelCase : int ):
for j in range(UpperCAmelCase ):
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ :str = (graph[j][k] for k in ["src", "dst", "weight"])
if distance[u] != float("inf" ) and distance[u] + w < distance[v]:
return True
return False
def snake_case__ ( UpperCAmelCase : list[dict[str, int]] , UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : int ):
lowerCAmelCase__ :int = [float("inf" )] * vertex_count
lowerCAmelCase__ :Optional[int] = 0.0
for _ in range(vertex_count - 1 ):
for j in range(UpperCAmelCase ):
lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ :Dict = (graph[j][k] for k in ["src", "dst", "weight"])
if distance[u] != float("inf" ) and distance[u] + w < distance[v]:
lowerCAmelCase__ :int = distance[u] + w
lowerCAmelCase__ :str = check_negative_cycle(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
if negative_cycle_exists:
raise Exception("Negative cycle found" )
return distance
if __name__ == "__main__":
import doctest
doctest.testmod()
_a : str = int(input("""Enter number of vertices: """).strip())
_a : Optional[int] = int(input("""Enter number of edges: """).strip())
_a : list[dict[str, int]] = [{} for _ in range(E)]
for i in range(E):
print("""Edge """, i + 1)
_a , _a , _a : List[str] = (
int(x)
for x in input("""Enter source, destination, weight: """).strip().split(""" """)
)
_a : int = {"""src""": src, """dst""": dest, """weight""": weight}
_a : Optional[Any] = int(input("""\nEnter shortest path source:""").strip())
_a : Dict = bellman_ford(graph, V, E, source)
print_distance(shortest_distance, 0)
| 145
| 1
|
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from typing import List
from unittest.mock import Mock
import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset
from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A ):
__A : Any = data
def __iter__( self ):
for element in self.data:
yield element
def _SCREAMING_SNAKE_CASE ( a=True ) -> Any:
__A : List[Any] = Accelerator(even_batches=a )
assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
return accelerator
def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str:
if iterable:
__A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) )
else:
__A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) )
__A : Optional[Any] = DataLoader(a , batch_size=a )
__A : Optional[int] = accelerator.prepare(a )
return dl
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]:
__A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a )
__A : Tuple = [len(batch[0] ) for batch in dl]
if accelerator.process_index == 0:
assert batch_sizes == process_0_expected_batch_sizes
elif accelerator.process_index == 1:
assert batch_sizes == process_1_expected_batch_sizes
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__A : int = create_accelerator()
# without padding, we would expect a different number of batches
verify_dataloader_batch_sizes(
a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , )
# without padding, we would expect the same number of batches, but different sizes
verify_dataloader_batch_sizes(
a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , )
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__A : str = create_accelerator(even_batches=a )
verify_dataloader_batch_sizes(
a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , )
verify_dataloader_batch_sizes(
a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , )
def _SCREAMING_SNAKE_CASE ( ) -> str:
__A : Optional[Any] = create_accelerator(even_batches=a )
__A : str = torch.nn.Linear(1 , 1 )
__A : Optional[int] = accelerator.prepare(a )
__A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 )
__A : str = []
with accelerator.join_uneven_inputs([ddp_model] ):
for batch_idx, batch in enumerate(a ):
__A : Dict = ddp_model(batch[0].float() )
__A : List[str] = output.sum()
loss.backward()
batch_idxs.append(a )
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
assert batch_idxs == [0, 1]
elif accelerator.process_index == 1:
assert batch_idxs == [0]
def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]:
with warnings.catch_warnings(record=a ) as w:
with accelerator.join_uneven_inputs([Mock()] ):
pass
assert issubclass(w[-1].category , a )
assert "only supported for multi-GPU" in str(w[-1].message )
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
__A : int = True
__A : Union[str, Any] = False
__A : Optional[int] = create_accelerator(even_batches=a )
__A : int = torch.nn.Linear(1 , 1 )
__A : List[Any] = accelerator.prepare(a )
__A : int = create_dataloader(a , dataset_size=3 , batch_size=1 )
__A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 )
with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ):
__A : List[str] = train_dl.batch_sampler.even_batches
__A : Dict = valid_dl.batch_sampler.even_batches
assert train_dl_overridden_value == overridden_even_batches
assert valid_dl_overridden_value == overridden_even_batches
assert train_dl.batch_sampler.even_batches == default_even_batches
assert valid_dl.batch_sampler.even_batches == default_even_batches
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__A : Any = True
__A : List[Any] = False
__A : Tuple = create_accelerator(even_batches=a )
__A : List[str] = torch.nn.Linear(1 , 1 )
__A : Optional[Any] = accelerator.prepare(a )
create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a )
__A : int = create_dataloader(a , dataset_size=3 , batch_size=1 )
with warnings.catch_warnings():
warnings.filterwarnings('ignore' )
try:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ):
__A : Tuple = batch_dl.batch_sampler.even_batches
except AttributeError:
# ensure attribute error is not raised when processing iterable dl
raise AssertionError
assert batch_dl_overridden_value == overridden_even_batches
assert batch_dl.batch_sampler.even_batches == default_even_batches
def _SCREAMING_SNAKE_CASE ( ) -> Dict:
__A : Any = create_accelerator()
__A : Union[str, Any] = torch.nn.Linear(1 , 1 )
__A : str = accelerator.prepare(a )
create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a )
with warnings.catch_warnings(record=a ) as w:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ):
pass
assert issubclass(w[-1].category , a )
assert "only supported for map-style datasets" in str(w[-1].message )
def _SCREAMING_SNAKE_CASE ( ) -> List[str]:
__A : str = create_accelerator()
accelerator.print('Test that even_batches variable ensures uniform batches across processes' )
test_default_ensures_even_batch_sizes()
accelerator.print('Run tests with even_batches disabled' )
test_can_disable_even_batches()
accelerator.print('Test joining uneven inputs' )
test_can_join_uneven_inputs()
accelerator.print('Test overriding even_batches when joining uneven inputs' )
test_join_can_override_even_batches()
accelerator.print('Test overriding even_batches for mixed dataloader types' )
test_join_can_override_for_mixed_type_dataloaders()
accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' )
test_join_raises_warning_for_iterable_when_overriding_even_batches()
accelerator.print('Test join with non DDP distributed raises warning' )
__A : int = accelerator.state.distributed_type
__A : Tuple = DistributedType.FSDP
test_join_raises_warning_for_non_ddp_distributed(a )
__A : str = original_state
if __name__ == "__main__":
main()
| 77
|
import unittest
from accelerate import debug_launcher
from accelerate.test_utils import require_cpu, test_ops, test_script
@require_cpu
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
debug_launcher(test_script.main )
def UpperCAmelCase_ ( self ):
debug_launcher(test_ops.main )
| 77
| 1
|
import shutil
import tempfile
import unittest
import numpy as np
from transformers.testing_utils import (
is_pt_tf_cross_test,
require_tf,
require_torch,
require_torchvision,
require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, SamImageProcessor, SamProcessor
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
@require_vision
@require_torchvision
class __snake_case ( unittest.TestCase ):
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : List[str] = tempfile.mkdtemp()
lowercase : Union[str, Any] = SamImageProcessor()
lowercase : Tuple = SamProcessor(snake_case )
processor.save_pretrained(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self ,**snake_case ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname ,**snake_case ).image_processor
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : int = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )]
lowercase : Optional[Any] = [Image.fromarray(np.moveaxis(snake_case ,0 ,-1 ) ) for x in image_inputs]
return image_inputs
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : str = SamProcessor(image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowercase : Any = self.get_image_processor(do_normalize=snake_case ,padding_value=1.0 )
lowercase : Tuple = SamProcessor.from_pretrained(self.tmpdirname ,do_normalize=snake_case ,padding_value=1.0 )
self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor ,snake_case )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Any = self.get_image_processor()
lowercase : Tuple = SamProcessor(image_processor=snake_case )
lowercase : List[Any] = self.prepare_image_inputs()
lowercase : Optional[int] = image_processor(snake_case ,return_tensors="""np""" )
lowercase : Optional[Any] = processor(images=snake_case ,return_tensors="""np""" )
input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor
input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 )
@require_torch
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Any = self.get_image_processor()
lowercase : int = SamProcessor(image_processor=snake_case )
lowercase : Optional[Any] = [torch.ones((1, 3, 5, 5) )]
lowercase : Any = [[1764, 2646]]
lowercase : int = [[683, 1024]]
lowercase : Any = processor.post_process_masks(snake_case ,snake_case ,snake_case )
self.assertEqual(masks[0].shape ,(1, 3, 1764, 2646) )
lowercase : str = processor.post_process_masks(
snake_case ,torch.tensor(snake_case ) ,torch.tensor(snake_case ) )
self.assertEqual(masks[0].shape ,(1, 3, 1764, 2646) )
# should also work with np
lowercase : Union[str, Any] = [np.ones((1, 3, 5, 5) )]
lowercase : Any = processor.post_process_masks(snake_case ,np.array(snake_case ) ,np.array(snake_case ) )
self.assertEqual(masks[0].shape ,(1, 3, 1764, 2646) )
lowercase : List[str] = [[1, 0], [0, 1]]
with self.assertRaises(snake_case ):
lowercase : int = processor.post_process_masks(snake_case ,np.array(snake_case ) ,np.array(snake_case ) )
@require_vision
@require_tf
class __snake_case ( unittest.TestCase ):
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : List[Any] = tempfile.mkdtemp()
lowercase : Dict = SamImageProcessor()
lowercase : int = SamProcessor(snake_case )
processor.save_pretrained(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self ,**snake_case ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname ,**snake_case ).image_processor
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Optional[Any] = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )]
lowercase : Optional[Any] = [Image.fromarray(np.moveaxis(snake_case ,0 ,-1 ) ) for x in image_inputs]
return image_inputs
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Dict = SamProcessor(image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
lowercase : Dict = self.get_image_processor(do_normalize=snake_case ,padding_value=1.0 )
lowercase : List[Any] = SamProcessor.from_pretrained(self.tmpdirname ,do_normalize=snake_case ,padding_value=1.0 )
self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor ,snake_case )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : List[Any] = self.get_image_processor()
lowercase : Any = SamProcessor(image_processor=snake_case )
lowercase : Any = self.prepare_image_inputs()
lowercase : List[str] = image_processor(snake_case ,return_tensors="""np""" )
lowercase : Optional[Any] = processor(images=snake_case ,return_tensors="""np""" )
input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor
input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1e-2 )
@require_tf
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Tuple = self.get_image_processor()
lowercase : Optional[int] = SamProcessor(image_processor=snake_case )
lowercase : Dict = [tf.ones((1, 3, 5, 5) )]
lowercase : List[Any] = [[1764, 2646]]
lowercase : Any = [[683, 1024]]
lowercase : Any = processor.post_process_masks(snake_case ,snake_case ,snake_case ,return_tensors="""tf""" )
self.assertEqual(masks[0].shape ,(1, 3, 1764, 2646) )
lowercase : str = processor.post_process_masks(
snake_case ,tf.convert_to_tensor(snake_case ) ,tf.convert_to_tensor(snake_case ) ,return_tensors="""tf""" ,)
self.assertEqual(masks[0].shape ,(1, 3, 1764, 2646) )
# should also work with np
lowercase : Optional[int] = [np.ones((1, 3, 5, 5) )]
lowercase : Union[str, Any] = processor.post_process_masks(
snake_case ,np.array(snake_case ) ,np.array(snake_case ) ,return_tensors="""tf""" )
self.assertEqual(masks[0].shape ,(1, 3, 1764, 2646) )
lowercase : int = [[1, 0], [0, 1]]
with self.assertRaises(tf.errors.InvalidArgumentError ):
lowercase : Union[str, Any] = processor.post_process_masks(
snake_case ,np.array(snake_case ) ,np.array(snake_case ) ,return_tensors="""tf""" )
@require_vision
@require_torchvision
class __snake_case ( unittest.TestCase ):
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Dict = tempfile.mkdtemp()
lowercase : Dict = SamImageProcessor()
lowercase : Union[str, Any] = SamProcessor(snake_case )
processor.save_pretrained(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self ,**snake_case ):
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname ,**snake_case ).image_processor
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Dict = [np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )]
lowercase : List[str] = [Image.fromarray(np.moveaxis(snake_case ,0 ,-1 ) ) for x in image_inputs]
return image_inputs
@is_pt_tf_cross_test
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Optional[int] = self.get_image_processor()
lowercase : int = SamProcessor(image_processor=snake_case )
lowercase : Optional[Any] = np.random.randint(0 ,2 ,size=(1, 3, 5, 5) ).astype(np.floataa )
lowercase : Optional[int] = [tf.convert_to_tensor(snake_case )]
lowercase : Optional[int] = [torch.tensor(snake_case )]
lowercase : Optional[Any] = [[1764, 2646]]
lowercase : List[Any] = [[683, 1024]]
lowercase : Any = processor.post_process_masks(
snake_case ,snake_case ,snake_case ,return_tensors="""tf""" )
lowercase : Optional[int] = processor.post_process_masks(
snake_case ,snake_case ,snake_case ,return_tensors="""pt""" )
self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) )
@is_pt_tf_cross_test
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowercase : Tuple = self.get_image_processor()
lowercase : List[Any] = SamProcessor(image_processor=snake_case )
lowercase : Dict = self.prepare_image_inputs()
lowercase : List[str] = image_processor(snake_case ,return_tensors="""pt""" )["""pixel_values"""].numpy()
lowercase : int = processor(images=snake_case ,return_tensors="""pt""" )["""pixel_values"""].numpy()
lowercase : List[Any] = image_processor(snake_case ,return_tensors="""tf""" )["""pixel_values"""].numpy()
lowercase : str = processor(images=snake_case ,return_tensors="""tf""" )["""pixel_values"""].numpy()
self.assertTrue(np.allclose(snake_case ,snake_case ) )
self.assertTrue(np.allclose(snake_case ,snake_case ) )
self.assertTrue(np.allclose(snake_case ,snake_case ) )
| 336
|
"""simple docstring"""
from typing import Optional
import pyspark
from .. import Features, NamedSplit
from ..download import DownloadMode
from ..packaged_modules.spark.spark import Spark
from .abc import AbstractDatasetReader
class __a ( __snake_case ):
def __init__( self , UpperCAmelCase , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = True , UpperCAmelCase = None , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = True , UpperCAmelCase = "arrow" , **UpperCAmelCase , ):
'''simple docstring'''
super().__init__(
split=UpperCAmelCase , features=UpperCAmelCase , cache_dir=UpperCAmelCase , keep_in_memory=UpperCAmelCase , streaming=UpperCAmelCase , **UpperCAmelCase , )
lowerCAmelCase_ = load_from_cache_file
lowerCAmelCase_ = file_format
lowerCAmelCase_ = Spark(
df=UpperCAmelCase , features=UpperCAmelCase , cache_dir=UpperCAmelCase , working_dir=UpperCAmelCase , **UpperCAmelCase , )
def lowerCamelCase_ ( self ):
'''simple docstring'''
if self.streaming:
return self.builder.as_streaming_dataset(split=self.split )
lowerCAmelCase_ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD
self.builder.download_and_prepare(
download_mode=UpperCAmelCase , file_format=self._file_format , )
return self.builder.as_dataset(split=self.split )
| 552
| 0
|
"""simple docstring"""
import re
import time
from typing import Optional
import IPython.display as disp
from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def snake_case__ ( __lowerCamelCase : Any ):
"""simple docstring"""
lowerCamelCase__ : Tuple =int(__lowerCamelCase )
lowerCamelCase__ : Dict =t // 3600, (t // 60) % 60, t % 60
return f'''{h}:{m:02d}:{s:02d}''' if h != 0 else f'''{m:02d}:{s:02d}'''
def snake_case__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : Dict=300 ):
"""simple docstring"""
return f'''
<div>
{prefix}
<progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
{label}
</div>
'''
def snake_case__ ( __lowerCamelCase : Tuple ):
"""simple docstring"""
lowerCamelCase__ : List[str] ='''<table border="1" class="dataframe">\n'''
html_code += """ <thead>\n <tr style="text-align: left;">\n"""
for i in items[0]:
html_code += f''' <th>{i}</th>\n'''
html_code += " </tr>\n </thead>\n <tbody>\n"
for line in items[1:]:
html_code += " <tr>\n"
for elt in line:
lowerCamelCase__ : Any =f'''{elt:.6f}''' if isinstance(__lowerCamelCase , __lowerCamelCase ) else str(__lowerCamelCase )
html_code += f''' <td>{elt}</td>\n'''
html_code += " </tr>\n"
html_code += " </tbody>\n</table><p>"
return html_code
class __SCREAMING_SNAKE_CASE :
'''simple docstring'''
_a = 5
_a = 0.2
def __init__( self : Any, lowerCamelCase : int, lowerCamelCase : Optional[str] = None, lowerCamelCase : bool = True, lowerCamelCase : Optional["NotebookTrainingTracker"] = None, lowerCamelCase : int = 300, )-> Tuple:
lowerCamelCase__ : List[Any] =total
lowerCamelCase__ : int ='''''' if prefix is None else prefix
lowerCamelCase__ : Dict =leave
lowerCamelCase__ : Any =parent
lowerCamelCase__ : Dict =width
lowerCamelCase__ : str =None
lowerCamelCase__ : str =None
lowerCamelCase__ : Tuple =None
def snake_case ( self : Optional[int], lowerCamelCase : int, lowerCamelCase : bool = False, lowerCamelCase : str = None )-> List[str]:
lowerCamelCase__ : Dict =value
if comment is not None:
lowerCamelCase__ : Optional[int] =comment
if self.last_value is None:
lowerCamelCase__ : str =time.time()
lowerCamelCase__ : Optional[Any] =value
lowerCamelCase__ : List[Any] =None
lowerCamelCase__ : Dict =self.warmup
lowerCamelCase__ : Tuple =1
self.update_bar(lowerCamelCase )
elif value <= self.last_value and not force_update:
return
elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total ):
if self.first_calls > 0:
self.first_calls -= 1
lowerCamelCase__ : Optional[Any] =time.time()
lowerCamelCase__ : Optional[Any] =current_time - self.start_time
# We could have value = self.start_value if the update is called twixe with the same start value.
if value > self.start_value:
lowerCamelCase__ : Optional[Any] =self.elapsed_time / (value - self.start_value)
else:
lowerCamelCase__ : Tuple =None
if value >= self.total:
lowerCamelCase__ : Dict =self.total
lowerCamelCase__ : Tuple =None
if not self.leave:
self.close()
elif self.average_time_per_item is not None:
lowerCamelCase__ : List[Any] =self.average_time_per_item * (self.total - value)
self.update_bar(lowerCamelCase )
lowerCamelCase__ : Any =value
lowerCamelCase__ : List[str] =current_time
if self.average_time_per_item is None:
lowerCamelCase__ : str =1
else:
lowerCamelCase__ : str =max(int(self.update_every / self.average_time_per_item ), 1 )
def snake_case ( self : List[str], lowerCamelCase : int, lowerCamelCase : Dict=None )-> Optional[int]:
lowerCamelCase__ : int =''' ''' * (len(str(self.total ) ) - len(str(lowerCamelCase ) )) + str(lowerCamelCase )
if self.elapsed_time is None:
lowerCamelCase__ : Optional[int] =F'''[{spaced_value}/{self.total} : < :'''
elif self.predicted_remaining is None:
lowerCamelCase__ : Optional[Any] =F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time )}'''
else:
lowerCamelCase__ : Dict =(
F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <'''
F''' {format_time(self.predicted_remaining )}'''
)
self.label += F''', {1/self.average_time_per_item:.2f} it/s'''
self.label += "]" if self.comment is None or len(self.comment ) == 0 else F''', {self.comment}]'''
self.display()
def snake_case ( self : List[Any] )-> str:
lowerCamelCase__ : Optional[int] =html_progress_bar(self.value, self.total, self.prefix, self.label, self.width )
if self.parent is not None:
# If this is a child bar, the parent will take care of the display.
self.parent.display()
return
if self.output is None:
lowerCamelCase__ : Tuple =disp.display(disp.HTML(self.html_code ), display_id=lowerCamelCase )
else:
self.output.update(disp.HTML(self.html_code ) )
def snake_case ( self : Union[str, Any] )-> Any:
if self.parent is None and self.output is not None:
self.output.update(disp.HTML('''''' ) )
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
'''simple docstring'''
def __init__( self : Any, lowerCamelCase : Optional[int], lowerCamelCase : Union[str, Any]=None )-> str:
super().__init__(lowerCamelCase )
lowerCamelCase__ : List[Any] =None if column_names is None else [column_names]
lowerCamelCase__ : Tuple =None
def snake_case ( self : int )-> int:
lowerCamelCase__ : Union[str, Any] =html_progress_bar(self.value, self.total, self.prefix, self.label, self.width )
if self.inner_table is not None:
self.html_code += text_to_html_table(self.inner_table )
if self.child_bar is not None:
self.html_code += self.child_bar.html_code
if self.output is None:
lowerCamelCase__ : Union[str, Any] =disp.display(disp.HTML(self.html_code ), display_id=lowerCamelCase )
else:
self.output.update(disp.HTML(self.html_code ) )
def snake_case ( self : List[Any], lowerCamelCase : Any )-> Optional[int]:
if self.inner_table is None:
lowerCamelCase__ : List[str] =[list(values.keys() ), list(values.values() )]
else:
lowerCamelCase__ : Tuple =self.inner_table[0]
if len(self.inner_table ) == 1:
# We give a chance to update the column names at the first iteration
for key in values.keys():
if key not in columns:
columns.append(lowerCamelCase )
lowerCamelCase__ : List[str] =columns
self.inner_table.append([values[c] for c in columns] )
def snake_case ( self : str, lowerCamelCase : Optional[Any], lowerCamelCase : Optional[int]=None, lowerCamelCase : Tuple=300 )-> List[Any]:
lowerCamelCase__ : Optional[Any] =NotebookProgressBar(lowerCamelCase, prefix=lowerCamelCase, parent=self, width=lowerCamelCase )
return self.child_bar
def snake_case ( self : Union[str, Any] )-> List[str]:
lowerCamelCase__ : List[str] =None
self.display()
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
'''simple docstring'''
def __init__( self : Optional[int] )-> Dict:
lowerCamelCase__ : Optional[int] =None
lowerCamelCase__ : List[Any] =None
lowerCamelCase__ : Dict =False
def snake_case ( self : int, lowerCamelCase : Optional[int], lowerCamelCase : int, lowerCamelCase : Tuple, **lowerCamelCase : List[Any] )-> List[str]:
lowerCamelCase__ : Optional[int] ='''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step'''
lowerCamelCase__ : Union[str, Any] =0
lowerCamelCase__ : Tuple =0
lowerCamelCase__ : List[Any] =[self.first_column] + ['''Training Loss''']
if args.evaluation_strategy != IntervalStrategy.NO:
column_names.append('''Validation Loss''' )
lowerCamelCase__ : List[str] =NotebookTrainingTracker(state.max_steps, lowerCamelCase )
def snake_case ( self : str, lowerCamelCase : Any, lowerCamelCase : Dict, lowerCamelCase : Optional[Any], **lowerCamelCase : Union[str, Any] )-> List[str]:
lowerCamelCase__ : Optional[int] =int(state.epoch ) if int(state.epoch ) == state.epoch else F'''{state.epoch:.2f}'''
self.training_tracker.update(
state.global_step + 1, comment=F'''Epoch {epoch}/{state.num_train_epochs}''', force_update=self._force_next_update, )
lowerCamelCase__ : Optional[Any] =False
def snake_case ( self : Any, lowerCamelCase : Dict, lowerCamelCase : Dict, lowerCamelCase : int, lowerCamelCase : Union[str, Any]=None, **lowerCamelCase : List[Any] )-> Optional[int]:
if not has_length(lowerCamelCase ):
return
if self.prediction_bar is None:
if self.training_tracker is not None:
lowerCamelCase__ : Any =self.training_tracker.add_child(len(lowerCamelCase ) )
else:
lowerCamelCase__ : str =NotebookProgressBar(len(lowerCamelCase ) )
self.prediction_bar.update(1 )
else:
self.prediction_bar.update(self.prediction_bar.value + 1 )
def snake_case ( self : List[Any], lowerCamelCase : Any, lowerCamelCase : Any, lowerCamelCase : str, **lowerCamelCase : List[Any] )-> Union[str, Any]:
if self.prediction_bar is not None:
self.prediction_bar.close()
lowerCamelCase__ : List[Any] =None
def snake_case ( self : List[Any], lowerCamelCase : Optional[Any], lowerCamelCase : Dict, lowerCamelCase : Optional[int], lowerCamelCase : List[Any]=None, **lowerCamelCase : Dict )-> List[Any]:
# Only for when there is no evaluation
if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
lowerCamelCase__ : Dict ={'''Training Loss''': logs['''loss''']}
# First column is necessarily Step sine we're not in epoch eval strategy
lowerCamelCase__ : Tuple =state.global_step
self.training_tracker.write_line(lowerCamelCase )
def snake_case ( self : Dict, lowerCamelCase : int, lowerCamelCase : Optional[Any], lowerCamelCase : Union[str, Any], lowerCamelCase : Union[str, Any]=None, **lowerCamelCase : Optional[int] )-> Optional[int]:
if self.training_tracker is not None:
lowerCamelCase__ : str ={'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''}
for log in reversed(state.log_history ):
if "loss" in log:
lowerCamelCase__ : Any =log['''loss''']
break
if self.first_column == "Epoch":
lowerCamelCase__ : str =int(state.epoch )
else:
lowerCamelCase__ : List[Any] =state.global_step
lowerCamelCase__ : List[Any] ='''eval'''
for k in metrics:
if k.endswith('''_loss''' ):
lowerCamelCase__ : str =re.sub(r'''\_loss$''', '''''', lowerCamelCase )
lowerCamelCase__ : Dict =metrics.pop('''total_flos''', lowerCamelCase )
lowerCamelCase__ : Union[str, Any] =metrics.pop('''epoch''', lowerCamelCase )
lowerCamelCase__ : str =metrics.pop(F'''{metric_key_prefix}_runtime''', lowerCamelCase )
lowerCamelCase__ : Tuple =metrics.pop(F'''{metric_key_prefix}_samples_per_second''', lowerCamelCase )
lowerCamelCase__ : Optional[Any] =metrics.pop(F'''{metric_key_prefix}_steps_per_second''', lowerCamelCase )
lowerCamelCase__ : Any =metrics.pop(F'''{metric_key_prefix}_jit_compilation_time''', lowerCamelCase )
for k, v in metrics.items():
if k == F'''{metric_key_prefix}_loss''':
lowerCamelCase__ : Any =v
else:
lowerCamelCase__ : List[Any] =k.split('''_''' )
lowerCamelCase__ : Tuple =''' '''.join([part.capitalize() for part in splits[1:]] )
lowerCamelCase__ : List[str] =v
self.training_tracker.write_line(lowerCamelCase )
self.training_tracker.remove_child()
lowerCamelCase__ : List[Any] =None
# Evaluation takes a long time so we should force the next update.
lowerCamelCase__ : Union[str, Any] =True
def snake_case ( self : List[str], lowerCamelCase : List[str], lowerCamelCase : Optional[int], lowerCamelCase : str, **lowerCamelCase : str )-> Union[str, Any]:
self.training_tracker.update(
state.global_step, comment=F'''Epoch {int(state.epoch )}/{state.num_train_epochs}''', force_update=lowerCamelCase )
lowerCamelCase__ : int =None
| 717
|
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
@require_tf
class __SCREAMING_SNAKE_CASE :
'''simple docstring'''
_a = BlenderbotSmallConfig
_a = {}
_a = 'gelu'
def __init__( self : Union[str, Any], lowerCamelCase : List[str], lowerCamelCase : Dict=13, lowerCamelCase : Optional[Any]=7, lowerCamelCase : Optional[int]=True, lowerCamelCase : int=False, lowerCamelCase : Union[str, Any]=99, lowerCamelCase : str=32, lowerCamelCase : List[Any]=2, lowerCamelCase : Optional[int]=4, lowerCamelCase : Union[str, Any]=37, lowerCamelCase : str=0.1, lowerCamelCase : Optional[int]=0.1, lowerCamelCase : Optional[Any]=20, lowerCamelCase : int=2, lowerCamelCase : Any=1, lowerCamelCase : Optional[Any]=0, )-> List[str]:
lowerCamelCase__ : Any =parent
lowerCamelCase__ : Dict =batch_size
lowerCamelCase__ : Optional[int] =seq_length
lowerCamelCase__ : Tuple =is_training
lowerCamelCase__ : Dict =use_labels
lowerCamelCase__ : List[Any] =vocab_size
lowerCamelCase__ : str =hidden_size
lowerCamelCase__ : str =num_hidden_layers
lowerCamelCase__ : Union[str, Any] =num_attention_heads
lowerCamelCase__ : Any =intermediate_size
lowerCamelCase__ : Dict =hidden_dropout_prob
lowerCamelCase__ : List[Any] =attention_probs_dropout_prob
lowerCamelCase__ : str =max_position_embeddings
lowerCamelCase__ : Optional[int] =eos_token_id
lowerCamelCase__ : str =pad_token_id
lowerCamelCase__ : Union[str, Any] =bos_token_id
def snake_case ( self : Any )-> Any:
lowerCamelCase__ : Any =ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size )
lowerCamelCase__ : Tuple =tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ), 1 )
lowerCamelCase__ : Any =tf.concat([input_ids, eos_tensor], axis=1 )
lowerCamelCase__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length], self.vocab_size )
lowerCamelCase__ : int =self.config_cls(
vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, )
lowerCamelCase__ : Optional[int] =prepare_blenderbot_small_inputs_dict(lowerCamelCase, lowerCamelCase, lowerCamelCase )
return config, inputs_dict
def snake_case ( self : Any, lowerCamelCase : str, lowerCamelCase : Any )-> Optional[Any]:
lowerCamelCase__ : Union[str, Any] =TFBlenderbotSmallModel(config=lowerCamelCase ).get_decoder()
lowerCamelCase__ : List[Any] =inputs_dict['''input_ids''']
lowerCamelCase__ : Optional[int] =input_ids[:1, :]
lowerCamelCase__ : str =inputs_dict['''attention_mask'''][:1, :]
lowerCamelCase__ : Union[str, Any] =inputs_dict['''head_mask''']
lowerCamelCase__ : Optional[Any] =1
# first forward pass
lowerCamelCase__ : Dict =model(lowerCamelCase, attention_mask=lowerCamelCase, head_mask=lowerCamelCase, use_cache=lowerCamelCase )
lowerCamelCase__ , lowerCamelCase__ : List[str] =outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
lowerCamelCase__ : Union[str, Any] =ids_tensor((self.batch_size, 3), config.vocab_size )
lowerCamelCase__ : Tuple =tf.cast(ids_tensor((self.batch_size, 3), 2 ), tf.inta )
# append to next input_ids and
lowerCamelCase__ : List[str] =tf.concat([input_ids, next_tokens], axis=-1 )
lowerCamelCase__ : str =tf.concat([attention_mask, next_attn_mask], axis=-1 )
lowerCamelCase__ : Optional[int] =model(lowerCamelCase, attention_mask=lowerCamelCase )[0]
lowerCamelCase__ : Union[str, Any] =model(lowerCamelCase, attention_mask=lowerCamelCase, past_key_values=lowerCamelCase )[0]
self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1] )
# select random slice
lowerCamelCase__ : Tuple =int(ids_tensor((1,), output_from_past.shape[-1] ) )
lowerCamelCase__ : int =output_from_no_past[:, -3:, random_slice_idx]
lowerCamelCase__ : List[str] =output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(lowerCamelCase, lowerCamelCase, rtol=1E-3 )
def snake_case__ ( __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any=None , __lowerCamelCase : List[str]=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Optional[int]=None , ):
"""simple docstring"""
if attention_mask is None:
lowerCamelCase__ : List[str] =tf.cast(tf.math.not_equal(__lowerCamelCase , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
lowerCamelCase__ : str =tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ),
] , axis=-1 , )
if head_mask is None:
lowerCamelCase__ : int =tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
lowerCamelCase__ : int =tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
lowerCamelCase__ : List[str] =tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ):
'''simple docstring'''
_a = (
(TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
)
_a = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
_a = (
{
'conversational': TFBlenderbotSmallForConditionalGeneration,
'feature-extraction': TFBlenderbotSmallModel,
'summarization': TFBlenderbotSmallForConditionalGeneration,
'text2text-generation': TFBlenderbotSmallForConditionalGeneration,
'translation': TFBlenderbotSmallForConditionalGeneration,
}
if is_tf_available()
else {}
)
_a = True
_a = False
_a = False
def snake_case ( self : Any )-> str:
lowerCamelCase__ : Tuple =TFBlenderbotSmallModelTester(self )
lowerCamelCase__ : Union[str, Any] =ConfigTester(self, config_class=lowerCamelCase )
def snake_case ( self : Any )-> Optional[int]:
self.config_tester.run_common_tests()
def snake_case ( self : int )-> str:
lowerCamelCase__ : List[Any] =self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*lowerCamelCase )
@require_tokenizers
@require_tf
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
_a = [
'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like '
' i\'m going to throw up.\nand why is that?'
]
_a = 'facebook/blenderbot_small-90M'
@cached_property
def snake_case ( self : Any )-> List[Any]:
# use "old" tokenizer here because of bug when downloading new tokenizer
return BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' )
@cached_property
def snake_case ( self : int )-> List[Any]:
lowerCamelCase__ : str =TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
@slow
def snake_case ( self : Tuple )-> int:
lowerCamelCase__ : Dict =self.tokenizer(self.src_text, return_tensors='''tf''' )
lowerCamelCase__ : Any =self.model.generate(
model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=lowerCamelCase, )
lowerCamelCase__ : Any =self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=lowerCamelCase )[0]
assert generated_words in (
"i don't know. i just feel like i'm going to throw up. it's not fun.",
"i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
"i'm not sure. i just feel like i've been in a bad situation.",
)
| 625
| 0
|
import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional
import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors
import transformers
from transformers import (
AutoConfig,
AutoModelForMultipleChoice,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
__A : Any = logging.getLogger(__name__)
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
return (preds == labels).mean()
@dataclass
class lowerCamelCase:
'''simple docstring'''
__magic_name__ = field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
__magic_name__ = field(
default=__snake_case , metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
__magic_name__ = field(
default=__snake_case , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} )
__magic_name__ = field(
default=__snake_case , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
@dataclass
class lowerCamelCase:
'''simple docstring'''
__magic_name__ = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} )
__magic_name__ = field(metadata={'help': 'Should contain the data files for the task.'} )
__magic_name__ = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
__magic_name__ = field(
default=__snake_case , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
def __lowerCAmelCase( ) -> Union[str, Any]:
"""simple docstring"""
_A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
_A, _A, _A = parser.parse_args_into_dataclasses()
if (
os.path.exists(training_args.output_dir )
and os.listdir(training_args.output_dir )
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
F"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
' --overwrite_output_dir to overcome.' )
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , )
logger.warning(
'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , )
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info('Training/evaluation parameters %s' , _SCREAMING_SNAKE_CASE )
# Set seed
set_seed(training_args.seed )
try:
_A = processors[data_args.task_name]()
_A = processor.get_labels()
_A = len(_SCREAMING_SNAKE_CASE )
except KeyError:
raise ValueError('Task not found: %s' % (data_args.task_name) )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
_A = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_SCREAMING_SNAKE_CASE , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , )
_A = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
_A = AutoModelForMultipleChoice.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , )
# Get datasets
_A = (
MultipleChoiceDataset(
data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , )
if training_args.do_train
else None
)
_A = (
MultipleChoiceDataset(
data_dir=data_args.data_dir , tokenizer=_SCREAMING_SNAKE_CASE , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , )
if training_args.do_eval
else None
)
def compute_metrics(_SCREAMING_SNAKE_CASE ) -> Dict:
_A = np.argmax(p.predictions , axis=1 )
return {"acc": simple_accuracy(_SCREAMING_SNAKE_CASE , p.label_ids )}
# Data collator
_A = DataCollatorWithPadding(_SCREAMING_SNAKE_CASE , pad_to_multiple_of=8 ) if training_args.fpaa else None
# Initialize our Trainer
_A = Trainer(
model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=_SCREAMING_SNAKE_CASE , eval_dataset=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , data_collator=_SCREAMING_SNAKE_CASE , )
# Training
if training_args.do_train:
trainer.train(
model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None )
trainer.save_model()
# For convenience, we also re-save the tokenizer to the same directory,
# so that you can share your model easily on huggingface.co/models =)
if trainer.is_world_master():
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
_A = {}
if training_args.do_eval:
logger.info('*** Evaluate ***' )
_A = trainer.evaluate()
_A = os.path.join(training_args.output_dir , 'eval_results.txt' )
if trainer.is_world_master():
with open(_SCREAMING_SNAKE_CASE , 'w' ) as writer:
logger.info('***** Eval results *****' )
for key, value in result.items():
logger.info(' %s = %s' , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
writer.write('%s = %s\n' % (key, value) )
results.update(_SCREAMING_SNAKE_CASE )
return results
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
main()
if __name__ == "__main__":
main()
| 27
|
def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> float:
"""simple docstring"""
return price * (1 + tax_rate)
if __name__ == "__main__":
print(f"{price_plus_tax(100, 0.2_5) = }")
print(f"{price_plus_tax(1_2_5.5_0, 0.0_5) = }")
| 27
| 1
|
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings
lowercase : int = r"""
[`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and
can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args:
title_sep (`str`, *optional*, defaults to `\" / \"`):
Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].
doc_sep (`str`, *optional*, defaults to `\" // \"`):
Separator inserted between the text of the retrieved document and the original input when calling
[`RagRetriever`].
n_docs (`int`, *optional*, defaults to 5):
Number of documents to retrieve.
max_combined_length (`int`, *optional*, defaults to 300):
Max length of contextualized input returned by [`~RagRetriever.__call__`].
retrieval_vector_size (`int`, *optional*, defaults to 768):
Dimensionality of the document embeddings indexed by [`RagRetriever`].
retrieval_batch_size (`int`, *optional*, defaults to 8):
Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated
[`RagRetriever`].
dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):
A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids
using `datasets.list_datasets()`).
dataset_split (`str`, *optional*, defaults to `\"train\"`)
Which split of the `dataset` to load.
index_name (`str`, *optional*, defaults to `\"compressed\"`)
The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and
`\"compressed\"`.
index_path (`str`, *optional*)
The path to the serialized faiss index on disk.
passages_path (`str`, *optional*):
A path to text passages compatible with the faiss index. Required if using
[`~models.rag.retrieval_rag.LegacyIndex`]
use_dummy_dataset (`bool`, *optional*, defaults to `False`)
Whether to load a \"dummy\" variant of the dataset specified by `dataset`.
label_smoothing (`float`, *optional*, defaults to 0.0):
Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing
in the loss calculation. If set to 0, no label smoothing is performed.
do_marginalize (`bool`, *optional*, defaults to `False`):
If `True`, the logits are marginalized over all documents by making use of
`torch.nn.functional.log_softmax`.
reduce_loss (`bool`, *optional*, defaults to `False`):
Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.
do_deduplication (`bool`, *optional*, defaults to `True`):
Whether or not to deduplicate the generations from different context documents for a given input. Has to be
set to `False` if used while training with distributed backend.
exclude_bos_score (`bool`, *optional*, defaults to `False`):
Whether or not to disregard the BOS token when computing the loss.
output_retrieved(`bool`, *optional*, defaults to `False`):
If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
`context_attention_mask` are returned. See returned tensors for more detail.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models).
forced_eos_token_id (`int`, *optional*):
The id of the token to force as the last generated token when `max_length` is reached. Usually set to
`eos_token_id`.
"""
@add_start_docstrings(__UpperCAmelCase )
class A__ ( __UpperCAmelCase ):
"""simple docstring"""
__A : Dict = '''rag'''
__A : Dict = True
def __init__( self , lowercase=None , lowercase=True , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=" / " , lowercase=" // " , lowercase=5 , lowercase=300 , lowercase=768 , lowercase=8 , lowercase="wiki_dpr" , lowercase="train" , lowercase="compressed" , lowercase=None , lowercase=None , lowercase=False , lowercase=False , lowercase=0.0 , lowercase=True , lowercase=False , lowercase=False , lowercase=False , lowercase=True , lowercase=None , **lowercase , ) -> List[str]:
'''simple docstring'''
super().__init__(
bos_token_id=lowercase , pad_token_id=lowercase , eos_token_id=lowercase , decoder_start_token_id=lowercase , forced_eos_token_id=lowercase , is_encoder_decoder=lowercase , prefix=lowercase , vocab_size=lowercase , **lowercase , )
assert (
"question_encoder" in kwargs and "generator" in kwargs
), "Config has to be initialized with question_encoder and generator config"
a__ : str = kwargs.pop('question_encoder')
a__ : Tuple = question_encoder_config.pop('model_type')
a__ : int = kwargs.pop('generator')
a__ : int = decoder_config.pop('model_type')
from ..auto.configuration_auto import AutoConfig
a__ : Any = AutoConfig.for_model(lowercase , **lowercase)
a__ : Optional[int] = AutoConfig.for_model(lowercase , **lowercase)
a__ : Any = reduce_loss
a__ : List[str] = label_smoothing
a__ : Any = exclude_bos_score
a__ : Dict = do_marginalize
a__ : str = title_sep
a__ : Tuple = doc_sep
a__ : Optional[Any] = n_docs
a__ : Tuple = max_combined_length
a__ : str = dataset
a__ : List[str] = dataset_split
a__ : Any = index_name
a__ : Optional[int] = retrieval_vector_size
a__ : str = retrieval_batch_size
a__ : Optional[Any] = passages_path
a__ : List[Any] = index_path
a__ : Optional[Any] = use_dummy_dataset
a__ : Optional[int] = output_retrieved
a__ : List[Any] = do_deduplication
a__ : int = use_cache
if self.forced_eos_token_id is None:
a__ : Any = getattr(self.generator , 'forced_eos_token_id' , lowercase)
@classmethod
def __lowercase ( cls , lowercase , lowercase , **lowercase) -> PretrainedConfig:
'''simple docstring'''
return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **lowercase)
def __lowercase ( self) -> str:
'''simple docstring'''
a__ : str = copy.deepcopy(self.__dict__)
a__ : List[Any] = self.question_encoder.to_dict()
a__ : Union[str, Any] = self.generator.to_dict()
a__ : str = self.__class__.model_type
return output
| 392
|
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow
if is_torch_available():
import torch
from transformers import XLMRobertaModel
@require_sentencepiece
@require_tokenizers
@require_torch
class A__ ( unittest.TestCase ):
"""simple docstring"""
@slow
def __lowercase ( self) -> str:
'''simple docstring'''
a__ : int = XLMRobertaModel.from_pretrained('xlm-roberta-base')
a__ : Optional[Any] = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]])
# The dog is cute and lives in the garden house
a__ : int = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim
a__ : int = torch.tensor(
[[-0.01_01, 0.12_18, -0.08_03, 0.08_01, 0.13_27, 0.07_76, -0.12_15, 0.23_83, 0.33_38, 0.31_06, 0.03_00, 0.02_52]])
# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')
# xlmr.eval()
# expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
with torch.no_grad():
a__ : Tuple = model(lowercase)['last_hidden_state'].detach()
self.assertEqual(output.shape , lowercase)
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1] , lowercase , atol=1e-3))
@slow
def __lowercase ( self) -> Tuple:
'''simple docstring'''
a__ : Dict = XLMRobertaModel.from_pretrained('xlm-roberta-large')
a__ : str = torch.tensor([[0, 581, 1_0269, 83, 9_9942, 136, 6_0742, 23, 70, 8_0583, 1_8276, 2]])
# The dog is cute and lives in the garden house
a__ : List[Any] = torch.Size((1, 12, 1024)) # batch_size, sequence_length, embedding_vector_dim
a__ : List[Any] = torch.tensor(
[[-0.06_99, -0.03_18, 0.07_05, -0.12_41, 0.09_99, -0.05_20, 0.10_04, -0.18_38, -0.47_04, 0.14_37, 0.08_21, 0.01_26]])
# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large')
# xlmr.eval()
# expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
with torch.no_grad():
a__ : Union[str, Any] = model(lowercase)['last_hidden_state'].detach()
self.assertEqual(output.shape , lowercase)
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1] , lowercase , atol=1e-3))
| 392
| 1
|
import gc
import random
import tempfile
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu
class _A ( unittest.TestCase ):
'''simple docstring'''
def snake_case_ ( self ):
'''simple docstring'''
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def snake_case_ ( self ):
'''simple docstring'''
snake_case : str = 1
snake_case : str = 3
snake_case : Optional[Any] = (32, 32)
snake_case : int = floats_tensor((batch_size, num_channels) + sizes ,rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE_ )
return image
@property
def snake_case_ ( self ):
'''simple docstring'''
torch.manual_seed(0 )
snake_case : str = UNetaDConditionModel(
block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,cross_attention_dim=32 ,)
return model
@property
def snake_case_ ( self ):
'''simple docstring'''
torch.manual_seed(0 )
snake_case : Dict = 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 ,)
return model
@property
def snake_case_ ( self ):
'''simple docstring'''
torch.manual_seed(0 )
snake_case : Any = CLIPTextConfig(
bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1000 ,)
return CLIPTextModel(SCREAMING_SNAKE_CASE_ )
@property
def snake_case_ ( self ):
'''simple docstring'''
def extract(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ):
class _A :
'''simple docstring'''
def __init__( self ):
'''simple docstring'''
snake_case : Optional[Any] = torch.ones([0] )
def snake_case_ ( self ,SCREAMING_SNAKE_CASE_ ):
'''simple docstring'''
self.pixel_values.to(SCREAMING_SNAKE_CASE_ )
return self
return Out()
return extract
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Dict = """cpu""" # ensure determinism for the device-dependent torch.Generator
snake_case : Optional[Any] = self.dummy_cond_unet
snake_case : Optional[int] = DDIMScheduler(
beta_start=0.0_00_85 ,beta_end=0.0_12 ,beta_schedule="""scaled_linear""" ,clip_sample=SCREAMING_SNAKE_CASE_ ,set_alpha_to_one=SCREAMING_SNAKE_CASE_ ,)
snake_case : Any = self.dummy_vae
snake_case : List[str] = self.dummy_text_encoder
snake_case : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
# make sure here that pndm scheduler skips prk
snake_case : Dict = StableDiffusionPipeline(
unet=SCREAMING_SNAKE_CASE_ ,scheduler=SCREAMING_SNAKE_CASE_ ,vae=SCREAMING_SNAKE_CASE_ ,text_encoder=SCREAMING_SNAKE_CASE_ ,tokenizer=SCREAMING_SNAKE_CASE_ ,safety_checker=SCREAMING_SNAKE_CASE_ ,feature_extractor=self.dummy_extractor ,)
snake_case : int = sd_pipe.to(SCREAMING_SNAKE_CASE_ )
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
snake_case : str = """A painting of a squirrel eating a burger"""
snake_case : List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(0 )
snake_case : Tuple = sd_pipe([prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type="""np""" )
snake_case : Any = output.images
snake_case : Union[str, Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(0 )
snake_case : Dict = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type="""np""" ,return_dict=SCREAMING_SNAKE_CASE_ ,)[0]
snake_case : Dict = image[0, -3:, -3:, -1]
snake_case : Tuple = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case : Any = np.array([0.57_56, 0.61_18, 0.50_05, 0.50_41, 0.54_71, 0.47_26, 0.49_76, 0.48_65, 0.48_64] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator
snake_case : Optional[int] = self.dummy_cond_unet
snake_case : Any = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ )
snake_case : str = self.dummy_vae
snake_case : Dict = self.dummy_text_encoder
snake_case : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
# make sure here that pndm scheduler skips prk
snake_case : Dict = StableDiffusionPipeline(
unet=SCREAMING_SNAKE_CASE_ ,scheduler=SCREAMING_SNAKE_CASE_ ,vae=SCREAMING_SNAKE_CASE_ ,text_encoder=SCREAMING_SNAKE_CASE_ ,tokenizer=SCREAMING_SNAKE_CASE_ ,safety_checker=SCREAMING_SNAKE_CASE_ ,feature_extractor=self.dummy_extractor ,)
snake_case : Dict = sd_pipe.to(SCREAMING_SNAKE_CASE_ )
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
snake_case : Tuple = """A painting of a squirrel eating a burger"""
snake_case : Dict = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(0 )
snake_case : Optional[int] = sd_pipe([prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type="""np""" )
snake_case : str = output.images
snake_case : Dict = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(0 )
snake_case : str = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=6.0 ,num_inference_steps=2 ,output_type="""np""" ,return_dict=SCREAMING_SNAKE_CASE_ ,)[0]
snake_case : int = image[0, -3:, -3:, -1]
snake_case : Any = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
snake_case : int = np.array([0.51_25, 0.57_16, 0.48_28, 0.50_60, 0.56_50, 0.47_68, 0.51_85, 0.48_95, 0.49_93] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Optional[Any] = StableDiffusionPipeline.from_pretrained(
"""hf-internal-testing/tiny-stable-diffusion-lms-pipe""" ,safety_checker=SCREAMING_SNAKE_CASE_ )
assert isinstance(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
assert isinstance(pipe.scheduler ,SCREAMING_SNAKE_CASE_ )
assert pipe.safety_checker is None
snake_case : str = pipe("""example prompt""" ,num_inference_steps=2 ).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(SCREAMING_SNAKE_CASE_ )
snake_case : Any = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
snake_case : int = pipe("""example prompt""" ,num_inference_steps=2 ).images[0]
assert image is not None
@unittest.skipIf(torch_device != """cuda""" ,"""This test requires a GPU""" )
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Any = self.dummy_cond_unet
snake_case : Tuple = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_ )
snake_case : int = self.dummy_vae
snake_case : int = self.dummy_text_encoder
snake_case : Any = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
# put models in fp16
snake_case : Dict = unet.half()
snake_case : Optional[int] = vae.half()
snake_case : Any = bert.half()
# make sure here that pndm scheduler skips prk
snake_case : Any = StableDiffusionPipeline(
unet=SCREAMING_SNAKE_CASE_ ,scheduler=SCREAMING_SNAKE_CASE_ ,vae=SCREAMING_SNAKE_CASE_ ,text_encoder=SCREAMING_SNAKE_CASE_ ,tokenizer=SCREAMING_SNAKE_CASE_ ,safety_checker=SCREAMING_SNAKE_CASE_ ,feature_extractor=self.dummy_extractor ,)
snake_case : int = sd_pipe.to(SCREAMING_SNAKE_CASE_ )
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
snake_case : Tuple = """A painting of a squirrel eating a burger"""
snake_case : int = sd_pipe([prompt] ,num_inference_steps=2 ,output_type="""np""" ).images
assert image.shape == (1, 64, 64, 3)
@nightly
@require_torch_gpu
class _A ( unittest.TestCase ):
'''simple docstring'''
def snake_case_ ( self ):
'''simple docstring'''
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Optional[int] = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ,safety_checker=SCREAMING_SNAKE_CASE_ )
snake_case : List[Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
snake_case : Dict = sd_pipe.to(SCREAMING_SNAKE_CASE_ )
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
snake_case : List[Any] = (
"""portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"""
""" coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"""
""" anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"""
""" children from bahnhof zoo, detailed """
)
snake_case : List[Any] = 4003660346
snake_case : Optional[Any] = 7
# without safety guidance (sld_guidance_scale = 0)
snake_case : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE_ )
snake_case : int = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=SCREAMING_SNAKE_CASE_ ,num_inference_steps=50 ,output_type="""np""" ,width=512 ,height=512 ,sld_guidance_scale=0 ,)
snake_case : Optional[Any] = output.images
snake_case : Union[str, Any] = image[0, -3:, -3:, -1]
snake_case : Optional[int] = [0.22_78, 0.22_31, 0.22_49, 0.23_33, 0.23_03, 0.18_85, 0.22_73, 0.21_44, 0.21_76]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
# without safety guidance (strong configuration)
snake_case : int = torch.manual_seed(SCREAMING_SNAKE_CASE_ )
snake_case : Optional[int] = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=SCREAMING_SNAKE_CASE_ ,num_inference_steps=50 ,output_type="""np""" ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.0_25 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,)
snake_case : Dict = output.images
snake_case : Optional[int] = image[0, -3:, -3:, -1]
snake_case : str = [0.23_83, 0.22_76, 0.2_36, 0.21_92, 0.21_86, 0.20_53, 0.19_71, 0.19_01, 0.17_19]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Tuple = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ,safety_checker=SCREAMING_SNAKE_CASE_ )
snake_case : int = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config )
snake_case : List[Any] = sd_pipe.to(SCREAMING_SNAKE_CASE_ )
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
snake_case : Optional[Any] = """padme amidala taking a bath artwork, safe for work, no nudity"""
snake_case : Optional[Any] = 2734971755
snake_case : Dict = 7
snake_case : Tuple = torch.manual_seed(SCREAMING_SNAKE_CASE_ )
snake_case : int = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=SCREAMING_SNAKE_CASE_ ,num_inference_steps=50 ,output_type="""np""" ,width=512 ,height=512 ,sld_guidance_scale=0 ,)
snake_case : Union[str, Any] = output.images
snake_case : Union[str, Any] = image[0, -3:, -3:, -1]
snake_case : Any = [0.35_02, 0.36_22, 0.33_96, 0.36_42, 0.34_78, 0.33_18, 0.35, 0.33_48, 0.32_97]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
snake_case : str = torch.manual_seed(SCREAMING_SNAKE_CASE_ )
snake_case : Union[str, Any] = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=SCREAMING_SNAKE_CASE_ ,num_inference_steps=50 ,output_type="""np""" ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.0_25 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,)
snake_case : str = output.images
snake_case : Optional[Any] = image[0, -3:, -3:, -1]
snake_case : Any = [0.55_31, 0.52_06, 0.48_95, 0.51_56, 0.51_82, 0.47_51, 0.48_02, 0.48_03, 0.44_43]
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def snake_case_ ( self ):
'''simple docstring'''
snake_case : Any = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" )
snake_case : str = sd_pipe.to(SCREAMING_SNAKE_CASE_ )
sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ )
snake_case : Optional[int] = (
"""the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."""
""" leyendecker"""
)
snake_case : List[Any] = 1044355234
snake_case : Optional[Any] = 12
snake_case : Union[str, Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ )
snake_case : Dict = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=SCREAMING_SNAKE_CASE_ ,num_inference_steps=50 ,output_type="""np""" ,width=512 ,height=512 ,sld_guidance_scale=0 ,)
snake_case : str = output.images
snake_case : Optional[int] = image[0, -3:, -3:, -1]
snake_case : Tuple = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] )
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7
snake_case : str = torch.manual_seed(SCREAMING_SNAKE_CASE_ )
snake_case : str = sd_pipe(
[prompt] ,generator=SCREAMING_SNAKE_CASE_ ,guidance_scale=SCREAMING_SNAKE_CASE_ ,num_inference_steps=50 ,output_type="""np""" ,width=512 ,height=512 ,sld_guidance_scale=2000 ,sld_warmup_steps=7 ,sld_threshold=0.0_25 ,sld_momentum_scale=0.5 ,sld_mom_beta=0.7 ,)
snake_case : Dict = output.images
snake_case : Optional[Any] = image[0, -3:, -3:, -1]
snake_case : Optional[Any] = np.array([0.58_18, 0.62_85, 0.68_35, 0.60_19, 0.6_25, 0.67_54, 0.60_96, 0.63_34, 0.65_61] )
assert image.shape == (1, 512, 512, 3)
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
| 36
|
class A__ :
def __init__( self : List[str] ) -> List[str]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE ={}
def __UpperCamelCase ( self : Any , _a : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
if vertex not in self.adjacency:
_SCREAMING_SNAKE_CASE ={}
self.num_vertices += 1
def __UpperCamelCase ( self : Optional[int] , _a : Tuple , _a : Tuple , _a : Dict ) -> Union[str, Any]:
"""simple docstring"""
self.add_vertex(_a )
self.add_vertex(_a )
if head == tail:
return
_SCREAMING_SNAKE_CASE =weight
_SCREAMING_SNAKE_CASE =weight
def __UpperCamelCase ( self : Dict ) -> int:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =self.get_edges()
for edge in edges:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =edge
edges.remove((tail, head, weight) )
for i in range(len(_a ) ):
_SCREAMING_SNAKE_CASE =list(edges[i] )
edges.sort(key=lambda _a : e[2] )
for i in range(len(_a ) - 1 ):
if edges[i][2] >= edges[i + 1][2]:
_SCREAMING_SNAKE_CASE =edges[i][2] + 1
for edge in edges:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =edge
_SCREAMING_SNAKE_CASE =weight
_SCREAMING_SNAKE_CASE =weight
def __str__( self : str ) -> List[str]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =''''''
for tail in self.adjacency:
for head in self.adjacency[tail]:
_SCREAMING_SNAKE_CASE =self.adjacency[head][tail]
string += f"{head} -> {tail} == {weight}\n"
return string.rstrip('''\n''' )
def __UpperCamelCase ( self : int ) -> Optional[Any]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =[]
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]) )
return output
def __UpperCamelCase ( self : Any ) -> Any:
"""simple docstring"""
return self.adjacency.keys()
@staticmethod
def __UpperCamelCase ( _a : List[str]=None , _a : Optional[int]=None ) -> Optional[Any]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =Graph()
if vertices is None:
_SCREAMING_SNAKE_CASE =[]
if edges is None:
_SCREAMING_SNAKE_CASE =[]
for vertex in vertices:
g.add_vertex(_a )
for edge in edges:
g.add_edge(*_a )
return g
class A__ :
def __init__( self : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE ={}
_SCREAMING_SNAKE_CASE ={}
def __len__( self : Optional[int] ) -> Tuple:
"""simple docstring"""
return len(self.parent )
def __UpperCamelCase ( self : Dict , _a : Optional[Any] ) -> int:
"""simple docstring"""
if item in self.parent:
return self.find(_a )
_SCREAMING_SNAKE_CASE =item
_SCREAMING_SNAKE_CASE =0
return item
def __UpperCamelCase ( self : str , _a : Tuple ) -> Union[str, Any]:
"""simple docstring"""
if item not in self.parent:
return self.make_set(_a )
if item != self.parent[item]:
_SCREAMING_SNAKE_CASE =self.find(self.parent[item] )
return self.parent[item]
def __UpperCamelCase ( self : Dict , _a : Optional[int] , _a : List[Any] ) -> List[str]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =self.find(_a )
_SCREAMING_SNAKE_CASE =self.find(_a )
if roota == roota:
return roota
if self.rank[roota] > self.rank[roota]:
_SCREAMING_SNAKE_CASE =roota
return roota
if self.rank[roota] < self.rank[roota]:
_SCREAMING_SNAKE_CASE =roota
return roota
if self.rank[roota] == self.rank[roota]:
self.rank[roota] += 1
_SCREAMING_SNAKE_CASE =roota
return roota
return None
@staticmethod
def __UpperCamelCase ( _a : int ) -> Union[str, Any]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE =graph.num_vertices
_SCREAMING_SNAKE_CASE =Graph.UnionFind()
_SCREAMING_SNAKE_CASE =[]
while num_components > 1:
_SCREAMING_SNAKE_CASE ={}
for vertex in graph.get_vertices():
_SCREAMING_SNAKE_CASE =-1
_SCREAMING_SNAKE_CASE =graph.get_edges()
for edge in edges:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =edge
edges.remove((tail, head, weight) )
for edge in edges:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =edge
_SCREAMING_SNAKE_CASE =union_find.find(_a )
_SCREAMING_SNAKE_CASE =union_find.find(_a )
if seta != seta:
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
_SCREAMING_SNAKE_CASE =[head, tail, weight]
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
_SCREAMING_SNAKE_CASE =[head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =cheap_edge[vertex]
if union_find.find(_a ) != union_find.find(_a ):
union_find.union(_a , _a )
mst_edges.append(cheap_edge[vertex] )
_SCREAMING_SNAKE_CASE =num_components - 1
_SCREAMING_SNAKE_CASE =Graph.build(edges=_a )
return mst
| 691
| 0
|
'''simple docstring'''
from __future__ import annotations
from collections.abc import Callable
from typing import Any, Generic, TypeVar
UpperCamelCase__ : List[Any] = TypeVar("T")
class _a (Generic[T]):
"""simple docstring"""
def __init__( self , A__ , A__ ) -> None:
_SCREAMING_SNAKE_CASE = None
_SCREAMING_SNAKE_CASE = len(A__ )
_SCREAMING_SNAKE_CASE = [any_type for _ in range(self.N )] + arr
_SCREAMING_SNAKE_CASE = fnc
self.build()
def UpperCamelCase ( self ) -> None:
for p in range(self.N - 1 , 0 , -1 ):
_SCREAMING_SNAKE_CASE = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def UpperCamelCase ( self , A__ , A__ ) -> None:
p += self.N
_SCREAMING_SNAKE_CASE = v
while p > 1:
_SCREAMING_SNAKE_CASE = p // 2
_SCREAMING_SNAKE_CASE = self.fn(self.st[p * 2] , self.st[p * 2 + 1] )
def UpperCamelCase ( self , A__ , A__ ) -> T | None: # noqa: E741
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = l + self.N, r + self.N
_SCREAMING_SNAKE_CASE = None
while l <= r:
if l % 2 == 1:
_SCREAMING_SNAKE_CASE = self.st[l] if res is None else self.fn(A__ , self.st[l] )
if r % 2 == 0:
_SCREAMING_SNAKE_CASE = self.st[r] if res is None else self.fn(A__ , self.st[r] )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = (l + 1) // 2, (r - 1) // 2
return res
if __name__ == "__main__":
from functools import reduce
UpperCamelCase__ : Optional[int] = [1, 10, -2, 9, -3, 8, 4, -7, 5, 6, 11, -12]
UpperCamelCase__ : Union[str, Any] = {
0: 7,
1: 2,
2: 6,
3: -14,
4: 5,
5: 4,
6: 7,
7: -10,
8: 9,
9: 10,
10: 12,
11: 1,
}
UpperCamelCase__ : List[str] = SegmentTree(test_array, min)
UpperCamelCase__ : List[Any] = SegmentTree(test_array, max)
UpperCamelCase__ : Optional[Any] = SegmentTree(test_array, lambda a, b: a + b)
def lowerCAmelCase_ ( ) -> None:
"""simple docstring"""
for i in range(len(SCREAMING_SNAKE_CASE_ ) ):
for j in range(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ):
_SCREAMING_SNAKE_CASE = reduce(SCREAMING_SNAKE_CASE_ , test_array[i : j + 1] )
_SCREAMING_SNAKE_CASE = reduce(SCREAMING_SNAKE_CASE_ , test_array[i : j + 1] )
_SCREAMING_SNAKE_CASE = reduce(lambda SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : a + b , test_array[i : j + 1] )
assert min_range == min_segment_tree.query(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
assert max_range == max_segment_tree.query(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
assert sum_range == sum_segment_tree.query(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
test_all_segments()
for index, value in test_updates.items():
UpperCamelCase__ : List[str] = value
min_segment_tree.update(index, value)
max_segment_tree.update(index, value)
sum_segment_tree.update(index, value)
test_all_segments()
| 0
|
'''simple docstring'''
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ ) -> str:
"""simple docstring"""
return "".join([hex(SCREAMING_SNAKE_CASE_ )[2:].zfill(2 ).upper() for byte in list(SCREAMING_SNAKE_CASE_ )] )
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ ) -> bytes:
"""simple docstring"""
# Check data validity, following RFC3548
# https://www.ietf.org/rfc/rfc3548.txt
if (len(SCREAMING_SNAKE_CASE_ ) % 2) != 0:
raise ValueError(
"""Base16 encoded data is invalid:
Data does not have an even number of hex digits.""" )
# Check the character set - the standard base16 alphabet
# is uppercase according to RFC3548 section 6
if not set(SCREAMING_SNAKE_CASE_ ) <= set("""0123456789ABCDEF""" ):
raise ValueError(
"""Base16 encoded data is invalid:
Data is not uppercase hex or it contains invalid characters.""" )
# For every two hexadecimal digits (= a byte), turn it into an integer.
# Then, string the result together into bytes, and return it.
return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) , 2 ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 0
| 1
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
__UpperCamelCase : Dict = {
"""configuration_mega""": ["""MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MegaConfig""", """MegaOnnxConfig"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Optional[int] = [
"""MEGA_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MegaForCausalLM""",
"""MegaForMaskedLM""",
"""MegaForMultipleChoice""",
"""MegaForQuestionAnswering""",
"""MegaForSequenceClassification""",
"""MegaForTokenClassification""",
"""MegaModel""",
"""MegaPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mega import (
MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
MegaForCausalLM,
MegaForMaskedLM,
MegaForMultipleChoice,
MegaForQuestionAnswering,
MegaForSequenceClassification,
MegaForTokenClassification,
MegaModel,
MegaPreTrainedModel,
)
else:
import sys
__UpperCamelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 80
|
"""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 SCREAMING_SNAKE_CASE :
"""simple docstring"""
def __init__(self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=7 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=99 , lowerCAmelCase_=64 , lowerCAmelCase_=32 , lowerCAmelCase_=5 , lowerCAmelCase_=4 , lowerCAmelCase_=37 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=512 , lowerCAmelCase_=16 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=3 , lowerCAmelCase_=4 , lowerCAmelCase_=None , ):
A_ : Optional[Any] = parent
A_ : List[str] = batch_size
A_ : List[str] = seq_length
A_ : List[str] = is_training
A_ : Optional[Any] = use_input_mask
A_ : Dict = use_token_type_ids
A_ : Any = use_labels
A_ : Tuple = vocab_size
A_ : Optional[Any] = hidden_size
A_ : Tuple = embedding_size
A_ : Tuple = num_hidden_layers
A_ : Any = num_attention_heads
A_ : Optional[int] = intermediate_size
A_ : Union[str, Any] = hidden_act
A_ : Optional[int] = hidden_dropout_prob
A_ : Optional[Any] = attention_probs_dropout_prob
A_ : str = max_position_embeddings
A_ : str = type_vocab_size
A_ : Optional[Any] = type_sequence_label_size
A_ : List[str] = initializer_range
A_ : str = num_labels
A_ : Dict = num_choices
A_ : Any = scope
def lowerCamelCase(self ):
A_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
A_ : Optional[int] = None
if self.use_input_mask:
A_ : str = random_attention_mask([self.batch_size, self.seq_length] )
A_ : int = None
if self.use_token_type_ids:
A_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
A_ : Union[str, Any] = None
A_ : Union[str, Any] = None
A_ : List[str] = None
if self.use_labels:
A_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size )
A_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
A_ : Dict = ids_tensor([self.batch_size] , self.num_choices )
A_ : Tuple = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowerCamelCase(self ):
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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : str = MobileBertModel(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : Optional[int] = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ )
A_ : Union[str, Any] = model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ )
A_ : int = 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : Optional[int] = MobileBertForMaskedLM(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : List[Any] = 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : Optional[int] = MobileBertForNextSentencePrediction(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : Tuple = model(
lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def lowerCamelCase(self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : int = MobileBertForPreTraining(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : Union[str, Any] = 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : Union[str, Any] = MobileBertForQuestionAnswering(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : Tuple = 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : int = self.num_labels
A_ : Optional[int] = MobileBertForSequenceClassification(lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : int = 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : str = self.num_labels
A_ : int = MobileBertForTokenClassification(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : str = 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ):
A_ : str = self.num_choices
A_ : int = MobileBertForMultipleChoice(config=lowerCAmelCase_ )
model.to(lowerCAmelCase_ )
model.eval()
A_ : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
A_ : str = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
A_ : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
A_ : Union[str, Any] = 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 ):
A_ : Optional[Any] = self.prepare_config_and_inputs()
(
(
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) , (
A_
) ,
) : Dict = config_and_inputs
A_ : Any = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
_A : Dict = (
(
MobileBertModel,
MobileBertForMaskedLM,
MobileBertForMultipleChoice,
MobileBertForNextSentencePrediction,
MobileBertForPreTraining,
MobileBertForQuestionAnswering,
MobileBertForSequenceClassification,
MobileBertForTokenClassification,
)
if is_torch_available()
else ()
)
_A : Union[str, Any] = (
{
"""feature-extraction""": MobileBertModel,
"""fill-mask""": MobileBertForMaskedLM,
"""question-answering""": MobileBertForQuestionAnswering,
"""text-classification""": MobileBertForSequenceClassification,
"""token-classification""": MobileBertForTokenClassification,
"""zero-shot""": MobileBertForSequenceClassification,
}
if is_torch_available()
else {}
)
_A : Union[str, Any] = True
def lowerCamelCase(self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ):
A_ : Optional[int] = super()._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ , return_labels=lowerCAmelCase_ )
if return_labels:
if model_class in get_values(lowerCAmelCase_ ):
A_ : List[Any] = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowerCAmelCase_ )
A_ : Optional[int] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase_ )
return inputs_dict
def lowerCamelCase(self ):
A_ : Optional[int] = MobileBertModelTester(self )
A_ : Optional[Any] = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=37 )
def lowerCamelCase(self ):
self.config_tester.run_common_tests()
def lowerCamelCase(self ):
A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_model(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_masked_lm(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_multiple_choice(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_pretraining(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_question_answering(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_sequence_classification(*lowerCAmelCase_ )
def lowerCamelCase(self ):
A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_token_classification(*lowerCAmelCase_ )
def __UpperCamelCase ( snake_case__ ):
return torch.tensor(
snake_case__ , dtype=torch.long , device=snake_case__ , )
_lowerCAmelCase = 1e-3
@require_torch
@require_sentencepiece
@require_tokenizers
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
"""simple docstring"""
@slow
def lowerCamelCase(self ):
A_ : Union[str, Any] = MobileBertModel.from_pretrained("""google/mobilebert-uncased""" ).to(lowerCAmelCase_ )
A_ : Any = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] )
with torch.no_grad():
A_ : Dict = model(lowerCAmelCase_ )[0]
A_ : Any = torch.Size((1, 9, 512) )
self.assertEqual(output.shape , lowerCAmelCase_ )
A_ : Optional[int] = 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
A_ : List[str] = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE )
A_ : Any = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE )
self.assertTrue(lower_bound and upper_bound )
| 180
| 0
|
'''simple docstring'''
import math
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput
class __magic_name__ ( __snake_case , __snake_case ):
UpperCamelCase__ = 1
@register_to_config
def __init__( self , snake_case_ = 10_00 , snake_case_ = None ):
self.set_timesteps(_lowercase )
# standard deviation of the initial noise distribution
lowercase =1.0
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
lowercase =4
# running values
lowercase =[]
def _A( self , snake_case_ , snake_case_ = None ):
lowercase =num_inference_steps
lowercase =torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1]
lowercase =torch.cat([steps, torch.tensor([0.0] )] )
if self.config.trained_betas is not None:
lowercase =torch.tensor(self.config.trained_betas , dtype=torch.floataa )
else:
lowercase =torch.sin(steps * math.pi / 2 ) ** 2
lowercase =(1.0 - self.betas**2) ** 0.5
lowercase =(torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1]
lowercase =timesteps.to(_lowercase )
lowercase =[]
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ = True , ):
if self.num_inference_steps is None:
raise ValueError(
'''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler''' )
lowercase =(self.timesteps == timestep).nonzero().item()
lowercase =timestep_index + 1
lowercase =sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
self.ets.append(_lowercase )
if len(self.ets ) == 1:
lowercase =self.ets[-1]
elif len(self.ets ) == 2:
lowercase =(3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets ) == 3:
lowercase =(23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
lowercase =(1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
lowercase =self._get_prev_sample(_lowercase , _lowercase , _lowercase , _lowercase )
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=_lowercase )
def _A( self , snake_case_ , *snake_case_ , **snake_case_ ):
return sample
def _A( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ ):
lowercase =self.alphas[timestep_index]
lowercase =self.betas[timestep_index]
lowercase =self.alphas[prev_timestep_index]
lowercase =self.betas[prev_timestep_index]
lowercase =(sample - sigma * ets) / max(_lowercase , 1E-8 )
lowercase =next_alpha * pred + ets * next_sigma
return prev_sample
def __len__( self ):
return self.config.num_train_timesteps
| 719
|
'''simple docstring'''
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from transformers import (
VisualBertConfig,
VisualBertForMultipleChoice,
VisualBertForPreTraining,
VisualBertForQuestionAnswering,
VisualBertForVisualReasoning,
)
from transformers.utils import logging
logging.set_verbosity_info()
_UpperCAmelCase : List[Any] = logging.get_logger(__name__)
_UpperCAmelCase : Union[str, Any] = [
('''bert.bert''', '''visual_bert'''),
('''bert.cls''', '''cls'''),
('''bert.classifier''', '''cls'''),
('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''),
('''position_embeddings_visual''', '''visual_position_embeddings'''),
('''projection''', '''visual_projection'''),
]
_UpperCAmelCase : Union[str, Any] = [
'''nlvr2_coco_pre_trained.th''',
'''nlvr2_fine_tuned.th''',
'''nlvr2_pre_trained.th''',
'''vcr_coco_pre_train.th''',
'''vcr_fine_tune.th''',
'''vcr_pre_train.th''',
'''vqa_coco_pre_trained.th''',
'''vqa_fine_tuned.th''',
'''vqa_pre_trained.th''',
]
def UpperCamelCase ( lowercase_ : List[str] ) -> Dict:
'''simple docstring'''
lowercase =torch.load(lowercase_ , map_location='''cpu''' )
return sd
def UpperCamelCase ( lowercase_ : Tuple , lowercase_ : Tuple , lowercase_ : Optional[Any]=rename_keys_prefix ) -> Tuple:
'''simple docstring'''
lowercase =OrderedDict()
lowercase =torch.arange(config.max_position_embeddings ).expand((1, -1) )
# detector_d = OrderedDict()
for key in d:
if "detector" in key:
# detector_d[key.replace('detector.','')] = d[key]
continue
lowercase =key
for name_pair in rename_keys_prefix:
lowercase =new_key.replace(name_pair[0] , name_pair[1] )
lowercase =d[key]
if key == "bert.cls.predictions.decoder.weight":
# Old bert code didn't have `decoder.bias`, but was added separately
lowercase =new_d['''cls.predictions.bias''']
return new_d
@torch.no_grad()
def UpperCamelCase ( lowercase_ : List[Any] , lowercase_ : List[str] ) -> List[Any]:
'''simple docstring'''
assert (
checkpoint_path.split('''/''' )[-1] in ACCEPTABLE_CHECKPOINTS
), f'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.'
# Get Config
if "pre" in checkpoint_path:
lowercase ='''pretraining'''
if "vcr" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 5_1_2}
elif "vqa_advanced" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 2_0_4_8}
elif "vqa" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 2_0_4_8}
elif "nlvr" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 1_0_2_4}
else:
raise NotImplementedError(f'No implementation found for `{checkpoint_path}`.' )
else:
if "vcr" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 5_1_2}
lowercase ='''multichoice'''
elif "vqa_advanced" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 2_0_4_8}
lowercase ='''vqa_advanced'''
elif "vqa" in checkpoint_path:
lowercase ={'''visual_embedding_dim''': 2_0_4_8, '''num_labels''': 3_1_2_9}
lowercase ='''vqa'''
elif "nlvr" in checkpoint_path:
lowercase ={
'''visual_embedding_dim''': 1_0_2_4,
'''num_labels''': 2,
}
lowercase ='''nlvr'''
lowercase =VisualBertConfig(**lowercase_ )
# Load State Dict
lowercase =load_state_dict(lowercase_ )
lowercase =get_new_dict(lowercase_ , lowercase_ )
if model_type == "pretraining":
lowercase =VisualBertForPreTraining(lowercase_ )
elif model_type == "vqa":
lowercase =VisualBertForQuestionAnswering(lowercase_ )
elif model_type == "nlvr":
lowercase =VisualBertForVisualReasoning(lowercase_ )
elif model_type == "multichoice":
lowercase =VisualBertForMultipleChoice(lowercase_ )
model.load_state_dict(lowercase_ )
# Save Checkpoints
Path(lowercase_ ).mkdir(exist_ok=lowercase_ )
model.save_pretrained(lowercase_ )
if __name__ == "__main__":
_UpperCAmelCase : Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''')
parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''')
_UpperCAmelCase : List[str] = parser.parse_args()
convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
| 145
| 0
|
'''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
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
class SCREAMING_SNAKE_CASE :
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : str
SCREAMING_SNAKE_CASE__ : str = None
@staticmethod
def __UpperCAmelCase ( ):
"""simple docstring"""
raise NotImplementedError
def __UpperCAmelCase ( self : int , snake_case : Dict , snake_case : int , snake_case : str , **snake_case : Optional[int] ):
"""simple docstring"""
raise NotImplementedError
def __UpperCAmelCase ( self : str , snake_case : Dict ):
"""simple docstring"""
raise NotImplementedError
def __UpperCAmelCase ( self : Any ):
"""simple docstring"""
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 __UpperCAmelCase ( cls : Union[str, Any] ):
"""simple docstring"""
return F"""`pip install {cls.pip_package or cls.name}`"""
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[int] = '''optuna'''
@staticmethod
def __UpperCAmelCase ( ):
"""simple docstring"""
return is_optuna_available()
def __UpperCAmelCase ( self : Any , snake_case : Tuple , snake_case : int , snake_case : str , **snake_case : Optional[int] ):
"""simple docstring"""
return run_hp_search_optuna(snake_case , snake_case , snake_case , **snake_case )
def __UpperCAmelCase ( self : Optional[Any] , snake_case : Dict ):
"""simple docstring"""
return default_hp_space_optuna(snake_case )
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Dict = '''ray'''
SCREAMING_SNAKE_CASE__ : Optional[Any] = '''\'ray[tune]\''''
@staticmethod
def __UpperCAmelCase ( ):
"""simple docstring"""
return is_ray_available()
def __UpperCAmelCase ( self : List[str] , snake_case : Tuple , snake_case : int , snake_case : str , **snake_case : str ):
"""simple docstring"""
return run_hp_search_ray(snake_case , snake_case , snake_case , **snake_case )
def __UpperCAmelCase ( self : int , snake_case : Optional[Any] ):
"""simple docstring"""
return default_hp_space_ray(snake_case )
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : List[str] = '''sigopt'''
@staticmethod
def __UpperCAmelCase ( ):
"""simple docstring"""
return is_sigopt_available()
def __UpperCAmelCase ( self : int , snake_case : Optional[int] , snake_case : int , snake_case : str , **snake_case : Dict ):
"""simple docstring"""
return run_hp_search_sigopt(snake_case , snake_case , snake_case , **snake_case )
def __UpperCAmelCase ( self : int , snake_case : List[Any] ):
"""simple docstring"""
return default_hp_space_sigopt(snake_case )
class SCREAMING_SNAKE_CASE ( lowercase_ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[int] = '''wandb'''
@staticmethod
def __UpperCAmelCase ( ):
"""simple docstring"""
return is_wandb_available()
def __UpperCAmelCase ( self : Dict , snake_case : List[str] , snake_case : int , snake_case : str , **snake_case : Optional[Any] ):
"""simple docstring"""
return run_hp_search_wandb(snake_case , snake_case , snake_case , **snake_case )
def __UpperCAmelCase ( self : Union[str, Any] , snake_case : int ):
"""simple docstring"""
return default_hp_space_wandb(snake_case )
SCREAMING_SNAKE_CASE_ = {
HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}
def lowerCamelCase__ ( ) -> str:
"""simple docstring"""
_snake_case : Optional[Any] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
if len(a__) > 0:
_snake_case : Any = available_backends[0].name
if len(a__) > 1:
logger.info(
F"""{len(a__)} 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()))
| 517
|
'''simple docstring'''
import argparse
import re
from typing import Dict
import torch
from datasets import Audio, Dataset, load_dataset, load_metric
from transformers import AutoFeatureExtractor, pipeline
def lowerCamelCase__ ( a__ , a__) -> Dict:
"""simple docstring"""
_snake_case : Optional[Any] = args.log_outputs
_snake_case : List[Any] = '_'.join(args.dataset.split('/') + [args.config, args.split])
# load metric
_snake_case : Optional[int] = load_metric('wer')
_snake_case : List[Any] = load_metric('cer')
# compute metrics
_snake_case : List[str] = wer.compute(references=result['target'] , predictions=result['prediction'])
_snake_case : Dict = cer.compute(references=result['target'] , predictions=result['prediction'])
# print & log results
_snake_case : List[Any] = F"""WER: {wer_result}\nCER: {cer_result}"""
print(a__)
with open(F"""{dataset_id}_eval_results.txt""" , 'w') as f:
f.write(a__)
# log all results in text file. Possibly interesting for analysis
if log_outputs is not None:
_snake_case : List[Any] = F"""log_{dataset_id}_predictions.txt"""
_snake_case : List[str] = F"""log_{dataset_id}_targets.txt"""
with open(a__ , 'w') as p, open(a__ , 'w') as t:
# mapping function to write output
def write_to_file(a__ , a__):
p.write(F"""{i}""" + '\n')
p.write(batch['prediction'] + '\n')
t.write(F"""{i}""" + '\n')
t.write(batch['target'] + '\n')
result.map(a__ , with_indices=a__)
def lowerCamelCase__ ( a__) -> str:
"""simple docstring"""
_snake_case : List[str] = '[,?.!\-\;\:"“%‘”�—’…–]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
_snake_case : int = re.sub(a__ , '' , text.lower())
# In addition, we can normalize the target text, e.g. removing new lines characters etc...
# note that order is important here!
_snake_case : Dict = ['\n\n', '\n', ' ', ' ']
for t in token_sequences_to_ignore:
_snake_case : int = ' '.join(text.split(a__))
return text
def lowerCamelCase__ ( a__) -> Dict:
"""simple docstring"""
_snake_case : Optional[Any] = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=a__)
# for testing: only process the first two examples as a test
# dataset = dataset.select(range(10))
# load processor
_snake_case : Optional[int] = AutoFeatureExtractor.from_pretrained(args.model_id)
_snake_case : List[Any] = feature_extractor.sampling_rate
# resample audio
_snake_case : List[str] = dataset.cast_column('audio' , Audio(sampling_rate=a__))
# load eval pipeline
if args.device is None:
_snake_case : Dict = 0 if torch.cuda.is_available() else -1
_snake_case : Dict = pipeline('automatic-speech-recognition' , model=args.model_id , device=args.device)
# map function to decode audio
def map_to_pred(a__):
_snake_case : int = asr(
batch['audio']['array'] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s)
_snake_case : Union[str, Any] = prediction['text']
_snake_case : Optional[int] = normalize_text(batch['sentence'])
return batch
# run inference on all examples
_snake_case : str = dataset.map(a__ , remove_columns=dataset.column_names)
# compute and log_results
# do not change function below
log_results(a__ , a__)
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
parser.add_argument(
"--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
)
parser.add_argument(
"--dataset",
type=str,
required=True,
help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",
)
parser.add_argument(
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
)
parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")
parser.add_argument(
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."
)
parser.add_argument(
"--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."
)
parser.add_argument(
"--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
)
parser.add_argument(
"--device",
type=int,
default=None,
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
)
SCREAMING_SNAKE_CASE_ = parser.parse_args()
main(args)
| 517
| 1
|
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> list:
_UpperCAmelCase = word.split()
def justify(snake_case , snake_case , snake_case ) -> str:
_UpperCAmelCase = max_width - width
_UpperCAmelCase = len(snake_case )
if len(snake_case ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
_UpperCAmelCase = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
_UpperCAmelCase = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
_UpperCAmelCase = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(snake_case ):
num_spaces_between_words_list[i] += 1
_UpperCAmelCase = []
for i in range(snake_case ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * """ """ )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(snake_case )
_UpperCAmelCase = []
_UpperCAmelCase = []
_UpperCAmelCase = 0
for word in words:
if width + len(snake_case ) + len(snake_case ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(snake_case )
width += len(snake_case )
else:
# justify the line and add it to result
answer.append(justify(snake_case , snake_case , snake_case ) )
# reset new line and new width
_UpperCAmelCase , _UpperCAmelCase = [word], len(snake_case )
_UpperCAmelCase = max_width - width - len(snake_case )
answer.append(""" """.join(snake_case ) + (remaining_spaces + 1) * """ """ )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 175
|
import csv
import tweepy
# Twitter API credentials
a = ""
a = ""
a = ""
a = ""
def _SCREAMING_SNAKE_CASE ( snake_case ) -> None:
# authorize twitter, initialize tweepy
_UpperCAmelCase = tweepy.OAuthHandler(snake_case , snake_case )
auth.set_access_token(snake_case , snake_case )
_UpperCAmelCase = tweepy.API(snake_case )
# initialize a list to hold all the tweepy Tweets
_UpperCAmelCase = []
# make initial request for most recent tweets (200 is the maximum allowed count)
_UpperCAmelCase = api.user_timeline(screen_name=snake_case , count=2_0_0 )
# save most recent tweets
alltweets.extend(snake_case )
# save the id of the oldest tweet less one
_UpperCAmelCase = alltweets[-1].id - 1
# keep grabbing tweets until there are no tweets left to grab
while len(snake_case ) > 0:
print(f"getting tweets before {oldest}" )
# all subsequent requests use the max_id param to prevent duplicates
_UpperCAmelCase = api.user_timeline(
screen_name=snake_case , count=2_0_0 , max_id=snake_case )
# save most recent tweets
alltweets.extend(snake_case )
# update the id of the oldest tweet less one
_UpperCAmelCase = alltweets[-1].id - 1
print(f"...{len(snake_case )} tweets downloaded so far" )
# transform the tweepy tweets into a 2D array that will populate the csv
_UpperCAmelCase = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets]
# write the csv
with open(f"new_{screen_name}_tweets.csv" , """w""" ) as f:
_UpperCAmelCase = csv.writer(snake_case )
writer.writerow(["""id""", """created_at""", """text"""] )
writer.writerows(snake_case )
if __name__ == "__main__":
# pass in the username of the account you want to download
get_all_tweets("FirePing32")
| 175
| 1
|
from math import sqrt
def lowerCamelCase_ ( lowerCAmelCase__ : int ) -> bool:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (
number >= 0
), "'number' must been an int and positive"
A = True
# 0 and 1 are none primes.
if number <= 1:
A = False
for divisor in range(2 , int(round(sqrt(lowerCAmelCase__ ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
A = False
break
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'status' must been from type bool"
return status
def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> str:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
A = list(range(2 , n + 1 ) )
A = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(lowerCAmelCase__ ) ):
for j in range(i + 1 , len(lowerCAmelCase__ ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
A = 0
# filters actual prime numbers.
A = [x for x in begin_list if x != 0]
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : str ) -> Dict:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n > 2), "'N' must been an int and > 2"
A = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2 , n + 1 ):
if is_prime(lowerCAmelCase__ ):
ans.append(lowerCAmelCase__ )
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Dict:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and number >= 0, "'number' must been an int and >= 0"
A = [] # this list will be returns of the function.
# potential prime number factors.
A = 2
A = number
if number == 0 or number == 1:
ans.append(lowerCAmelCase__ )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(lowerCAmelCase__ ):
while quotient != 1:
if is_prime(lowerCAmelCase__ ) and (quotient % factor == 0):
ans.append(lowerCAmelCase__ )
quotient /= factor
else:
factor += 1
else:
ans.append(lowerCAmelCase__ )
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> Tuple:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (
number >= 0
), "'number' bust been an int and >= 0"
A = 0
# prime factorization of 'number'
A = prime_factorization(lowerCAmelCase__ )
A = max(lowerCAmelCase__ )
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type int"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : int ) -> List[Any]:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (
number >= 0
), "'number' bust been an int and >= 0"
A = 0
# prime factorization of 'number'
A = prime_factorization(lowerCAmelCase__ )
A = min(lowerCAmelCase__ )
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type int"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> Optional[int]:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'number' must been an int"
assert isinstance(number % 2 == 0 , lowerCAmelCase__ ), "compare bust been from type bool"
return number % 2 == 0
def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Any:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'number' must been an int"
assert isinstance(number % 2 != 0 , lowerCAmelCase__ ), "compare bust been from type bool"
return number % 2 != 0
def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> int:
'''simple docstring'''
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (number > 2) and is_even(lowerCAmelCase__ )
), "'number' must been an int, even and > 2"
A = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
A = get_prime_numbers(lowerCAmelCase__ )
A = len(lowerCAmelCase__ )
# run variable for while-loops.
A = 0
A = None
# exit variable. for break up the loops
A = True
while i < len_pn and loop:
A = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
A = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and (len(lowerCAmelCase__ ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] ) -> List[Any]:
'''simple docstring'''
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
A = 0
while numbera != 0:
A = numbera % numbera
A = numbera
A = rest
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
A = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
A = prime_factorization(lowerCAmelCase__ )
A = prime_factorization(lowerCAmelCase__ )
elif numbera == 1 or numbera == 1:
A = []
A = []
A = max(lowerCAmelCase__ , lowerCAmelCase__ )
A = 0
A = 0
A = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
A = prime_fac_a.count(lowerCAmelCase__ )
A = prime_fac_a.count(lowerCAmelCase__ )
for _ in range(max(lowerCAmelCase__ , lowerCAmelCase__ ) ):
ans *= n
else:
A = prime_fac_a.count(lowerCAmelCase__ )
for _ in range(lowerCAmelCase__ ):
ans *= n
done.append(lowerCAmelCase__ )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
A = prime_fac_a.count(lowerCAmelCase__ )
for _ in range(lowerCAmelCase__ ):
ans *= n
done.append(lowerCAmelCase__ )
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Any:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'number' must been a positive int"
A = 0
A = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(lowerCAmelCase__ ):
ans += 1
# precondition
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and is_prime(
lowerCAmelCase__ ), "'ans' must been a prime number and from type int"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str ) -> Optional[int]:
'''simple docstring'''
assert (
is_prime(lowerCAmelCase__ ) and is_prime(lowerCAmelCase__ ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
A = p_number_a + 1 # jump to the next number
A = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(lowerCAmelCase__ ):
number += 1
while number < p_number_a:
ans.append(lowerCAmelCase__ )
number += 1
# fetch the next prime number.
while not is_prime(lowerCAmelCase__ ):
number += 1
# precondition
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and ans[0] != p_number_a
and ans[len(lowerCAmelCase__ ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> List[str]:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 1), "'n' must been int and >= 1"
A = [] # will be returned.
for divisor in range(1 , n + 1 ):
if n % divisor == 0:
ans.append(lowerCAmelCase__ )
# precondition
assert ans[0] == 1 and ans[len(lowerCAmelCase__ ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Optional[Any]:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (
number > 1
), "'number' must been an int and >= 1"
A = get_divisors(lowerCAmelCase__ )
# precondition
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and (divisors[0] == 1)
and (divisors[len(lowerCAmelCase__ ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCamelCase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] ) -> str:
'''simple docstring'''
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
A = gcd(abs(lowerCAmelCase__ ) , abs(lowerCAmelCase__ ) )
# precondition
assert (
isinstance(lowerCAmelCase__ , lowerCAmelCase__ )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCamelCase_ ( lowerCAmelCase__ : Dict ) -> int:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'n' must been a int and >= 0"
A = 1 # this will be return.
for factor in range(1 , n + 1 ):
ans *= factor
return ans
def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Union[str, Any]:
'''simple docstring'''
assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'n' must been an int and >= 0"
A = 0
A = 1
A = 1 # this will be return
for _ in range(n - 1 ):
A = ans
ans += fiba
A = tmp
return ans
| 106
|
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 (
MobileViTConfig,
MobileViTForImageClassification,
MobileViTForSemanticSegmentation,
MobileViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
_lowercase: Dict = logging.get_logger(__name__)
def _lowerCamelCase ( snake_case ):
_lowerCAmelCase = MobileViTConfig()
# size of the architecture
if "mobilevit_s" in mobilevit_name:
_lowerCAmelCase = [144, 192, 240]
_lowerCAmelCase = [16, 32, 64, 96, 128, 160, 640]
elif "mobilevit_xs" in mobilevit_name:
_lowerCAmelCase = [96, 120, 144]
_lowerCAmelCase = [16, 32, 48, 64, 80, 96, 384]
elif "mobilevit_xxs" in mobilevit_name:
_lowerCAmelCase = [64, 80, 96]
_lowerCAmelCase = [16, 16, 24, 48, 64, 80, 320]
_lowerCAmelCase = 0.05
_lowerCAmelCase = 2.0
if mobilevit_name.startswith('deeplabv3_' ):
_lowerCAmelCase = 512
_lowerCAmelCase = 16
_lowerCAmelCase = 21
_lowerCAmelCase = 'pascal-voc-id2label.json'
else:
_lowerCAmelCase = 1_000
_lowerCAmelCase = 'imagenet-1k-id2label.json'
_lowerCAmelCase = 'huggingface/label-files'
_lowerCAmelCase = json.load(open(hf_hub_download(snake_case , snake_case , repo_type='dataset' ) , 'r' ) )
_lowerCAmelCase = {int(snake_case ): v for k, v in idalabel.items()}
_lowerCAmelCase = idalabel
_lowerCAmelCase = {v: k for k, v in idalabel.items()}
return config
def _lowerCamelCase ( snake_case , snake_case=False ):
for i in range(1 , 6 ):
if F'layer_{i}.' in name:
_lowerCAmelCase = name.replace(F'layer_{i}.' , F'encoder.layer.{i - 1}.' )
if "conv_1." in name:
_lowerCAmelCase = name.replace('conv_1.' , 'conv_stem.' )
if ".block." in name:
_lowerCAmelCase = name.replace('.block.' , '.' )
if "exp_1x1" in name:
_lowerCAmelCase = name.replace('exp_1x1' , 'expand_1x1' )
if "red_1x1" in name:
_lowerCAmelCase = name.replace('red_1x1' , 'reduce_1x1' )
if ".local_rep.conv_3x3." in name:
_lowerCAmelCase = name.replace('.local_rep.conv_3x3.' , '.conv_kxk.' )
if ".local_rep.conv_1x1." in name:
_lowerCAmelCase = name.replace('.local_rep.conv_1x1.' , '.conv_1x1.' )
if ".norm." in name:
_lowerCAmelCase = name.replace('.norm.' , '.normalization.' )
if ".conv." in name:
_lowerCAmelCase = name.replace('.conv.' , '.convolution.' )
if ".conv_proj." in name:
_lowerCAmelCase = name.replace('.conv_proj.' , '.conv_projection.' )
for i in range(0 , 2 ):
for j in range(0 , 4 ):
if F'.{i}.{j}.' in name:
_lowerCAmelCase = name.replace(F'.{i}.{j}.' , F'.{i}.layer.{j}.' )
for i in range(2 , 6 ):
for j in range(0 , 4 ):
if F'.{i}.{j}.' in name:
_lowerCAmelCase = name.replace(F'.{i}.{j}.' , F'.{i}.' )
if "expand_1x1" in name:
_lowerCAmelCase = name.replace('expand_1x1' , 'downsampling_layer.expand_1x1' )
if "conv_3x3" in name:
_lowerCAmelCase = name.replace('conv_3x3' , 'downsampling_layer.conv_3x3' )
if "reduce_1x1" in name:
_lowerCAmelCase = name.replace('reduce_1x1' , 'downsampling_layer.reduce_1x1' )
for i in range(2 , 5 ):
if F'.global_rep.{i}.weight' in name:
_lowerCAmelCase = name.replace(F'.global_rep.{i}.weight' , '.layernorm.weight' )
if F'.global_rep.{i}.bias' in name:
_lowerCAmelCase = name.replace(F'.global_rep.{i}.bias' , '.layernorm.bias' )
if ".global_rep." in name:
_lowerCAmelCase = name.replace('.global_rep.' , '.transformer.' )
if ".pre_norm_mha.0." in name:
_lowerCAmelCase = name.replace('.pre_norm_mha.0.' , '.layernorm_before.' )
if ".pre_norm_mha.1.out_proj." in name:
_lowerCAmelCase = name.replace('.pre_norm_mha.1.out_proj.' , '.attention.output.dense.' )
if ".pre_norm_ffn.0." in name:
_lowerCAmelCase = name.replace('.pre_norm_ffn.0.' , '.layernorm_after.' )
if ".pre_norm_ffn.1." in name:
_lowerCAmelCase = name.replace('.pre_norm_ffn.1.' , '.intermediate.dense.' )
if ".pre_norm_ffn.4." in name:
_lowerCAmelCase = name.replace('.pre_norm_ffn.4.' , '.output.dense.' )
if ".transformer." in name:
_lowerCAmelCase = name.replace('.transformer.' , '.transformer.layer.' )
if ".aspp_layer." in name:
_lowerCAmelCase = name.replace('.aspp_layer.' , '.' )
if ".aspp_pool." in name:
_lowerCAmelCase = name.replace('.aspp_pool.' , '.' )
if "seg_head." in name:
_lowerCAmelCase = name.replace('seg_head.' , 'segmentation_head.' )
if "segmentation_head.classifier.classifier." in name:
_lowerCAmelCase = name.replace('segmentation_head.classifier.classifier.' , 'segmentation_head.classifier.' )
if "classifier.fc." in name:
_lowerCAmelCase = name.replace('classifier.fc.' , 'classifier.' )
elif (not base_model) and ("segmentation_head." not in name):
_lowerCAmelCase = 'mobilevit.' + name
return name
def _lowerCamelCase ( snake_case , snake_case , snake_case=False ):
if base_model:
_lowerCAmelCase = ''
else:
_lowerCAmelCase = 'mobilevit.'
for key in orig_state_dict.copy().keys():
_lowerCAmelCase = orig_state_dict.pop(snake_case )
if key[:8] == "encoder.":
_lowerCAmelCase = key[8:]
if "qkv" in key:
_lowerCAmelCase = key.split('.' )
_lowerCAmelCase = int(key_split[0][6:] ) - 1
_lowerCAmelCase = int(key_split[3] )
_lowerCAmelCase = model.get_submodule(F'{model_prefix}encoder.layer.{layer_num}' )
_lowerCAmelCase = layer.transformer.layer[transformer_num].attention.attention.all_head_size
_lowerCAmelCase = (
F'{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.'
)
if "weight" in key:
_lowerCAmelCase = val[:dim, :]
_lowerCAmelCase = val[dim : dim * 2, :]
_lowerCAmelCase = val[-dim:, :]
else:
_lowerCAmelCase = val[:dim]
_lowerCAmelCase = val[dim : dim * 2]
_lowerCAmelCase = val[-dim:]
else:
_lowerCAmelCase = val
return orig_state_dict
def _lowerCamelCase ( ):
_lowerCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg'
_lowerCAmelCase = Image.open(requests.get(snake_case , stream=snake_case ).raw )
return im
@torch.no_grad()
def _lowerCamelCase ( snake_case , snake_case , snake_case , snake_case=False ):
_lowerCAmelCase = get_mobilevit_config(snake_case )
# load original state_dict
_lowerCAmelCase = torch.load(snake_case , map_location='cpu' )
# load 🤗 model
if mobilevit_name.startswith('deeplabv3_' ):
_lowerCAmelCase = MobileViTForSemanticSegmentation(snake_case ).eval()
else:
_lowerCAmelCase = MobileViTForImageClassification(snake_case ).eval()
_lowerCAmelCase = convert_state_dict(snake_case , snake_case )
model.load_state_dict(snake_case )
# Check outputs on an image, prepared by MobileViTImageProcessor
_lowerCAmelCase = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 )
_lowerCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' )
_lowerCAmelCase = model(**snake_case )
_lowerCAmelCase = outputs.logits
if mobilevit_name.startswith('deeplabv3_' ):
assert logits.shape == (1, 21, 32, 32)
if mobilevit_name == "deeplabv3_mobilevit_s":
_lowerCAmelCase = torch.tensor(
[
[[6.20_65, 6.12_92, 6.20_70], [6.10_79, 6.12_54, 6.17_47], [6.00_42, 6.10_71, 6.10_34]],
[[-6.92_53, -6.86_53, -7.03_98], [-7.32_18, -7.39_83, -7.36_70], [-7.19_61, -7.24_82, -7.15_69]],
[[-4.47_23, -4.43_48, -4.37_69], [-5.36_29, -5.46_32, -5.45_98], [-5.15_87, -5.34_02, -5.50_59]],
] )
elif mobilevit_name == "deeplabv3_mobilevit_xs":
_lowerCAmelCase = torch.tensor(
[
[[5.44_49, 5.57_33, 5.63_14], [5.18_15, 5.39_30, 5.59_63], [5.16_56, 5.43_33, 5.48_53]],
[[-9.44_23, -9.77_66, -9.67_14], [-9.15_81, -9.57_20, -9.55_19], [-9.10_06, -9.64_58, -9.57_03]],
[[-7.77_21, -7.37_16, -7.15_83], [-8.45_99, -8.06_24, -7.79_44], [-8.41_72, -7.83_66, -7.50_25]],
] )
elif mobilevit_name == "deeplabv3_mobilevit_xxs":
_lowerCAmelCase = torch.tensor(
[
[[6.98_11, 6.97_43, 7.31_23], [7.17_77, 7.19_31, 7.39_38], [7.56_33, 7.80_50, 7.89_01]],
[[-10.55_36, -10.23_32, -10.29_24], [-10.23_36, -9.86_24, -9.59_64], [-10.88_40, -10.81_58, -10.66_59]],
[[-3.49_38, -3.06_31, -2.86_20], [-3.42_05, -2.81_35, -2.68_75], [-3.41_79, -2.79_45, -2.87_50]],
] )
else:
raise ValueError(F'Unknown mobilevit_name: {mobilevit_name}' )
assert torch.allclose(logits[0, :3, :3, :3] , snake_case , atol=1E-4 )
else:
assert logits.shape == (1, 1_000)
if mobilevit_name == "mobilevit_s":
_lowerCAmelCase = torch.tensor([-0.98_66, 0.23_92, -1.12_41] )
elif mobilevit_name == "mobilevit_xs":
_lowerCAmelCase = torch.tensor([-2.47_61, -0.93_99, -1.95_87] )
elif mobilevit_name == "mobilevit_xxs":
_lowerCAmelCase = torch.tensor([-1.93_64, -1.23_27, -0.46_53] )
else:
raise ValueError(F'Unknown mobilevit_name: {mobilevit_name}' )
assert torch.allclose(logits[0, :3] , snake_case , atol=1E-4 )
Path(snake_case ).mkdir(exist_ok=snake_case )
print(F'Saving model {mobilevit_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 push_to_hub:
_lowerCAmelCase = {
'mobilevit_s': 'mobilevit-small',
'mobilevit_xs': 'mobilevit-x-small',
'mobilevit_xxs': 'mobilevit-xx-small',
'deeplabv3_mobilevit_s': 'deeplabv3-mobilevit-small',
'deeplabv3_mobilevit_xs': 'deeplabv3-mobilevit-x-small',
'deeplabv3_mobilevit_xxs': 'deeplabv3-mobilevit-xx-small',
}
print('Pushing to the hub...' )
_lowerCAmelCase = model_mapping[mobilevit_name]
image_processor.push_to_hub(snake_case , organization='apple' )
model.push_to_hub(snake_case , organization='apple' )
if __name__ == "__main__":
_lowercase: Union[str, Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--mobilevit_name''',
default='''mobilevit_s''',
type=str,
help=(
'''Name of the MobileViT model you\'d like to convert. Should be one of \'mobilevit_s\', \'mobilevit_xs\','''
''' \'mobilevit_xxs\', \'deeplabv3_mobilevit_s\', \'deeplabv3_mobilevit_xs\', \'deeplabv3_mobilevit_xxs\'.'''
),
)
parser.add_argument(
'''--checkpoint_path''', required=True, type=str, help='''Path to the original state dict (.pt file).'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', required=True, type=str, help='''Path to the output PyTorch model directory.'''
)
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
_lowercase: List[str] = parser.parse_args()
convert_movilevit_checkpoint(
args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 192
| 0
|
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging
logging.set_verbosity_info()
A_ = logging.get_logger(__name__)
def __UpperCAmelCase ( UpperCAmelCase, UpperCAmelCase=False, UpperCAmelCase=False )-> int:
"""simple docstring"""
lowercase = '''backbone.''' if is_semantic else ''''''
lowercase = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((f'{prefix}blocks.{i}.norm1.weight', f'beit.encoder.layer.{i}.layernorm_before.weight') )
rename_keys.append((f'{prefix}blocks.{i}.norm1.bias', f'beit.encoder.layer.{i}.layernorm_before.bias') )
rename_keys.append(
(f'{prefix}blocks.{i}.attn.proj.weight', f'beit.encoder.layer.{i}.attention.output.dense.weight') )
rename_keys.append(
(f'{prefix}blocks.{i}.attn.proj.bias', f'beit.encoder.layer.{i}.attention.output.dense.bias') )
rename_keys.append((f'{prefix}blocks.{i}.norm2.weight', f'beit.encoder.layer.{i}.layernorm_after.weight') )
rename_keys.append((f'{prefix}blocks.{i}.norm2.bias', f'beit.encoder.layer.{i}.layernorm_after.bias') )
rename_keys.append((f'{prefix}blocks.{i}.mlp.fc1.weight', f'beit.encoder.layer.{i}.intermediate.dense.weight') )
rename_keys.append((f'{prefix}blocks.{i}.mlp.fc1.bias', f'beit.encoder.layer.{i}.intermediate.dense.bias') )
rename_keys.append((f'{prefix}blocks.{i}.mlp.fc2.weight', f'beit.encoder.layer.{i}.output.dense.weight') )
rename_keys.append((f'{prefix}blocks.{i}.mlp.fc2.bias', f'beit.encoder.layer.{i}.output.dense.bias') )
# projection layer + position embeddings
rename_keys.extend(
[
(f'{prefix}cls_token', '''beit.embeddings.cls_token'''),
(f'{prefix}patch_embed.proj.weight', '''beit.embeddings.patch_embeddings.projection.weight'''),
(f'{prefix}patch_embed.proj.bias', '''beit.embeddings.patch_embeddings.projection.bias'''),
(f'{prefix}pos_embed', '''beit.embeddings.position_embeddings'''),
] )
if has_lm_head:
# mask token + layernorm
rename_keys.extend(
[
('''mask_token''', '''beit.embeddings.mask_token'''),
('''norm.weight''', '''layernorm.weight'''),
('''norm.bias''', '''layernorm.bias'''),
] )
else:
# layernorm + classification head
rename_keys.extend(
[
('''fc_norm.weight''', '''beit.pooler.layernorm.weight'''),
('''fc_norm.bias''', '''beit.pooler.layernorm.bias'''),
('''head.weight''', '''classifier.weight'''),
('''head.bias''', '''classifier.bias'''),
] )
return rename_keys
def __UpperCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase=False, UpperCAmelCase=False )-> Union[str, Any]:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
lowercase = '''backbone.''' if is_semantic else ''''''
# queries, keys and values
lowercase = state_dict.pop(f'{prefix}blocks.{i}.attn.qkv.weight' )
lowercase = state_dict.pop(f'{prefix}blocks.{i}.attn.q_bias' )
lowercase = state_dict.pop(f'{prefix}blocks.{i}.attn.v_bias' )
lowercase = in_proj_weight[
: config.hidden_size, :
]
lowercase = q_bias
lowercase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
lowercase = in_proj_weight[
-config.hidden_size :, :
]
lowercase = v_bias
# gamma_1 and gamma_2
# we call them lambda because otherwise they are renamed when using .from_pretrained
lowercase = state_dict.pop(f'{prefix}blocks.{i}.gamma_1' )
lowercase = state_dict.pop(f'{prefix}blocks.{i}.gamma_2' )
lowercase = gamma_a
lowercase = gamma_a
def __UpperCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )-> Optional[Any]:
"""simple docstring"""
lowercase = dct.pop(UpperCAmelCase )
lowercase = val
def __UpperCAmelCase ( )-> int:
"""simple docstring"""
lowercase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
lowercase = Image.open(requests.get(UpperCAmelCase, stream=UpperCAmelCase ).raw )
return im
@torch.no_grad()
def __UpperCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase=False )-> Dict:
"""simple docstring"""
lowercase = False if '''rvlcdip''' in checkpoint_url else True
lowercase = BeitConfig(use_absolute_position_embeddings=UpperCAmelCase, use_mask_token=UpperCAmelCase )
# size of the architecture
if "large" in checkpoint_url or "dit-l" in checkpoint_url:
lowercase = 1024
lowercase = 4096
lowercase = 24
lowercase = 16
# labels
if "rvlcdip" in checkpoint_url:
lowercase = 16
lowercase = '''huggingface/label-files'''
lowercase = '''rvlcdip-id2label.json'''
lowercase = json.load(open(hf_hub_download(UpperCAmelCase, UpperCAmelCase, repo_type='''dataset''' ), '''r''' ) )
lowercase = {int(UpperCAmelCase ): v for k, v in idalabel.items()}
lowercase = idalabel
lowercase = {v: k for k, v in idalabel.items()}
# load state_dict of original model, remove and rename some keys
lowercase = torch.hub.load_state_dict_from_url(UpperCAmelCase, map_location='''cpu''' )['''model''']
lowercase = create_rename_keys(UpperCAmelCase, has_lm_head=UpperCAmelCase )
for src, dest in rename_keys:
rename_key(UpperCAmelCase, UpperCAmelCase, UpperCAmelCase )
read_in_q_k_v(UpperCAmelCase, UpperCAmelCase, has_lm_head=UpperCAmelCase )
# load HuggingFace model
lowercase = BeitForMaskedImageModeling(UpperCAmelCase ) if has_lm_head else BeitForImageClassification(UpperCAmelCase )
model.eval()
model.load_state_dict(UpperCAmelCase )
# Check outputs on an image
lowercase = BeitImageProcessor(
size=config.image_size, resample=PILImageResampling.BILINEAR, do_center_crop=UpperCAmelCase )
lowercase = prepare_img()
lowercase = image_processor(images=UpperCAmelCase, return_tensors='''pt''' )
lowercase = encoding['''pixel_values''']
lowercase = model(UpperCAmelCase )
lowercase = outputs.logits
# verify logits
lowercase = [1, 16] if '''rvlcdip''' in checkpoint_url else [1, 196, 8192]
assert logits.shape == torch.Size(UpperCAmelCase ), "Shape of logits not as expected"
Path(UpperCAmelCase ).mkdir(exist_ok=UpperCAmelCase )
print(f'Saving model to {pytorch_dump_folder_path}' )
model.save_pretrained(UpperCAmelCase )
print(f'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(UpperCAmelCase )
if push_to_hub:
if has_lm_head:
lowercase = '''dit-base''' if '''base''' in checkpoint_url else '''dit-large'''
else:
lowercase = '''dit-base-finetuned-rvlcdip''' if '''dit-b''' in checkpoint_url else '''dit-large-finetuned-rvlcdip'''
image_processor.push_to_hub(
repo_path_or_name=Path(UpperCAmelCase, UpperCAmelCase ), organization='''nielsr''', commit_message='''Add image processor''', use_temp_dir=UpperCAmelCase, )
model.push_to_hub(
repo_path_or_name=Path(UpperCAmelCase, UpperCAmelCase ), organization='''nielsr''', commit_message='''Add model''', use_temp_dir=UpperCAmelCase, )
if __name__ == "__main__":
A_ = argparse.ArgumentParser()
parser.add_argument(
"--checkpoint_url",
default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth",
type=str,
help="URL to the original PyTorch checkpoint (.pth file).",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
)
parser.add_argument(
"--push_to_hub",
action="store_true",
)
A_ = parser.parse_args()
convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 479
|
from __future__ import annotations
import math
def __UpperCAmelCase ( UpperCAmelCase )-> list[int]:
"""simple docstring"""
if num <= 0:
lowercase = f'{num}: Invalid input, please enter a positive integer.'
raise ValueError(UpperCAmelCase )
lowercase = [True] * (num + 1)
lowercase = []
lowercase = 2
lowercase = int(math.sqrt(UpperCAmelCase ) )
while start <= end:
# If start is a prime
if sieve[start] is True:
prime.append(UpperCAmelCase )
# Set multiples of start be False
for i in range(start * start, num + 1, UpperCAmelCase ):
if sieve[i] is True:
lowercase = False
start += 1
for j in range(end + 1, num + 1 ):
if sieve[j] is True:
prime.append(UpperCAmelCase )
return prime
if __name__ == "__main__":
print(prime_sieve(int(input("Enter a positive integer: ").strip())))
| 479
| 1
|
'''simple docstring'''
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Audio, Features, Value
from .base import TaskTemplate
@dataclass(frozen=A__ )
class UpperCAmelCase ( A__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ = field(default='automatic-speech-recognition' , metadata={'include_in_asdict_even_if_is_default': True} )
SCREAMING_SNAKE_CASE_ = Features({'audio': Audio()} )
SCREAMING_SNAKE_CASE_ = Features({'transcription': Value('string' )} )
SCREAMING_SNAKE_CASE_ = "audio"
SCREAMING_SNAKE_CASE_ = "transcription"
def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]:
'''simple docstring'''
if self.audio_column not in features:
raise ValueError(f'''Column {self.audio_column} is not present in features.''' )
if not isinstance(features[self.audio_column] , _UpperCamelCase ):
raise ValueError(f'''Column {self.audio_column} is not an Audio type.''' )
lowerCamelCase_ = copy.deepcopy(self )
lowerCamelCase_ = self.input_schema.copy()
lowerCamelCase_ = features[self.audio_column]
lowerCamelCase_ = input_schema
return task_template
@property
def UpperCamelCase( self ) -> Optional[Any]:
'''simple docstring'''
return {self.audio_column: "audio", self.transcription_column: "transcription"}
| 42
|
from math import sqrt
def A__ ( SCREAMING_SNAKE_CASE_ : int ) -> bool:
"""simple docstring"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(sqrt(SCREAMING_SNAKE_CASE_ ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def A__ ( SCREAMING_SNAKE_CASE_ : int = 1_00_01 ) -> int:
"""simple docstring"""
_UpperCAmelCase = 0
_UpperCAmelCase = 1
while count != nth and number < 3:
number += 1
if is_prime(SCREAMING_SNAKE_CASE_ ):
count += 1
while count != nth:
number += 2
if is_prime(SCREAMING_SNAKE_CASE_ ):
count += 1
return number
if __name__ == "__main__":
print(f'''{solution() = }''')
| 32
| 0
|
'''simple docstring'''
from collections.abc import Sequence
def __lowerCamelCase ( _UpperCamelCase : Dict = None ):
'''simple docstring'''
if nums is None or not nums:
raise ValueError('''Input sequence should not be empty''' )
UpperCAmelCase_ = nums[0]
for i in range(1 , len(_UpperCamelCase ) ):
UpperCAmelCase_ = nums[i]
UpperCAmelCase_ = max(_UpperCamelCase , ans + num , _UpperCamelCase )
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
lowercase__ : Optional[Any] = int(input("Enter number of elements : ").strip())
lowercase__ : Union[str, Any] = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
print(max_subsequence_sum(array))
| 700
|
'''simple docstring'''
def __lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : list[str] ):
'''simple docstring'''
UpperCAmelCase_ = ''''''
for word_or_phrase in separated:
if not isinstance(_UpperCamelCase , _UpperCamelCase ):
raise Exception('''join() accepts only strings to be joined''' )
joined += word_or_phrase + separator
return joined.strip(_UpperCamelCase )
if __name__ == "__main__":
from doctest import testmod
testmod()
| 43
| 0
|
import logging
import os
from typing import List, TextIO, Union
from conllu import parse_incr
from utils_ner import InputExample, Split, TokenClassificationTask
_A = logging.getLogger(__name__)
class A ( __UpperCAmelCase ):
def __init__( self, UpperCamelCase__=-1 ):
"""simple docstring"""
lowerCAmelCase_ = label_idx
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
if isinstance(UpperCamelCase__, UpperCamelCase__ ):
lowerCAmelCase_ = mode.value
lowerCAmelCase_ = os.path.join(UpperCamelCase__, f"{mode}.txt" )
lowerCAmelCase_ = 1
lowerCAmelCase_ = []
with open(UpperCamelCase__, encoding='''utf-8''' ) as f:
lowerCAmelCase_ = []
lowerCAmelCase_ = []
for line in f:
if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n":
if words:
examples.append(InputExample(guid=f"{mode}-{guid_index}", words=UpperCamelCase__, labels=UpperCamelCase__ ) )
guid_index += 1
lowerCAmelCase_ = []
lowerCAmelCase_ = []
else:
lowerCAmelCase_ = line.split(''' ''' )
words.append(splits[0] )
if len(UpperCamelCase__ ) > 1:
labels.append(splits[self.label_idx].replace('''\n''', '''''' ) )
else:
# Examples could have no label for mode = "test"
labels.append('''O''' )
if words:
examples.append(InputExample(guid=f"{mode}-{guid_index}", words=UpperCamelCase__, labels=UpperCamelCase__ ) )
return examples
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = 0
for line in test_input_reader:
if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n":
writer.write(UpperCamelCase__ )
if not preds_list[example_id]:
example_id += 1
elif preds_list[example_id]:
lowerCAmelCase_ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n'''
writer.write(UpperCamelCase__ )
else:
logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''', line.split()[0] )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
if path:
with open(UpperCamelCase__, '''r''' ) as f:
lowerCAmelCase_ = f.read().splitlines()
if "O" not in labels:
lowerCAmelCase_ = ['''O'''] + labels
return labels
else:
return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
class A ( __UpperCAmelCase ):
def __init__( self ):
"""simple docstring"""
super().__init__(label_idx=-2 )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
if path:
with open(UpperCamelCase__, '''r''' ) as f:
lowerCAmelCase_ = f.read().splitlines()
if "O" not in labels:
lowerCAmelCase_ = ['''O'''] + labels
return labels
else:
return [
"O",
"B-ADVP",
"B-INTJ",
"B-LST",
"B-PRT",
"B-NP",
"B-SBAR",
"B-VP",
"B-ADJP",
"B-CONJP",
"B-PP",
"I-ADVP",
"I-INTJ",
"I-LST",
"I-PRT",
"I-NP",
"I-SBAR",
"I-VP",
"I-ADJP",
"I-CONJP",
"I-PP",
]
class A ( __UpperCAmelCase ):
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
if isinstance(UpperCamelCase__, UpperCamelCase__ ):
lowerCAmelCase_ = mode.value
lowerCAmelCase_ = os.path.join(UpperCamelCase__, f"{mode}.txt" )
lowerCAmelCase_ = 1
lowerCAmelCase_ = []
with open(UpperCamelCase__, encoding='''utf-8''' ) as f:
for sentence in parse_incr(UpperCamelCase__ ):
lowerCAmelCase_ = []
lowerCAmelCase_ = []
for token in sentence:
words.append(token['''form'''] )
labels.append(token['''upos'''] )
assert len(UpperCamelCase__ ) == len(UpperCamelCase__ )
if words:
examples.append(InputExample(guid=f"{mode}-{guid_index}", words=UpperCamelCase__, labels=UpperCamelCase__ ) )
guid_index += 1
return examples
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = 0
for sentence in parse_incr(UpperCamelCase__ ):
lowerCAmelCase_ = preds_list[example_id]
lowerCAmelCase_ = ''''''
for token in sentence:
out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) "
out += "\n"
writer.write(UpperCamelCase__ )
example_id += 1
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__ ):
"""simple docstring"""
if path:
with open(UpperCamelCase__, '''r''' ) as f:
return f.read().splitlines()
else:
return [
"ADJ",
"ADP",
"ADV",
"AUX",
"CCONJ",
"DET",
"INTJ",
"NOUN",
"NUM",
"PART",
"PRON",
"PROPN",
"PUNCT",
"SCONJ",
"SYM",
"VERB",
"X",
]
| 431
|
import copy
import inspect
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
VideoMAEForPreTraining,
VideoMAEForVideoClassification,
VideoMAEModel,
)
from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from transformers import VideoMAEImageProcessor
class A :
def __init__( self, UpperCamelCase__, UpperCamelCase__=13, UpperCamelCase__=10, UpperCamelCase__=3, UpperCamelCase__=2, UpperCamelCase__=2, UpperCamelCase__=2, UpperCamelCase__=True, UpperCamelCase__=True, UpperCamelCase__=32, UpperCamelCase__=5, UpperCamelCase__=4, UpperCamelCase__=37, UpperCamelCase__="gelu", UpperCamelCase__=0.1, UpperCamelCase__=0.1, UpperCamelCase__=10, UpperCamelCase__=0.02, UpperCamelCase__=0.9, UpperCamelCase__=None, ):
"""simple docstring"""
lowerCAmelCase_ = parent
lowerCAmelCase_ = batch_size
lowerCAmelCase_ = image_size
lowerCAmelCase_ = num_channels
lowerCAmelCase_ = patch_size
lowerCAmelCase_ = tubelet_size
lowerCAmelCase_ = num_frames
lowerCAmelCase_ = is_training
lowerCAmelCase_ = use_labels
lowerCAmelCase_ = hidden_size
lowerCAmelCase_ = num_hidden_layers
lowerCAmelCase_ = num_attention_heads
lowerCAmelCase_ = intermediate_size
lowerCAmelCase_ = hidden_act
lowerCAmelCase_ = hidden_dropout_prob
lowerCAmelCase_ = attention_probs_dropout_prob
lowerCAmelCase_ = type_sequence_label_size
lowerCAmelCase_ = initializer_range
lowerCAmelCase_ = mask_ratio
lowerCAmelCase_ = scope
# in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
lowerCAmelCase_ = (image_size // patch_size) ** 2
lowerCAmelCase_ = (num_frames // tubelet_size) * self.num_patches_per_frame
# use this variable to define bool_masked_pos
lowerCAmelCase_ = int(mask_ratio * self.seq_length )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = floats_tensor(
[self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] )
lowerCAmelCase_ = None
if self.use_labels:
lowerCAmelCase_ = ids_tensor([self.batch_size], self.type_sequence_label_size )
lowerCAmelCase_ = self.get_config()
return config, pixel_values, labels
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
return VideoMAEConfig(
image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_frames=self.num_frames, tubelet_size=self.tubelet_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, is_decoder=UpperCamelCase__, initializer_range=self.initializer_range, )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = VideoMAEModel(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
lowerCAmelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = VideoMAEForPreTraining(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
# important: each video needs to have the same number of masked patches
# hence we define a single mask, which we then repeat for each example in the batch
lowerCAmelCase_ = torch.ones((self.num_masks,) )
lowerCAmelCase_ = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] )
lowerCAmelCase_ = mask.expand(self.batch_size, -1 ).bool()
lowerCAmelCase_ = model(UpperCamelCase__, UpperCamelCase__ )
# model only returns predictions for masked patches
lowerCAmelCase_ = mask.sum().item()
lowerCAmelCase_ = 3 * self.tubelet_size * self.patch_size**2
self.parent.assertEqual(result.logits.shape, (self.batch_size, num_masked_patches, decoder_num_labels) )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = self.prepare_config_and_inputs()
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = config_and_inputs
lowerCAmelCase_ = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class A ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
__snake_case = (
(VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
)
__snake_case = (
{'feature-extraction': VideoMAEModel, 'video-classification': VideoMAEForVideoClassification}
if is_torch_available()
else {}
)
__snake_case = False
__snake_case = False
__snake_case = False
__snake_case = False
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = VideoMAEModelTester(self )
lowerCAmelCase_ = ConfigTester(self, config_class=UpperCamelCase__, has_text_modality=UpperCamelCase__, hidden_size=37 )
def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__=False ):
"""simple docstring"""
lowerCAmelCase_ = copy.deepcopy(UpperCamelCase__ )
if model_class == VideoMAEForPreTraining:
# important: each video needs to have the same number of masked patches
# hence we define a single mask, which we then repeat for each example in the batch
lowerCAmelCase_ = torch.ones((self.model_tester.num_masks,) )
lowerCAmelCase_ = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] )
lowerCAmelCase_ = mask.expand(self.model_tester.batch_size, -1 ).bool()
lowerCAmelCase_ = bool_masked_pos.to(UpperCamelCase__ )
if return_labels:
if model_class in [
*get_values(UpperCamelCase__ ),
]:
lowerCAmelCase_ = torch.zeros(
self.model_tester.batch_size, dtype=torch.long, device=UpperCamelCase__ )
return inputs_dict
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='''VideoMAE does not use inputs_embeds''' )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCAmelCase_ = model_class(UpperCamelCase__ )
self.assertIsInstance(model.get_input_embeddings(), (nn.Module) )
lowerCAmelCase_ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(UpperCamelCase__, nn.Linear ) )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCAmelCase_ = model_class(UpperCamelCase__ )
lowerCAmelCase_ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCAmelCase_ = [*signature.parameters.keys()]
lowerCAmelCase_ = ['''pixel_values''']
self.assertListEqual(arg_names[:1], UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase_ = VideoMAEModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
if not self.has_attentions:
pass
else:
lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
lowerCAmelCase_ = True
for model_class in self.all_model_classes:
lowerCAmelCase_ = self.model_tester.seq_length - self.model_tester.num_masks
lowerCAmelCase_ = (
num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
)
lowerCAmelCase_ = True
lowerCAmelCase_ = False
lowerCAmelCase_ = True
lowerCAmelCase_ = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
with torch.no_grad():
lowerCAmelCase_ = model(**self._prepare_for_class(UpperCamelCase__, UpperCamelCase__ ) )
lowerCAmelCase_ = outputs.attentions
self.assertEqual(len(UpperCamelCase__ ), self.model_tester.num_hidden_layers )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
lowerCAmelCase_ = True
lowerCAmelCase_ = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
with torch.no_grad():
lowerCAmelCase_ = model(**self._prepare_for_class(UpperCamelCase__, UpperCamelCase__ ) )
lowerCAmelCase_ = outputs.attentions
self.assertEqual(len(UpperCamelCase__ ), self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ), [self.model_tester.num_attention_heads, seq_len, seq_len], )
lowerCAmelCase_ = len(UpperCamelCase__ )
# Check attention is always last and order is fine
lowerCAmelCase_ = True
lowerCAmelCase_ = True
lowerCAmelCase_ = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
with torch.no_grad():
lowerCAmelCase_ = model(**self._prepare_for_class(UpperCamelCase__, UpperCamelCase__ ) )
self.assertEqual(out_len + 1, len(UpperCamelCase__ ) )
lowerCAmelCase_ = outputs.attentions
self.assertEqual(len(UpperCamelCase__ ), self.model_tester.num_hidden_layers )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ), [self.model_tester.num_attention_heads, seq_len, seq_len], )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
def check_hidden_states_output(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ):
lowerCAmelCase_ = model_class(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
with torch.no_grad():
lowerCAmelCase_ = model(**self._prepare_for_class(UpperCamelCase__, UpperCamelCase__ ) )
lowerCAmelCase_ = outputs.hidden_states
lowerCAmelCase_ = self.model_tester.num_hidden_layers + 1
self.assertEqual(len(UpperCamelCase__ ), UpperCamelCase__ )
lowerCAmelCase_ = self.model_tester.seq_length - self.model_tester.num_masks
lowerCAmelCase_ = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
self.assertListEqual(
list(hidden_states[0].shape[-2:] ), [seq_length, self.model_tester.hidden_size], )
lowerCAmelCase_ , lowerCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCAmelCase_ = True
check_hidden_states_output(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowerCAmelCase_ = True
check_hidden_states_output(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ )
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
pass
def __UpperCamelCase ( ):
lowerCAmelCase_ = hf_hub_download(
repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' )
lowerCAmelCase_ = np.load(_A )
return list(_A )
@require_torch
@require_vision
class A ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
return (
VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5] )
if is_vision_available()
else None
)
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics''' ).to(
UpperCamelCase__ )
lowerCAmelCase_ = self.default_image_processor
lowerCAmelCase_ = prepare_video()
lowerCAmelCase_ = image_processor(UpperCamelCase__, return_tensors='''pt''' ).to(UpperCamelCase__ )
# forward pass
with torch.no_grad():
lowerCAmelCase_ = model(**UpperCamelCase__ )
# verify the logits
lowerCAmelCase_ = torch.Size((1, 400) )
self.assertEqual(outputs.logits.shape, UpperCamelCase__ )
lowerCAmelCase_ = torch.tensor([0.3_669, -0.0_688, -0.2_421] ).to(UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3], UpperCamelCase__, atol=1E-4 ) )
@slow
def SCREAMING_SNAKE_CASE__ ( self ):
"""simple docstring"""
lowerCAmelCase_ = VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' ).to(UpperCamelCase__ )
lowerCAmelCase_ = self.default_image_processor
lowerCAmelCase_ = prepare_video()
lowerCAmelCase_ = image_processor(UpperCamelCase__, return_tensors='''pt''' ).to(UpperCamelCase__ )
# add boolean mask, indicating which patches to mask
lowerCAmelCase_ = hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''', filename='''bool_masked_pos.pt''' )
lowerCAmelCase_ = torch.load(UpperCamelCase__ )
# forward pass
with torch.no_grad():
lowerCAmelCase_ = model(**UpperCamelCase__ )
# verify the logits
lowerCAmelCase_ = torch.Size([1, 1408, 1536] )
lowerCAmelCase_ = torch.tensor(
[[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]], device=UpperCamelCase__ )
self.assertEqual(outputs.logits.shape, UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], UpperCamelCase__, atol=1E-4 ) )
# verify the loss (`config.norm_pix_loss` = `True`)
lowerCAmelCase_ = torch.tensor([0.5_142], device=UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.loss, UpperCamelCase__, atol=1E-4 ) )
# verify the loss (`config.norm_pix_loss` = `False`)
lowerCAmelCase_ = VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''', norm_pix_loss=UpperCamelCase__ ).to(
UpperCamelCase__ )
with torch.no_grad():
lowerCAmelCase_ = model(**UpperCamelCase__ )
lowerCAmelCase_ = torch.tensor(torch.tensor([0.6_469] ), device=UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.loss, UpperCamelCase__, atol=1E-4 ) )
| 431
| 1
|
'''simple docstring'''
def _A ( A__ , A__ , A__ ):
"""simple docstring"""
def update_area_of_max_square(A__ , A__ ) -> int:
# BASE CASE
if row >= rows or col >= cols:
return 0
__lowercase = update_area_of_max_square(A__ , col + 1 )
__lowercase = update_area_of_max_square(row + 1 , col + 1 )
__lowercase = update_area_of_max_square(row + 1 , A__ )
if mat[row][col]:
__lowercase = 1 + min([right, diagonal, down] )
__lowercase = max(largest_square_area[0] , A__ )
return sub_problem_sol
else:
return 0
__lowercase = [0]
update_area_of_max_square(0 , 0 )
return largest_square_area[0]
def _A ( A__ , A__ , A__ ):
"""simple docstring"""
def update_area_of_max_square_using_dp_array(
A__ , A__ , A__ ) -> int:
if row >= rows or col >= cols:
return 0
if dp_array[row][col] != -1:
return dp_array[row][col]
__lowercase = update_area_of_max_square_using_dp_array(A__ , col + 1 , A__ )
__lowercase = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , A__ )
__lowercase = update_area_of_max_square_using_dp_array(row + 1 , A__ , A__ )
if mat[row][col]:
__lowercase = 1 + min([right, diagonal, down] )
__lowercase = max(largest_square_area[0] , A__ )
__lowercase = sub_problem_sol
return sub_problem_sol
else:
return 0
__lowercase = [0]
__lowercase = [[-1] * cols for _ in range(A__ )]
update_area_of_max_square_using_dp_array(0 , 0 , A__ )
return largest_square_area[0]
def _A ( A__ , A__ , A__ ):
"""simple docstring"""
__lowercase = [[0] * (cols + 1) for _ in range(rows + 1 )]
__lowercase = 0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
__lowercase = dp_array[row][col + 1]
__lowercase = dp_array[row + 1][col + 1]
__lowercase = dp_array[row + 1][col]
if mat[row][col] == 1:
__lowercase = 1 + min(A__ , A__ , A__ )
__lowercase = max(dp_array[row][col] , A__ )
else:
__lowercase = 0
return largest_square_area
def _A ( A__ , A__ , A__ ):
"""simple docstring"""
__lowercase = [0] * (cols + 1)
__lowercase = [0] * (cols + 1)
__lowercase = 0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
__lowercase = current_row[col + 1]
__lowercase = next_row[col + 1]
__lowercase = next_row[col]
if mat[row][col] == 1:
__lowercase = 1 + min(A__ , A__ , A__ )
__lowercase = max(current_row[col] , A__ )
else:
__lowercase = 0
__lowercase = current_row
return largest_square_area
if __name__ == "__main__":
import doctest
doctest.testmod()
print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
| 624
|
'''simple docstring'''
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
import numpy as np
# Parrameters
lowerCAmelCase__ = (720, 1280) # Height, Width
lowerCAmelCase__ = (0.4, 0.6) # if height or width lower than this scale, drop it.
lowerCAmelCase__ = 1 / 100
lowerCAmelCase__ = ''''''
lowerCAmelCase__ = ''''''
lowerCAmelCase__ = ''''''
lowerCAmelCase__ = 250
def _A ( ):
"""simple docstring"""
__lowercase , __lowercase = get_dataset(A__ , A__ )
for index in range(A__ ):
__lowercase = random.sample(range(len(A__ ) ) , 4 )
__lowercase , __lowercase , __lowercase = update_image_and_anno(
A__ , A__ , A__ , A__ , A__ , filter_scale=A__ , )
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
__lowercase = random_chars(32 )
__lowercase = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0]
__lowercase = F"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}"
cva.imwrite(F"{file_root}.jpg" , A__ , [cva.IMWRITE_JPEG_QUALITY, 85] )
print(F"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}" )
__lowercase = []
for anno in new_annos:
__lowercase = anno[3] - anno[1]
__lowercase = anno[4] - anno[2]
__lowercase = anno[1] + width / 2
__lowercase = anno[2] + height / 2
__lowercase = F"{anno[0]} {x_center} {y_center} {width} {height}"
annos_list.append(A__ )
with open(F"{file_root}.txt" , '''w''' ) as outfile:
outfile.write('''\n'''.join(line for line in annos_list ) )
def _A ( A__ , A__ ):
"""simple docstring"""
__lowercase = []
__lowercase = []
for label_file in glob.glob(os.path.join(A__ , '''*.txt''' ) ):
__lowercase = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0]
with open(A__ ) as in_file:
__lowercase = in_file.readlines()
__lowercase = os.path.join(A__ , F"{label_name}.jpg" )
__lowercase = []
for obj_list in obj_lists:
__lowercase = obj_list.rstrip('''\n''' ).split(''' ''' )
__lowercase = float(obj[1] ) - float(obj[3] ) / 2
__lowercase = float(obj[2] ) - float(obj[4] ) / 2
__lowercase = float(obj[1] ) + float(obj[3] ) / 2
__lowercase = float(obj[2] ) + float(obj[4] ) / 2
boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] )
if not boxes:
continue
img_paths.append(A__ )
labels.append(A__ )
return img_paths, labels
def _A ( A__ , A__ , A__ , A__ , A__ , A__ = 0.0 , ):
"""simple docstring"""
__lowercase = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta )
__lowercase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
__lowercase = scale_range[0] + random.random() * (scale_range[1] - scale_range[0])
__lowercase = int(scale_x * output_size[1] )
__lowercase = int(scale_y * output_size[0] )
__lowercase = []
__lowercase = []
for i, index in enumerate(A__ ):
__lowercase = all_img_list[index]
path_list.append(A__ )
__lowercase = all_annos[index]
__lowercase = cva.imread(A__ )
if i == 0: # top-left
__lowercase = cva.resize(A__ , (divid_point_x, divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = bbox[1] * scale_x
__lowercase = bbox[2] * scale_y
__lowercase = bbox[3] * scale_x
__lowercase = bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 1: # top-right
__lowercase = cva.resize(A__ , (output_size[1] - divid_point_x, divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = scale_x + bbox[1] * (1 - scale_x)
__lowercase = bbox[2] * scale_y
__lowercase = scale_x + bbox[3] * (1 - scale_x)
__lowercase = bbox[4] * scale_y
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
elif i == 2: # bottom-left
__lowercase = cva.resize(A__ , (divid_point_x, output_size[0] - divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = bbox[1] * scale_x
__lowercase = scale_y + bbox[2] * (1 - scale_y)
__lowercase = bbox[3] * scale_x
__lowercase = scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
else: # bottom-right
__lowercase = cva.resize(
A__ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) )
__lowercase = img
for bbox in img_annos:
__lowercase = scale_x + bbox[1] * (1 - scale_x)
__lowercase = scale_y + bbox[2] * (1 - scale_y)
__lowercase = scale_x + bbox[3] * (1 - scale_x)
__lowercase = scale_y + bbox[4] * (1 - scale_y)
new_anno.append([bbox[0], xmin, ymin, xmax, ymax] )
# Remove bounding box small than scale of filter
if filter_scale > 0:
__lowercase = [
anno
for anno in new_anno
if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2])
]
return output_img, new_anno, path_list[0]
def _A ( A__ ):
"""simple docstring"""
assert number_char > 1, "The number of character should greater than 1"
__lowercase = ascii_lowercase + digits
return "".join(random.choice(A__ ) for _ in range(A__ ) )
if __name__ == "__main__":
main()
print('''DONE ✅''')
| 624
| 1
|
"""simple docstring"""
from typing import Any, Dict, List, Union
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from ..image_utils import load_image
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
_UpperCAmelCase = logging.get_logger(__name__)
_UpperCAmelCase = Dict[str, Any]
_UpperCAmelCase = List[Prediction]
@add_end_docstrings(UpperCamelCase_ )
class a ( UpperCamelCase_ ):
def __init__( self : Tuple , *lowerCAmelCase : List[str] , **lowerCAmelCase : int ) -> List[str]:
'''simple docstring'''
super().__init__(*lowercase_ , **lowercase_ )
if self.framework == "tf":
raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' )
requires_backends(self , """vision""" )
self.check_model_type(
dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) )
def lowerCamelCase__ ( self : List[str] , **lowerCAmelCase : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Union[str, Any] ={}
if "threshold" in kwargs:
SCREAMING_SNAKE_CASE_: Any =kwargs['threshold']
return {}, {}, postprocess_kwargs
def __call__( self : Any , *lowerCAmelCase : Optional[Any] , **lowerCAmelCase : Dict ) -> Union[Predictions, List[Prediction]]:
'''simple docstring'''
return super().__call__(*lowercase_ , **lowercase_ )
def lowerCamelCase__ ( self : Any , lowerCAmelCase : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Union[str, Any] =load_image(lowercase_ )
SCREAMING_SNAKE_CASE_: Tuple =torch.IntTensor([[image.height, image.width]] )
SCREAMING_SNAKE_CASE_: Optional[Any] =self.image_processor(images=[image] , return_tensors="""pt""" )
if self.tokenizer is not None:
SCREAMING_SNAKE_CASE_: Tuple =self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" )
SCREAMING_SNAKE_CASE_: Any =target_size
return inputs
def lowerCamelCase__ ( self : List[str] , lowerCAmelCase : Any ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE_: List[Any] =model_inputs.pop("""target_size""" )
SCREAMING_SNAKE_CASE_: Union[str, Any] =self.model(**lowercase_ )
SCREAMING_SNAKE_CASE_: str =outputs.__class__({"""target_size""": target_size, **outputs} )
if self.tokenizer is not None:
SCREAMING_SNAKE_CASE_: Union[str, Any] =model_inputs['bbox']
return model_outputs
def lowerCamelCase__ ( self : Any , lowerCAmelCase : List[Any] , lowerCAmelCase : Dict=0.9 ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE_: Dict =model_outputs['target_size']
if self.tokenizer is not None:
# This is a LayoutLMForTokenClassification variant.
# The OCR got the boxes and the model classified the words.
SCREAMING_SNAKE_CASE_: Union[str, Any] =target_size[0].tolist()
def unnormalize(lowerCAmelCase : Tuple ):
return self._get_bounding_box(
torch.Tensor(
[
(width * bbox[0] / 1000),
(height * bbox[1] / 1000),
(width * bbox[2] / 1000),
(height * bbox[3] / 1000),
] ) )
SCREAMING_SNAKE_CASE_: List[Any] =model_outputs['logits'].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 )
SCREAMING_SNAKE_CASE_: Tuple =[self.model.config.idalabel[prediction] for prediction in classes.tolist()]
SCREAMING_SNAKE_CASE_: Dict =[unnormalize(lowercase_ ) for bbox in model_outputs['bbox'].squeeze(0 )]
SCREAMING_SNAKE_CASE_: Optional[Any] =['score', 'label', 'box']
SCREAMING_SNAKE_CASE_: Union[str, Any] =[dict(zip(lowercase_ , lowercase_ ) ) for vals in zip(scores.tolist() , lowercase_ , lowercase_ ) if vals[0] > threshold]
else:
# This is a regular ForObjectDetectionModel
SCREAMING_SNAKE_CASE_: Tuple =self.image_processor.post_process_object_detection(lowercase_ , lowercase_ , lowercase_ )
SCREAMING_SNAKE_CASE_: Optional[int] =raw_annotations[0]
SCREAMING_SNAKE_CASE_: Union[str, Any] =raw_annotation['scores']
SCREAMING_SNAKE_CASE_: int =raw_annotation['labels']
SCREAMING_SNAKE_CASE_: Union[str, Any] =raw_annotation['boxes']
SCREAMING_SNAKE_CASE_: Optional[Any] =scores.tolist()
SCREAMING_SNAKE_CASE_: Tuple =[self.model.config.idalabel[label.item()] for label in labels]
SCREAMING_SNAKE_CASE_: Union[str, Any] =[self._get_bounding_box(lowercase_ ) for box in boxes]
# {"scores": [...], ...} --> [{"score":x, ...}, ...]
SCREAMING_SNAKE_CASE_: List[Any] =['score', 'label', 'box']
SCREAMING_SNAKE_CASE_: Optional[Any] =[
dict(zip(lowercase_ , lowercase_ ) )
for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] )
]
return annotation
def lowerCamelCase__ ( self : int , lowerCAmelCase : "torch.Tensor" ) -> Dict[str, int]:
'''simple docstring'''
if self.framework != "pt":
raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" )
SCREAMING_SNAKE_CASE_: Tuple =box.int().tolist()
SCREAMING_SNAKE_CASE_: Union[str, Any] ={
'xmin': xmin,
'ymin': ymin,
'xmax': xmax,
'ymax': ymax,
}
return bbox
| 409
|
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments
from transformers.testing_utils import TestCasePlus, require_torch, slow
from transformers.utils import is_datasets_available
if is_datasets_available():
import datasets
class A ( UpperCamelCase_ ):
@slow
@require_torch
def lowerCamelCase ( self : Any ) -> Any:
"""simple docstring"""
_lowerCamelCase : int =EncoderDecoderModel.from_encoder_decoder_pretrained('prajjwal1/bert-tiny' , 'prajjwal1/bert-tiny' )
_lowerCamelCase : Dict =BertTokenizer.from_pretrained('bert-base-uncased' )
_lowerCamelCase : Union[str, Any] =bertabert.config.encoder.vocab_size
_lowerCamelCase : Dict =tokenizer.sep_token_id
_lowerCamelCase : List[Any] =tokenizer.cls_token_id
_lowerCamelCase : Optional[int] =128
_lowerCamelCase : int =datasets.load_dataset('cnn_dailymail' , '3.0.0' , split='train[:1%]' )
_lowerCamelCase : int =datasets.load_dataset('cnn_dailymail' , '3.0.0' , split='validation[:1%]' )
_lowerCamelCase : Optional[int] =train_dataset.select(range(32 ) )
_lowerCamelCase : Optional[int] =val_dataset.select(range(16 ) )
_lowerCamelCase : Optional[int] =4
def _map_to_encoder_decoder_inputs(lowercase_ : Tuple ):
# Tokenizer will automatically set [BOS] <text> [EOS]
_lowerCamelCase : Optional[int] =tokenizer(batch['article'] , padding='max_length' , truncation=lowercase_ , max_length=512 )
_lowerCamelCase : List[str] =tokenizer(batch['highlights'] , padding='max_length' , truncation=lowercase_ , max_length=128 )
_lowerCamelCase : List[str] =inputs.input_ids
_lowerCamelCase : Any =inputs.attention_mask
_lowerCamelCase : List[str] =outputs.input_ids
_lowerCamelCase : int =outputs.input_ids.copy()
_lowerCamelCase : List[str] =[
[-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch['labels']
]
_lowerCamelCase : Dict =outputs.attention_mask
assert all(len(lowercase_ ) == 512 for x in inputs.input_ids )
assert all(len(lowercase_ ) == 128 for x in outputs.input_ids )
return batch
def _compute_metrics(lowercase_ : str ):
_lowerCamelCase : List[Any] =pred.label_ids
_lowerCamelCase : List[Any] =pred.predictions
# all unnecessary tokens are removed
_lowerCamelCase : str =tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ )
_lowerCamelCase : Tuple =tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ )
_lowerCamelCase : List[str] =sum([int(pred_str[i] == label_str[i] ) for i in range(len(lowercase_ ) )] ) / len(lowercase_ )
return {"accuracy": accuracy}
# map train dataset
_lowerCamelCase : Tuple =train_dataset.map(
_map_to_encoder_decoder_inputs , batched=lowercase_ , batch_size=lowercase_ , remove_columns=['article', 'highlights'] , )
train_dataset.set_format(
type='torch' , columns=['input_ids', 'attention_mask', 'decoder_input_ids', 'decoder_attention_mask', 'labels'] , )
# same for validation dataset
_lowerCamelCase : Tuple =val_dataset.map(
_map_to_encoder_decoder_inputs , batched=lowercase_ , batch_size=lowercase_ , remove_columns=['article', 'highlights'] , )
val_dataset.set_format(
type='torch' , columns=['input_ids', 'attention_mask', 'decoder_input_ids', 'decoder_attention_mask', 'labels'] , )
_lowerCamelCase : Dict =self.get_auto_remove_tmp_dir()
_lowerCamelCase : Optional[int] =SeqaSeqTrainingArguments(
output_dir=lowercase_ , per_device_train_batch_size=lowercase_ , per_device_eval_batch_size=lowercase_ , predict_with_generate=lowercase_ , evaluation_strategy='steps' , do_train=lowercase_ , do_eval=lowercase_ , warmup_steps=0 , eval_steps=2 , logging_steps=2 , )
# instantiate trainer
_lowerCamelCase : Optional[Any] =SeqaSeqTrainer(
model=lowercase_ , args=lowercase_ , compute_metrics=_compute_metrics , train_dataset=lowercase_ , eval_dataset=lowercase_ , tokenizer=lowercase_ , )
# start training
trainer.train()
| 464
| 0
|
from math import sqrt
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> bool:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (
number >= 0
), "'number' must been an int and positive"
A__ = True
# 0 and 1 are none primes.
if number <= 1:
A__ = False
for divisor in range(2 , int(round(sqrt(SCREAMING_SNAKE_CASE_ ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
A__ = False
break
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'status' must been from type bool"
return status
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> Any:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
A__ = list(range(2 , n + 1 ) )
A__ = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(SCREAMING_SNAKE_CASE_ ) ):
for j in range(i + 1 , len(SCREAMING_SNAKE_CASE_ ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
A__ = 0
# filters actual prime numbers.
A__ = [x for x in begin_list if x != 0]
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'ans' must been from type list"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Tuple:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (n > 2), "'N' must been an int and > 2"
A__ = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2 , n + 1 ):
if is_prime(SCREAMING_SNAKE_CASE_ ):
ans.append(SCREAMING_SNAKE_CASE_ )
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'ans' must been from type list"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Optional[Any]:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and number >= 0, "'number' must been an int and >= 0"
A__ = [] # this list will be returns of the function.
# potential prime number factors.
A__ = 2
A__ = number
if number == 0 or number == 1:
ans.append(SCREAMING_SNAKE_CASE_ )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(SCREAMING_SNAKE_CASE_ ):
while quotient != 1:
if is_prime(SCREAMING_SNAKE_CASE_ ) and (quotient % factor == 0):
ans.append(SCREAMING_SNAKE_CASE_ )
quotient /= factor
else:
factor += 1
else:
ans.append(SCREAMING_SNAKE_CASE_ )
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'ans' must been from type list"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> int:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (
number >= 0
), "'number' bust been an int and >= 0"
A__ = 0
# prime factorization of 'number'
A__ = prime_factorization(SCREAMING_SNAKE_CASE_ )
A__ = max(SCREAMING_SNAKE_CASE_ )
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'ans' must been from type int"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (
number >= 0
), "'number' bust been an int and >= 0"
A__ = 0
# prime factorization of 'number'
A__ = prime_factorization(SCREAMING_SNAKE_CASE_ )
A__ = min(SCREAMING_SNAKE_CASE_ )
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'ans' must been from type int"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'number' must been an int"
assert isinstance(number % 2 == 0 , SCREAMING_SNAKE_CASE_ ), "compare bust been from type bool"
return number % 2 == 0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[Any] ) -> str:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), "'number' must been an int"
assert isinstance(number % 2 != 0 , SCREAMING_SNAKE_CASE_ ), "compare bust been from type bool"
return number % 2 != 0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> int:
'''simple docstring'''
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (number > 2) and is_even(SCREAMING_SNAKE_CASE_ )
), "'number' must been an int, even and > 2"
A__ = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
A__ = get_prime_numbers(SCREAMING_SNAKE_CASE_ )
A__ = len(SCREAMING_SNAKE_CASE_ )
# run variable for while-loops.
A__ = 0
A__ = None
# exit variable. for break up the loops
A__ = True
while i < len_pn and loop:
A__ = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
A__ = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and (len(SCREAMING_SNAKE_CASE_ ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> Any:
'''simple docstring'''
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
A__ = 0
while numbera != 0:
A__ = numbera % numbera
A__ = numbera
A__ = rest
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] , SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]:
'''simple docstring'''
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
A__ = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
A__ = prime_factorization(SCREAMING_SNAKE_CASE_ )
A__ = prime_factorization(SCREAMING_SNAKE_CASE_ )
elif numbera == 1 or numbera == 1:
A__ = []
A__ = []
A__ = max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
A__ = 0
A__ = 0
A__ = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
A__ = prime_fac_a.count(SCREAMING_SNAKE_CASE_ )
A__ = prime_fac_a.count(SCREAMING_SNAKE_CASE_ )
for _ in range(max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ):
ans *= n
else:
A__ = prime_fac_a.count(SCREAMING_SNAKE_CASE_ )
for _ in range(SCREAMING_SNAKE_CASE_ ):
ans *= n
done.append(SCREAMING_SNAKE_CASE_ )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
A__ = prime_fac_a.count(SCREAMING_SNAKE_CASE_ )
for _ in range(SCREAMING_SNAKE_CASE_ ):
ans *= n
done.append(SCREAMING_SNAKE_CASE_ )
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Dict:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (n >= 0), "'number' must been a positive int"
A__ = 0
A__ = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(SCREAMING_SNAKE_CASE_ ):
ans += 1
# precondition
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and is_prime(
SCREAMING_SNAKE_CASE_ ), "'ans' must been a prime number and from type int"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict , SCREAMING_SNAKE_CASE_: Any ) -> Dict:
'''simple docstring'''
assert (
is_prime(SCREAMING_SNAKE_CASE_ ) and is_prime(SCREAMING_SNAKE_CASE_ ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
A__ = p_number_a + 1 # jump to the next number
A__ = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(SCREAMING_SNAKE_CASE_ ):
number += 1
while number < p_number_a:
ans.append(SCREAMING_SNAKE_CASE_ )
number += 1
# fetch the next prime number.
while not is_prime(SCREAMING_SNAKE_CASE_ ):
number += 1
# precondition
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and ans[0] != p_number_a
and ans[len(SCREAMING_SNAKE_CASE_ ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Dict:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (n >= 1), "'n' must been int and >= 1"
A__ = [] # will be returned.
for divisor in range(1 , n + 1 ):
if n % divisor == 0:
ans.append(SCREAMING_SNAKE_CASE_ )
# precondition
assert ans[0] == 1 and ans[len(SCREAMING_SNAKE_CASE_ ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (
number > 1
), "'number' must been an int and >= 1"
A__ = get_divisors(SCREAMING_SNAKE_CASE_ )
# precondition
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and (divisors[0] == 1)
and (divisors[len(SCREAMING_SNAKE_CASE_ ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: Optional[int] ) -> List[Any]:
'''simple docstring'''
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
A__ = gcd(abs(SCREAMING_SNAKE_CASE_ ) , abs(SCREAMING_SNAKE_CASE_ ) )
# precondition
assert (
isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> Dict:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (n >= 0), "'n' must been a int and >= 0"
A__ = 1 # this will be return.
for factor in range(1 , n + 1 ):
ans *= factor
return ans
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> str:
'''simple docstring'''
assert isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and (n >= 0), "'n' must been an int and >= 0"
A__ = 0
A__ = 1
A__ = 1 # this will be return
for _ in range(n - 1 ):
A__ = ans
ans += fiba
A__ = tmp
return ans
| 626
|
from __future__ import annotations
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[int] , SCREAMING_SNAKE_CASE_: list[int] , SCREAMING_SNAKE_CASE_: list[int] , SCREAMING_SNAKE_CASE_: list[list[str]] , SCREAMING_SNAKE_CASE_: int , ) -> None:
'''simple docstring'''
A__ = len(SCREAMING_SNAKE_CASE_ )
# If row is equal to the size of the board it means there are a queen in each row in
# the current board (possible_board)
if row == n:
# We convert the variable possible_board that looks like this: [1, 3, 0, 2] to
# this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']
boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board] )
return
# We iterate each column in the row to find all possible results in each row
for col in range(SCREAMING_SNAKE_CASE_ ):
# We apply that we learned previously. First we check that in the current board
# (possible_board) there are not other same value because if there is it means
# that there are a collision in vertical. Then we apply the two formulas we
# learned before:
#
# 45º: y - x = b or 45: row - col = b
# 135º: y + x = b or row + col = b.
#
# And we verify if the results of this two formulas not exist in their variables
# respectively. (diagonal_right_collisions, diagonal_left_collisions)
#
# If any or these are True it means there is a collision so we continue to the
# next value in the for loop.
if (
col in possible_board
or row - col in diagonal_right_collisions
or row + col in diagonal_left_collisions
):
continue
# If it is False we call dfs function again and we update the inputs
depth_first_search(
[*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , )
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> None:
'''simple docstring'''
A__ = []
depth_first_search([] , [] , [] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Print all the boards
for board in boards:
for column in board:
print(SCREAMING_SNAKE_CASE_ )
print("" )
print(len(SCREAMING_SNAKE_CASE_ ) , "solutions were found." )
if __name__ == "__main__":
import doctest
doctest.testmod()
n_queens_solution(4)
| 626
| 1
|
"""simple docstring"""
class _lowerCAmelCase :
"""simple docstring"""
def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :Tuple = None
lowerCAmelCase__ :Any = None
lowerCAmelCase__ :Any = graph
self._normalize_graph(__UpperCAmelCase , __UpperCAmelCase )
lowerCAmelCase__ :int = len(__UpperCAmelCase )
lowerCAmelCase__ :Optional[int] = None
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ):
'''simple docstring'''
if sources is int:
lowerCAmelCase__ :List[Any] = [sources]
if sinks is int:
lowerCAmelCase__ :int = [sinks]
if len(__UpperCAmelCase ) == 0 or len(__UpperCAmelCase ) == 0:
return
lowerCAmelCase__ :List[str] = sources[0]
lowerCAmelCase__ :str = sinks[0]
# make fake vertex if there are more
# than one source or sink
if len(__UpperCAmelCase ) > 1 or len(__UpperCAmelCase ) > 1:
lowerCAmelCase__ :Any = 0
for i in sources:
max_input_flow += sum(self.graph[i] )
lowerCAmelCase__ :Optional[int] = len(self.graph ) + 1
for room in self.graph:
room.insert(0 , 0 )
self.graph.insert(0 , [0] * size )
for i in sources:
lowerCAmelCase__ :Optional[Any] = max_input_flow
lowerCAmelCase__ :int = 0
lowerCAmelCase__ :Optional[Any] = len(self.graph ) + 1
for room in self.graph:
room.append(0 )
self.graph.append([0] * size )
for i in sinks:
lowerCAmelCase__ :Any = max_input_flow
lowerCAmelCase__ :int = size - 1
def snake_case ( self ):
'''simple docstring'''
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 snake_case ( self , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = algorithm(self )
class _lowerCAmelCase :
"""simple docstring"""
def __init__( self , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :str = flow_network
lowerCAmelCase__ :Optional[int] = flow_network.verticesCount
lowerCAmelCase__ :Optional[Any] = flow_network.sourceIndex
lowerCAmelCase__ :Dict = flow_network.sinkIndex
# it's just a reference, so you shouldn't change
# it in your algorithms, use deep copy before doing that
lowerCAmelCase__ :Optional[int] = flow_network.graph
lowerCAmelCase__ :Optional[Any] = False
def snake_case ( self ):
'''simple docstring'''
if not self.executed:
self._algorithm()
lowerCAmelCase__ :List[Any] = True
def snake_case ( self ):
'''simple docstring'''
pass
class _lowerCAmelCase ( a ):
"""simple docstring"""
def __init__( self , __UpperCAmelCase ):
'''simple docstring'''
super().__init__(__UpperCAmelCase )
# use this to save your result
lowerCAmelCase__ :Optional[int] = -1
def snake_case ( self ):
'''simple docstring'''
if not self.executed:
raise Exception('You should execute algorithm before using its result!' )
return self.maximum_flow
class _lowerCAmelCase ( a ):
"""simple docstring"""
def __init__( self , __UpperCAmelCase ):
'''simple docstring'''
super().__init__(__UpperCAmelCase )
lowerCAmelCase__ :int = [[0] * self.verticies_count for i in range(self.verticies_count )]
lowerCAmelCase__ :Union[str, Any] = [0] * self.verticies_count
lowerCAmelCase__ :Optional[int] = [0] * self.verticies_count
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Dict = 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
lowerCAmelCase__ :List[str] = [
i
for i in range(self.verticies_count )
if i != self.source_index and i != self.sink_index
]
# move through list
lowerCAmelCase__ :str = 0
while i < len(__UpperCAmelCase ):
lowerCAmelCase__ :Any = vertices_list[i]
lowerCAmelCase__ :List[Any] = self.heights[vertex_index]
self.process_vertex(__UpperCAmelCase )
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(__UpperCAmelCase ) )
lowerCAmelCase__ :int = 0
else:
i += 1
lowerCAmelCase__ :Any = sum(self.preflow[self.source_index] )
def snake_case ( self , __UpperCAmelCase ):
'''simple docstring'''
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(__UpperCAmelCase , __UpperCAmelCase )
self.relabel(__UpperCAmelCase )
def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = 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 snake_case ( self , __UpperCAmelCase ):
'''simple docstring'''
lowerCAmelCase__ :Union[str, Any] = 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):
lowerCAmelCase__ :Union[str, Any] = self.heights[to_index]
if min_height is not None:
lowerCAmelCase__ :Optional[Any] = min_height + 1
if __name__ == "__main__":
__A = [0]
__A = [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 = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]]
# prepare our network
__A = FlowNetwork(graph, entrances, exits)
# set algorithm
flow_network.set_maximum_flow_algorithm(PushRelabelExecutor)
# and calculate
__A = flow_network.find_maximum_flow()
print(F'''maximum flow is {maximum_flow}''')
| 93
|
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available
__A = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A = ["""MLukeTokenizer"""]
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mluke import MLukeTokenizer
else:
import sys
__A = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 93
| 1
|
class snake_case__ :
"""simple docstring"""
def __init__( self : Dict , __lowerCamelCase : int , __lowerCamelCase : Tuple=None , __lowerCamelCase : Optional[int]=None ) -> List[str]:
a = data
a = previous
a = next_node
def __str__( self : Dict ) -> str:
return f"""{self.data}"""
def __UpperCAmelCase ( self : Tuple ) -> int:
return self.data
def __UpperCAmelCase ( self : Optional[int] ) -> Dict:
return self.next
def __UpperCAmelCase ( self : List[Any] ) -> Optional[Any]:
return self.previous
class snake_case__ :
"""simple docstring"""
def __init__( self : Dict , __lowerCamelCase : Any ) -> List[str]:
a = head
def __iter__( self : List[str] ) -> List[str]:
return self
def __UpperCAmelCase ( self : int ) -> List[str]:
if not self.current:
raise StopIteration
else:
a = self.current.get_data()
a = self.current.get_next()
return value
class snake_case__ :
"""simple docstring"""
def __init__( self : str ) -> List[str]:
a = None # First node in list
a = None # Last node in list
def __str__( self : str ) -> Optional[int]:
a = self.head
a = []
while current is not None:
nodes.append(current.get_data() )
a = current.get_next()
return " ".join(str(__lowerCamelCase ) for node in nodes )
def __contains__( self : Optional[Any] , __lowerCamelCase : int ) -> Optional[int]:
a = self.head
while current:
if current.get_data() == value:
return True
a = current.get_next()
return False
def __iter__( self : Dict ) -> List[Any]:
return LinkedListIterator(self.head )
def __UpperCAmelCase ( self : Dict ) -> Any:
if self.head:
return self.head.get_data()
return None
def __UpperCAmelCase ( self : List[Any] ) -> int:
if self.tail:
return self.tail.get_data()
return None
def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : Node ) -> None:
if self.head is None:
a = node
a = node
else:
self.insert_before_node(self.head , __lowerCamelCase )
def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Node ) -> None:
if self.head is None:
self.set_head(__lowerCamelCase )
else:
self.insert_after_node(self.tail , __lowerCamelCase )
def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : int ) -> None:
a = Node(__lowerCamelCase )
if self.head is None:
self.set_head(__lowerCamelCase )
else:
self.set_tail(__lowerCamelCase )
def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : Node , __lowerCamelCase : Node ) -> None:
a = node
a = node.previous
if node.get_previous() is None:
a = node_to_insert
else:
a = node_to_insert
a = node_to_insert
def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : Node , __lowerCamelCase : Node ) -> None:
a = node
a = node.next
if node.get_next() is None:
a = node_to_insert
else:
a = node_to_insert
a = node_to_insert
def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : int , __lowerCamelCase : int ) -> None:
a = 1
a = Node(__lowerCamelCase )
a = self.head
while node:
if current_position == position:
self.insert_before_node(__lowerCamelCase , __lowerCamelCase )
return
current_position += 1
a = node.next
self.insert_after_node(self.tail , __lowerCamelCase )
def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : int ) -> Node:
a = self.head
while node:
if node.get_data() == item:
return node
a = node.get_next()
raise Exception("Node not found" )
def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : Optional[Any] ) -> str:
if (node := self.get_node(__lowerCamelCase )) is not None:
if node == self.head:
a = self.head.get_next()
if node == self.tail:
a = self.tail.get_previous()
self.remove_node_pointers(__lowerCamelCase )
@staticmethod
def __UpperCAmelCase ( __lowerCamelCase : Node ) -> None:
if node.get_next():
a = node.previous
if node.get_previous():
a = node.next
a = None
a = None
def __UpperCAmelCase ( self : Tuple ) -> str:
return self.head is None
def __magic_name__ ( ):
'''simple docstring'''
if __name__ == "__main__":
import doctest
doctest.testmod()
| 662
|
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_big_bird import BigBirdTokenizer
else:
__lowerCAmelCase : Optional[int] = None
__lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
__lowerCAmelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}
__lowerCAmelCase : List[Any] = {
'vocab_file': {
'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model',
'google/bigbird-roberta-large': (
'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model'
),
'google/bigbird-base-trivia-itc': (
'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model'
),
},
'tokenizer_file': {
'google/bigbird-roberta-base': (
'https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json'
),
'google/bigbird-roberta-large': (
'https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json'
),
'google/bigbird-base-trivia-itc': (
'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json'
),
},
}
__lowerCAmelCase : List[str] = {
'google/bigbird-roberta-base': 4096,
'google/bigbird-roberta-large': 4096,
'google/bigbird-base-trivia-itc': 4096,
}
__lowerCAmelCase : Any = '▁'
class snake_case__ (_UpperCamelCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE_ : str = BigBirdTokenizer
SCREAMING_SNAKE_CASE_ : str = ["""input_ids""", """attention_mask"""]
SCREAMING_SNAKE_CASE_ : List[int] = []
def __init__( self : int , __lowerCamelCase : Any=None , __lowerCamelCase : List[str]=None , __lowerCamelCase : Optional[int]="<unk>" , __lowerCamelCase : int="<s>" , __lowerCamelCase : Optional[Any]="</s>" , __lowerCamelCase : Tuple="<pad>" , __lowerCamelCase : Tuple="[SEP]" , __lowerCamelCase : Dict="[MASK]" , __lowerCamelCase : Tuple="[CLS]" , **__lowerCamelCase : Optional[Any] , ) -> List[Any]:
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else bos_token
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else eos_token
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else unk_token
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else pad_token
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else cls_token
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else sep_token
# Mask token behave like a normal word, i.e. include the space before it
a = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else mask_token
super().__init__(
__lowerCamelCase , tokenizer_file=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , pad_token=__lowerCamelCase , cls_token=__lowerCamelCase , mask_token=__lowerCamelCase , **__lowerCamelCase , )
a = vocab_file
a = False if not self.vocab_file else True
def __UpperCAmelCase ( self : str , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ) -> List[int]:
a = [self.sep_token_id]
a = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None , __lowerCamelCase : bool = False ) -> List[int]:
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
"You should not supply a second sequence if the provided sequence of "
"ids is already formatted with special tokens for the model." )
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is None:
return [1] + ([0] * len(__lowerCamelCase )) + [1]
return [1] + ([0] * len(__lowerCamelCase )) + [1] + ([0] * len(__lowerCamelCase )) + [1]
def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ) -> List[int]:
a = [self.sep_token_id]
a = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ) -> Tuple[str]:
if not self.can_save_slow_tokenizer:
raise ValueError(
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
"tokenizer." )
if not os.path.isdir(__lowerCamelCase ):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
return
a = os.path.join(
__lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCamelCase ):
copyfile(self.vocab_file , __lowerCamelCase )
return (out_vocab_file,)
| 662
| 1
|
'''simple docstring'''
import math
__UpperCamelCase = 10
__UpperCamelCase = 7
__UpperCamelCase = BALLS_PER_COLOUR * NUM_COLOURS
def _a ( _lowerCamelCase = 20 ) -> str:
"""simple docstring"""
__snake_case : Optional[int] = math.comb(_lowerCamelCase , _lowerCamelCase )
__snake_case : Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , _lowerCamelCase )
__snake_case : Optional[int] = NUM_COLOURS * (1 - missing_colour / total)
return F'''{result:.9f}'''
if __name__ == "__main__":
print(solution(20))
| 26
|
'''simple docstring'''
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
__UpperCamelCase = logging.get_logger(__name__)
__UpperCamelCase = [
["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 ( _lowerCamelCase ) -> Union[str, Any]:
"""simple docstring"""
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
__snake_case : List[str] = k.replace(_lowerCamelCase , _lowerCamelCase )
if k.startswith("""encoder""" ):
__snake_case : Optional[int] = k.replace(""".attn""" , """.self_attn""" )
__snake_case : Tuple = k.replace("""norm1""" , """self_attn_layer_norm""" )
__snake_case : List[str] = k.replace("""norm2""" , """final_layer_norm""" )
elif k.startswith("""decoder""" ):
__snake_case : List[Any] = k.replace("""norm1""" , """self_attn_layer_norm""" )
__snake_case : str = k.replace("""norm2""" , """encoder_attn_layer_norm""" )
__snake_case : Optional[int] = k.replace("""norm3""" , """final_layer_norm""" )
return k
def _a ( _lowerCamelCase ) -> Any:
"""simple docstring"""
__snake_case : Optional[int] = [
"""model.encoder.layernorm_embedding.weight""",
"""model.encoder.layernorm_embedding.bias""",
"""model.decoder.layernorm_embedding.weight""",
"""model.decoder.layernorm_embedding.bias""",
]
for k in keys:
__snake_case : Optional[Any] = sd.pop(_lowerCamelCase )
__snake_case : List[str] = k.replace("""layernorm_embedding""" , """layer_norm""" )
assert new_k not in sd
__snake_case : Union[str, Any] = v
__UpperCamelCase = ["START"]
@torch.no_grad()
def _a ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> Dict:
"""simple docstring"""
__snake_case : Optional[int] = torch.load(_lowerCamelCase , map_location="""cpu""" )
__snake_case : Dict = model["""model"""]
__snake_case : Optional[int] = BlenderbotConfig.from_json_file(_lowerCamelCase )
__snake_case : Union[str, Any] = BlenderbotForConditionalGeneration(_lowerCamelCase )
__snake_case : List[Any] = m.model.state_dict().keys()
__snake_case : int = []
__snake_case : Union[str, Any] = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
__snake_case : Optional[int] = rename_state_dict_key(_lowerCamelCase )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
__snake_case : str = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(_lowerCamelCase )
m.model.load_state_dict(_lowerCamelCase , strict=_lowerCamelCase )
m.half()
m.save_pretrained(_lowerCamelCase )
if __name__ == "__main__":
__UpperCamelCase = 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"
)
__UpperCamelCase = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 26
| 1
|
'''simple docstring'''
class snake_case__ :
def __init__( self : Dict ) -> str:
UpperCAmelCase_ : Union[str, Any] = 0
UpperCAmelCase_ : List[Any] = 0
UpperCAmelCase_ : Optional[int] = {}
def A ( self : Optional[int] , _A : List[Any] ) -> Optional[int]:
if vertex not in self.adjacency:
UpperCAmelCase_ : List[str] = {}
self.num_vertices += 1
def A ( self : Dict , _A : Optional[int] , _A : Any , _A : Dict ) -> Union[str, Any]:
self.add_vertex(_A )
self.add_vertex(_A )
if head == tail:
return
UpperCAmelCase_ : int = weight
UpperCAmelCase_ : int = weight
def A ( self : Any ) -> List[Any]:
UpperCAmelCase_ : List[str] = self.get_edges()
for edge in edges:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = edge
edges.remove((tail, head, weight) )
for i in range(len(_A ) ):
UpperCAmelCase_ : str = list(edges[i] )
edges.sort(key=lambda _A : e[2] )
for i in range(len(_A ) - 1 ):
if edges[i][2] >= edges[i + 1][2]:
UpperCAmelCase_ : Any = edges[i][2] + 1
for edge in edges:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = edge
UpperCAmelCase_ : Optional[int] = weight
UpperCAmelCase_ : Optional[int] = weight
def __str__( self : Any ) -> int:
UpperCAmelCase_ : Union[str, Any] = ''''''
for tail in self.adjacency:
for head in self.adjacency[tail]:
UpperCAmelCase_ : Optional[Any] = self.adjacency[head][tail]
string += F"{head} -> {tail} == {weight}\n"
return string.rstrip('''\n''' )
def A ( self : int ) -> Dict:
UpperCAmelCase_ : List[str] = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]) )
return output
def A ( self : Tuple ) -> Tuple:
return self.adjacency.keys()
@staticmethod
def A ( _A : Tuple=None , _A : str=None ) -> int:
UpperCAmelCase_ : Union[str, Any] = Graph()
if vertices is None:
UpperCAmelCase_ : List[str] = []
if edges is None:
UpperCAmelCase_ : Optional[int] = []
for vertex in vertices:
g.add_vertex(_A )
for edge in edges:
g.add_edge(*_A )
return g
class snake_case__ :
def __init__( self : Optional[Any] ) -> Optional[int]:
UpperCAmelCase_ : int = {}
UpperCAmelCase_ : List[str] = {}
def __len__( self : List[str] ) -> Any:
return len(self.parent )
def A ( self : Union[str, Any] , _A : Any ) -> Union[str, Any]:
if item in self.parent:
return self.find(_A )
UpperCAmelCase_ : str = item
UpperCAmelCase_ : str = 0
return item
def A ( self : Optional[int] , _A : str ) -> Dict:
if item not in self.parent:
return self.make_set(_A )
if item != self.parent[item]:
UpperCAmelCase_ : str = self.find(self.parent[item] )
return self.parent[item]
def A ( self : Tuple , _A : List[Any] , _A : List[Any] ) -> Optional[Any]:
UpperCAmelCase_ : Union[str, Any] = self.find(_A )
UpperCAmelCase_ : List[Any] = self.find(_A )
if roota == roota:
return roota
if self.rank[roota] > self.rank[roota]:
UpperCAmelCase_ : Optional[Any] = roota
return roota
if self.rank[roota] < self.rank[roota]:
UpperCAmelCase_ : List[Any] = roota
return roota
if self.rank[roota] == self.rank[roota]:
self.rank[roota] += 1
UpperCAmelCase_ : Optional[Any] = roota
return roota
return None
@staticmethod
def A ( _A : Optional[int] ) -> List[str]:
UpperCAmelCase_ : str = graph.num_vertices
UpperCAmelCase_ : Optional[Any] = Graph.UnionFind()
UpperCAmelCase_ : Optional[int] = []
while num_components > 1:
UpperCAmelCase_ : Union[str, Any] = {}
for vertex in graph.get_vertices():
UpperCAmelCase_ : Tuple = -1
UpperCAmelCase_ : Any = graph.get_edges()
for edge in edges:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = edge
edges.remove((tail, head, weight) )
for edge in edges:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = edge
UpperCAmelCase_ : Dict = union_find.find(_A )
UpperCAmelCase_ : Tuple = union_find.find(_A )
if seta != seta:
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
UpperCAmelCase_ : Optional[int] = [head, tail, weight]
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
UpperCAmelCase_ : int = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = cheap_edge[vertex]
if union_find.find(_A ) != union_find.find(_A ):
union_find.union(_A , _A )
mst_edges.append(cheap_edge[vertex] )
UpperCAmelCase_ : Union[str, Any] = num_components - 1
UpperCAmelCase_ : Any = Graph.build(edges=_A )
return mst
| 216
|
'''simple docstring'''
from __future__ import annotations
import time
from math import sqrt
# 1 for manhattan, 0 for euclidean
_UpperCamelCase : List[Any] = 0
_UpperCamelCase : int = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
_UpperCamelCase : int = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
_UpperCamelCase : List[str] = tuple[int, int]
class snake_case__ :
def __init__( self : Dict , _A : int , _A : int , _A : int , _A : int , _A : int , _A : Node | None , ) -> None:
UpperCAmelCase_ : str = pos_x
UpperCAmelCase_ : Union[str, Any] = pos_y
UpperCAmelCase_ : int = (pos_y, pos_x)
UpperCAmelCase_ : Tuple = goal_x
UpperCAmelCase_ : List[Any] = goal_y
UpperCAmelCase_ : List[str] = g_cost
UpperCAmelCase_ : List[Any] = parent
UpperCAmelCase_ : List[str] = self.calculate_heuristic()
UpperCAmelCase_ : str = self.g_cost + self.h_cost
def A ( self : Union[str, Any] ) -> float:
UpperCAmelCase_ : List[str] = self.pos_x - self.goal_x
UpperCAmelCase_ : Dict = self.pos_y - self.goal_y
if HEURISTIC == 1:
return abs(_A ) + abs(_A )
else:
return sqrt(dy**2 + dx**2 )
def __lt__( self : int , _A : Node ) -> bool:
return self.f_cost < other.f_cost
class snake_case__ :
def __init__( self : List[Any] , _A : TPosition , _A : TPosition ) -> List[str]:
UpperCAmelCase_ : Union[str, Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , _A )
UpperCAmelCase_ : Optional[int] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_99_99 , _A )
UpperCAmelCase_ : Dict = [self.start]
UpperCAmelCase_ : list[Node] = []
UpperCAmelCase_ : List[Any] = False
def A ( self : Optional[int] ) -> list[TPosition]:
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
UpperCAmelCase_ : Optional[Any] = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
return self.retrace_path(_A )
self.closed_nodes.append(_A )
UpperCAmelCase_ : Optional[Any] = self.get_successors(_A )
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(_A )
else:
# retrieve the best current path
UpperCAmelCase_ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(_A ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(_A )
else:
self.open_nodes.append(_A )
return [self.start.pos]
def A ( self : Any , _A : Node ) -> list[Node]:
UpperCAmelCase_ : Optional[Any] = []
for action in delta:
UpperCAmelCase_ : List[str] = parent.pos_x + action[1]
UpperCAmelCase_ : Dict = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_A ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
_A , _A , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , _A , ) )
return successors
def A ( self : List[Any] , _A : Node | None ) -> list[TPosition]:
UpperCAmelCase_ : List[Any] = node
UpperCAmelCase_ : Tuple = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
UpperCAmelCase_ : Optional[Any] = current_node.parent
path.reverse()
return path
class snake_case__ :
def __init__( self : int , _A : TPosition , _A : TPosition ) -> None:
UpperCAmelCase_ : Any = AStar(_A , _A )
UpperCAmelCase_ : Dict = AStar(_A , _A )
UpperCAmelCase_ : Union[str, Any] = False
def A ( self : Union[str, Any] ) -> list[TPosition]:
while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes:
self.fwd_astar.open_nodes.sort()
self.bwd_astar.open_nodes.sort()
UpperCAmelCase_ : Optional[Any] = self.fwd_astar.open_nodes.pop(0 )
UpperCAmelCase_ : Optional[int] = self.bwd_astar.open_nodes.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
return self.retrace_bidirectional_path(
_A , _A )
self.fwd_astar.closed_nodes.append(_A )
self.bwd_astar.closed_nodes.append(_A )
UpperCAmelCase_ : int = current_bwd_node
UpperCAmelCase_ : int = current_fwd_node
UpperCAmelCase_ : List[Any] = {
self.fwd_astar: self.fwd_astar.get_successors(_A ),
self.bwd_astar: self.bwd_astar.get_successors(_A ),
}
for astar in [self.fwd_astar, self.bwd_astar]:
for child_node in successors[astar]:
if child_node in astar.closed_nodes:
continue
if child_node not in astar.open_nodes:
astar.open_nodes.append(_A )
else:
# retrieve the best current path
UpperCAmelCase_ : Optional[int] = astar.open_nodes.pop(
astar.open_nodes.index(_A ) )
if child_node.g_cost < better_node.g_cost:
astar.open_nodes.append(_A )
else:
astar.open_nodes.append(_A )
return [self.fwd_astar.start.pos]
def A ( self : List[Any] , _A : Node , _A : Node ) -> list[TPosition]:
UpperCAmelCase_ : Dict = self.fwd_astar.retrace_path(_A )
UpperCAmelCase_ : int = self.bwd_astar.retrace_path(_A )
bwd_path.pop()
bwd_path.reverse()
UpperCAmelCase_ : Dict = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
_UpperCamelCase : Optional[int] = (0, 0)
_UpperCamelCase : Union[str, Any] = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
_UpperCamelCase : str = time.time()
_UpperCamelCase : int = AStar(init, goal)
_UpperCamelCase : Any = a_star.search()
_UpperCamelCase : str = time.time() - start_time
print(f'''AStar execution time = {end_time:f} seconds''')
_UpperCamelCase : Union[str, Any] = time.time()
_UpperCamelCase : Dict = BidirectionalAStar(init, goal)
_UpperCamelCase : List[str] = time.time() - bd_start_time
print(f'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')
| 216
| 1
|
from sympy import diff, lambdify, symbols
from sympy.functions import * # noqa: F403
def A ( lowercase__ : str , lowercase__ : complex , lowercase__ : str = "x" , lowercase__ : float = 10**-10 , lowercase__ : int = 1 , ) -> complex:
UpperCamelCase__ :Optional[int] = symbols(lowercase__ )
UpperCamelCase__ :Dict = lambdify(lowercase__ , lowercase__ )
UpperCamelCase__ :Any = lambdify(lowercase__ , diff(lowercase__ , lowercase__ ) )
UpperCamelCase__ :List[str] = starting_point
while True:
if diff_function(lowercase__ ) != 0:
UpperCamelCase__ :List[Any] = prev_guess - multiplicity * func(lowercase__ ) / diff_function(
lowercase__ )
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
UpperCamelCase__ :Optional[Any] = 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)}''')
| 45
|
"""simple docstring"""
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 lowerCAmelCase_ ( SCREAMING_SNAKE_CASE : Any ):
'''simple docstring'''
__lowerCamelCase : Tuple =torch.exp(SCREAMING_SNAKE_CASE )
__lowerCamelCase : Dict =torch.sum(SCREAMING_SNAKE_CASE , dim=1 ) # sum of exp(x_i)
__lowerCamelCase : Optional[int] =torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i)
return torch.log(SCREAMING_SNAKE_CASE ) - B / A
class SCREAMING_SNAKE_CASE_ ( nn.Module ):
"""simple docstring"""
def __init__( self :List[str] , __lowercase :int ):
super().__init__()
__lowerCamelCase : str =config.output_attentions
__lowerCamelCase : List[Any] =config.output_hidden_states
__lowerCamelCase : Dict =nn.ModuleList([BertLayer(__lowercase ) for _ in range(config.num_hidden_layers )] )
__lowerCamelCase : str =nn.ModuleList([BertHighway(__lowercase ) for _ in range(config.num_hidden_layers )] )
__lowerCamelCase : Optional[Any] =[-1 for _ in range(config.num_hidden_layers )]
def __lowercase ( self :Union[str, Any] , __lowercase :Union[str, Any] ):
if (type(__lowercase ) is float) or (type(__lowercase ) is int):
for i in range(len(self.early_exit_entropy ) ):
__lowerCamelCase : Tuple =x
else:
__lowerCamelCase : Any =x
def __lowercase ( self :Union[str, Any] , __lowercase :Tuple ):
__lowerCamelCase : Union[str, Any] =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 :Tuple , __lowercase :Optional[int] , __lowercase :Dict=None , __lowercase :Union[str, Any]=None , __lowercase :List[str]=None , __lowercase :str=None , ):
__lowerCamelCase : Any =()
__lowerCamelCase : List[str] =()
__lowerCamelCase : Optional[int] =()
for i, layer_module in enumerate(self.layer ):
if self.output_hidden_states:
__lowerCamelCase : int =all_hidden_states + (hidden_states,)
__lowerCamelCase : List[Any] =layer_module(
__lowercase , __lowercase , head_mask[i] , __lowercase , __lowercase )
__lowerCamelCase : Optional[int] =layer_outputs[0]
if self.output_attentions:
__lowerCamelCase : Optional[Any] =all_attentions + (layer_outputs[1],)
__lowerCamelCase : Any =(hidden_states,)
if self.output_hidden_states:
__lowerCamelCase : Optional[Any] =current_outputs + (all_hidden_states,)
if self.output_attentions:
__lowerCamelCase : Dict =current_outputs + (all_attentions,)
__lowerCamelCase : str =self.highway[i](__lowercase )
# logits, pooled_output
if not self.training:
__lowerCamelCase : Tuple =highway_exit[0]
__lowerCamelCase : Tuple =entropy(__lowercase )
__lowerCamelCase : Tuple =highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy
__lowerCamelCase : Optional[int] =all_highway_exits + (highway_exit,)
if highway_entropy < self.early_exit_entropy[i]:
__lowerCamelCase : Dict =(highway_logits,) + current_outputs[1:] + (all_highway_exits,)
raise HighwayException(__lowercase , i + 1 )
else:
__lowerCamelCase : Union[str, Any] =all_highway_exits + (highway_exit,)
# Add last layer
if self.output_hidden_states:
__lowerCamelCase : Optional[Any] =all_hidden_states + (hidden_states,)
__lowerCamelCase : List[Any] =(hidden_states,)
if self.output_hidden_states:
__lowerCamelCase : Tuple =outputs + (all_hidden_states,)
if self.output_attentions:
__lowerCamelCase : Optional[int] =outputs + (all_attentions,)
__lowerCamelCase : int =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). """ , snake_case__ , )
class SCREAMING_SNAKE_CASE_ ( snake_case__ ):
"""simple docstring"""
def __init__( self :Union[str, Any] , __lowercase :str ):
super().__init__(__lowercase )
__lowerCamelCase : Union[str, Any] =config
__lowerCamelCase : List[str] =BertEmbeddings(__lowercase )
__lowerCamelCase : Dict =DeeBertEncoder(__lowercase )
__lowerCamelCase : List[Any] =BertPooler(__lowercase )
self.init_weights()
def __lowercase ( self :Tuple ):
self.encoder.init_highway_pooler(self.pooler )
def __lowercase ( self :Dict ):
return self.embeddings.word_embeddings
def __lowercase ( self :List[str] , __lowercase :int ):
__lowerCamelCase : Union[str, Any] =value
def __lowercase ( self :List[Any] , __lowercase :Dict ):
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(__lowercase )
@add_start_docstrings_to_model_forward(__lowercase )
def __lowercase ( self :Optional[Any] , __lowercase :List[str]=None , __lowercase :List[Any]=None , __lowercase :Any=None , __lowercase :Tuple=None , __lowercase :Union[str, Any]=None , __lowercase :Optional[Any]=None , __lowercase :Union[str, Any]=None , __lowercase :Tuple=None , ):
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:
__lowerCamelCase : List[str] =input_ids.size()
elif inputs_embeds is not None:
__lowerCamelCase : str =inputs_embeds.size()[:-1]
else:
raise ValueError('''You have to specify either input_ids or inputs_embeds''' )
__lowerCamelCase : Optional[int] =input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
__lowerCamelCase : str =torch.ones(__lowercase , device=__lowercase )
if encoder_attention_mask is None:
__lowerCamelCase : Tuple =torch.ones(__lowercase , device=__lowercase )
if token_type_ids is None:
__lowerCamelCase : List[Any] =torch.zeros(__lowercase , dtype=torch.long , device=__lowercase )
# 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.
__lowerCamelCase : torch.Tensor =self.get_extended_attention_mask(__lowercase , __lowercase , __lowercase )
# 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:
__lowerCamelCase : List[str] =encoder_attention_mask[:, None, :, :]
if encoder_attention_mask.dim() == 2:
__lowerCamelCase : Any =encoder_attention_mask[:, None, None, :]
__lowerCamelCase : Optional[Any] =encoder_extended_attention_mask.to(
dtype=next(self.parameters() ).dtype ) # fp16 compatibility
__lowerCamelCase : List[str] =(1.0 - encoder_extended_attention_mask) * -10000.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]
__lowerCamelCase : Union[str, Any] =self.get_head_mask(__lowercase , self.config.num_hidden_layers )
__lowerCamelCase : str =self.embeddings(
input_ids=__lowercase , position_ids=__lowercase , token_type_ids=__lowercase , inputs_embeds=__lowercase )
__lowerCamelCase : Dict =self.encoder(
__lowercase , attention_mask=__lowercase , head_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , )
__lowerCamelCase : int =encoder_outputs[0]
__lowerCamelCase : Tuple =self.pooler(__lowercase )
__lowerCamelCase : int =(
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 SCREAMING_SNAKE_CASE_ ( snake_case__ ):
"""simple docstring"""
def __init__( self :List[Any] , __lowercase :Optional[Any] , __lowercase :Dict ):
__lowerCamelCase : List[Any] =message
__lowerCamelCase : int =exit_layer # start from 1!
class SCREAMING_SNAKE_CASE_ ( nn.Module ):
"""simple docstring"""
def __init__( self :Any , __lowercase :str ):
super().__init__()
__lowerCamelCase : str =BertPooler(__lowercase )
__lowerCamelCase : Union[str, Any] =nn.Dropout(config.hidden_dropout_prob )
__lowerCamelCase : List[str] =nn.Linear(config.hidden_size , config.num_labels )
def __lowercase ( self :Union[str, Any] , __lowercase :List[str] ):
# Pooler
__lowerCamelCase : Optional[Any] =encoder_outputs[0]
__lowerCamelCase : Any =self.pooler(__lowercase )
# "return" pooler_output
# BertModel
__lowerCamelCase : List[str] =(pooler_input, pooler_output) + encoder_outputs[1:]
# "return" bmodel_output
# Dropout and classification
__lowerCamelCase : List[Any] =bmodel_output[1]
__lowerCamelCase : Optional[Any] =self.dropout(__lowercase )
__lowerCamelCase : int =self.classifier(__lowercase )
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. """ , snake_case__ , )
class SCREAMING_SNAKE_CASE_ ( snake_case__ ):
"""simple docstring"""
def __init__( self :Union[str, Any] , __lowercase :Dict ):
super().__init__(__lowercase )
__lowerCamelCase : Any =config.num_labels
__lowerCamelCase : int =config.num_hidden_layers
__lowerCamelCase : Tuple =DeeBertModel(__lowercase )
__lowerCamelCase : Optional[int] =nn.Dropout(config.hidden_dropout_prob )
__lowerCamelCase : Optional[int] =nn.Linear(config.hidden_size , self.config.num_labels )
self.init_weights()
@add_start_docstrings_to_model_forward(__lowercase )
def __lowercase ( self :List[str] , __lowercase :List[str]=None , __lowercase :str=None , __lowercase :Optional[Any]=None , __lowercase :List[Any]=None , __lowercase :Union[str, Any]=None , __lowercase :Dict=None , __lowercase :int=None , __lowercase :int=-1 , __lowercase :List[str]=False , ):
__lowerCamelCase : Union[str, Any] =self.num_layers
try:
__lowerCamelCase : Union[str, Any] =self.bert(
__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , position_ids=__lowercase , head_mask=__lowercase , inputs_embeds=__lowercase , )
# sequence_output, pooled_output, (hidden_states), (attentions), highway exits
__lowerCamelCase : List[Any] =outputs[1]
__lowerCamelCase : Optional[Any] =self.dropout(__lowercase )
__lowerCamelCase : Tuple =self.classifier(__lowercase )
__lowerCamelCase : int =(logits,) + outputs[2:] # add hidden states and attention if they are here
except HighwayException as e:
__lowerCamelCase : Union[str, Any] =e.message
__lowerCamelCase : Optional[Any] =e.exit_layer
__lowerCamelCase : Any =outputs[0]
if not self.training:
__lowerCamelCase : List[Any] =entropy(__lowercase )
__lowerCamelCase : Union[str, Any] =[]
__lowerCamelCase : int =[]
if labels is not None:
if self.num_labels == 1:
# We are doing regression
__lowerCamelCase : Union[str, Any] =MSELoss()
__lowerCamelCase : List[Any] =loss_fct(logits.view(-1 ) , labels.view(-1 ) )
else:
__lowerCamelCase : Dict =CrossEntropyLoss()
__lowerCamelCase : List[Any] =loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
# work with highway exits
__lowerCamelCase : str =[]
for highway_exit in outputs[-1]:
__lowerCamelCase : List[str] =highway_exit[0]
if not self.training:
highway_logits_all.append(__lowercase )
highway_entropy.append(highway_exit[2] )
if self.num_labels == 1:
# We are doing regression
__lowerCamelCase : Optional[int] =MSELoss()
__lowerCamelCase : Optional[Any] =loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) )
else:
__lowerCamelCase : int =CrossEntropyLoss()
__lowerCamelCase : int =loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
highway_losses.append(__lowercase )
if train_highway:
__lowerCamelCase : Dict =(sum(highway_losses[:-1] ),) + outputs
# exclude the final highway, of course
else:
__lowerCamelCase : List[str] =(loss,) + outputs
if not self.training:
__lowerCamelCase : List[Any] =outputs + ((original_entropy, highway_entropy), exit_layer)
if output_layer >= 0:
__lowerCamelCase : Dict =(
(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)
| 179
| 0
|
"""simple docstring"""
import flax.linen as nn
import jax
import jax.numpy as jnp
class lowercase__ ( nn.Module ):
'''simple docstring'''
_UpperCAmelCase = 42
_UpperCAmelCase = jnp.floataa
def lowerCamelCase_ ( self ) -> Tuple:
_UpperCAmelCase = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self , snake_case ) -> Optional[Any]:
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = hidden_states.shape
_UpperCAmelCase = jax.image.resize(
snake_case , shape=(batch, height * 2, width * 2, channels) , method='nearest' , )
_UpperCAmelCase = self.conv(snake_case )
return hidden_states
class lowercase__ ( nn.Module ):
'''simple docstring'''
_UpperCAmelCase = 42
_UpperCAmelCase = jnp.floataa
def lowerCamelCase_ ( self ) -> Optional[int]:
_UpperCAmelCase = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self , snake_case ) -> Tuple:
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
_UpperCAmelCase = self.conv(snake_case )
return hidden_states
class lowercase__ ( nn.Module ):
'''simple docstring'''
_UpperCAmelCase = 42
_UpperCAmelCase = None
_UpperCAmelCase = 0.0
_UpperCAmelCase = None
_UpperCAmelCase = jnp.floataa
def lowerCamelCase_ ( self ) -> List[Any]:
_UpperCAmelCase = self.in_channels if self.out_channels is None else self.out_channels
_UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1E-5 )
_UpperCAmelCase = nn.Conv(
snake_case , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_UpperCAmelCase = nn.Dense(snake_case , dtype=self.dtype )
_UpperCAmelCase = nn.GroupNorm(num_groups=32 , epsilon=1E-5 )
_UpperCAmelCase = nn.Dropout(self.dropout_prob )
_UpperCAmelCase = nn.Conv(
snake_case , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
_UpperCAmelCase = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
_UpperCAmelCase = None
if use_nin_shortcut:
_UpperCAmelCase = nn.Conv(
snake_case , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , )
def __call__( self , snake_case , snake_case , snake_case=True ) -> Union[str, Any]:
_UpperCAmelCase = hidden_states
_UpperCAmelCase = self.norma(snake_case )
_UpperCAmelCase = nn.swish(snake_case )
_UpperCAmelCase = self.conva(snake_case )
_UpperCAmelCase = self.time_emb_proj(nn.swish(snake_case ) )
_UpperCAmelCase = jnp.expand_dims(jnp.expand_dims(snake_case , 1 ) , 1 )
_UpperCAmelCase = hidden_states + temb
_UpperCAmelCase = self.norma(snake_case )
_UpperCAmelCase = nn.swish(snake_case )
_UpperCAmelCase = self.dropout(snake_case , snake_case )
_UpperCAmelCase = self.conva(snake_case )
if self.conv_shortcut is not None:
_UpperCAmelCase = self.conv_shortcut(snake_case )
return hidden_states + residual
| 24
|
"""simple docstring"""
import unittest
from transformers import (
MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
TextaTextGenerationPipeline,
pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available
from .test_pipelines_common import ANY
if is_torch_available():
import torch
@is_pipeline_test
class lowercase__ ( unittest.TestCase ):
'''simple docstring'''
_UpperCAmelCase = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
_UpperCAmelCase = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
def lowerCamelCase_ ( self , snake_case , snake_case , snake_case ) -> Dict:
_UpperCAmelCase = TextaTextGenerationPipeline(model=snake_case , tokenizer=snake_case )
return generator, ["Something to write", "Something else"]
def lowerCamelCase_ ( self , snake_case , snake_case ) -> Dict:
_UpperCAmelCase = generator('Something there' )
self.assertEqual(snake_case , [{'generated_text': ANY(snake_case )}] )
# These are encoder decoder, they don't just append to incoming string
self.assertFalse(outputs[0]['generated_text'].startswith('Something there' ) )
_UpperCAmelCase = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=snake_case )
self.assertEqual(
snake_case , [
[{'generated_text': ANY(snake_case )}, {'generated_text': ANY(snake_case )}],
[{'generated_text': ANY(snake_case )}, {'generated_text': ANY(snake_case )}],
] , )
_UpperCAmelCase = generator(
['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=snake_case )
self.assertEqual(
snake_case , [
[{'generated_text': ANY(snake_case )}, {'generated_text': ANY(snake_case )}],
[{'generated_text': ANY(snake_case )}, {'generated_text': ANY(snake_case )}],
] , )
with self.assertRaises(snake_case ):
generator(4 )
@require_torch
def lowerCamelCase_ ( self ) -> Dict:
_UpperCAmelCase = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt' )
# do_sample=False necessary for reproducibility
_UpperCAmelCase = generator('Something there' , do_sample=snake_case )
self.assertEqual(snake_case , [{'generated_text': ''}] )
_UpperCAmelCase = 3
_UpperCAmelCase = generator(
'Something there' , num_return_sequences=snake_case , num_beams=snake_case , )
_UpperCAmelCase = [
{'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'},
{'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'},
{'generated_text': ''},
]
self.assertEqual(snake_case , snake_case )
_UpperCAmelCase = generator('This is a test' , do_sample=snake_case , num_return_sequences=2 , return_tensors=snake_case )
self.assertEqual(
snake_case , [
{'generated_token_ids': ANY(torch.Tensor )},
{'generated_token_ids': ANY(torch.Tensor )},
] , )
_UpperCAmelCase = generator.model.config.eos_token_id
_UpperCAmelCase = '<pad>'
_UpperCAmelCase = generator(
['This is a test', 'This is a second test'] , do_sample=snake_case , num_return_sequences=2 , batch_size=2 , return_tensors=snake_case , )
self.assertEqual(
snake_case , [
[
{'generated_token_ids': ANY(torch.Tensor )},
{'generated_token_ids': ANY(torch.Tensor )},
],
[
{'generated_token_ids': ANY(torch.Tensor )},
{'generated_token_ids': ANY(torch.Tensor )},
],
] , )
@require_tf
def lowerCamelCase_ ( self ) -> Any:
_UpperCAmelCase = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf' )
# do_sample=False necessary for reproducibility
_UpperCAmelCase = generator('Something there' , do_sample=snake_case )
self.assertEqual(snake_case , [{'generated_text': ''}] )
| 24
| 1
|
"""simple docstring"""
def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
while a != 0:
__lowercase ,__lowercase : Tuple = b % a, a
return b
def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
if gcd(__UpperCamelCase , __UpperCamelCase ) != 1:
__lowercase : Union[str, Any] = f"""mod inverse of {a!r} and {m!r} does not exist"""
raise ValueError(__UpperCamelCase )
__lowercase ,__lowercase ,__lowercase : str = 1, 0, a
__lowercase ,__lowercase ,__lowercase : str = 0, 1, m
while va != 0:
__lowercase : Union[str, Any] = ua // va
__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase ,__lowercase : int = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m
| 76
|
"""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.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class UpperCAmelCase_ ( snake_case ):
UpperCamelCase ="openai/whisper-base"
UpperCamelCase =(
"This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the "
"transcribed text."
)
UpperCamelCase ="transcriber"
UpperCamelCase =WhisperProcessor
UpperCamelCase =WhisperForConditionalGeneration
UpperCamelCase =["audio"]
UpperCamelCase =["text"]
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Union[str, Any]:
return self.pre_processor(UpperCamelCase_ , return_tensors='''pt''' ).input_features
def _lowerCamelCase ( self , UpperCamelCase_ ) -> Optional[Any]:
return self.model.generate(inputs=UpperCamelCase_ )
def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[str]:
return self.pre_processor.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ )[0]
| 76
| 1
|
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline
else:
from .camera import create_pan_cameras
from .pipeline_shap_e import ShapEPipeline
from .pipeline_shap_e_img2img import ShapEImgaImgPipeline
from .renderer import (
BoundingBoxVolume,
ImportanceRaySampler,
MLPNeRFModelOutput,
MLPNeRSTFModel,
ShapEParamsProjModel,
ShapERenderer,
StratifiedRaySampler,
VoidNeRFModel,
)
| 707
|
"""simple docstring"""
import baseaa
def lowerCamelCase__ ( _lowerCamelCase ):
'''simple docstring'''
return baseaa.aaaencode(string.encode('utf-8' ) )
def lowerCamelCase__ ( _lowerCamelCase ):
'''simple docstring'''
return baseaa.aaadecode(_lowerCamelCase ).decode('utf-8' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 16
| 0
|
from __future__ import annotations
import math
def snake_case__ ( lowercase ):
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(lowercase ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
a : Optional[Any] = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)]
def snake_case__ ( lowercase ):
if not isinstance(lowercase , lowercase ):
raise ValueError("n must be an integer" )
if n <= 0:
raise ValueError("n must be >= 0" )
lowerCAmelCase_: Dict = []
for num in range(len(lowercase ) ):
lowerCAmelCase_: Optional[int] = 0
while 2 * i * i <= odd_composites[num]:
lowerCAmelCase_: int = odd_composites[num] - 2 * i * i
if is_prime(lowercase ):
break
i += 1
else:
list_nums.append(odd_composites[num] )
if len(lowercase ) == n:
return list_nums
return []
def snake_case__ ( ):
return compute_nums(1 )[0]
if __name__ == "__main__":
print(f'''{solution() = }''')
| 613
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
a : List[Any] = logging.get_logger(__name__)
a : Union[str, Any] = {
"""bigcode/gpt_bigcode-santacoder""": """https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json""",
}
class _lowercase ( UpperCAmelCase__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE: List[str] = 'gpt_bigcode'
SCREAMING_SNAKE_CASE: Union[str, Any] = ['past_key_values']
SCREAMING_SNAKE_CASE: Tuple = {
'hidden_size': 'n_embd',
'max_position_embeddings': 'n_positions',
'num_attention_heads': 'n_head',
'num_hidden_layers': 'n_layer',
}
def __init__( self , lowerCamelCase__=50_257 , lowerCamelCase__=1_024 , lowerCamelCase__=768 , lowerCamelCase__=12 , lowerCamelCase__=12 , lowerCamelCase__=None , lowerCamelCase__="gelu_pytorch_tanh" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=1E-5 , lowerCamelCase__=0.0_2 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=50_256 , lowerCamelCase__=50_256 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , **lowerCamelCase__ , ):
lowerCAmelCase_: List[Any] = vocab_size
lowerCAmelCase_: List[str] = n_positions
lowerCAmelCase_: Union[str, Any] = n_embd
lowerCAmelCase_: Union[str, Any] = n_layer
lowerCAmelCase_: Union[str, Any] = n_head
lowerCAmelCase_: List[Any] = n_inner
lowerCAmelCase_: List[Any] = activation_function
lowerCAmelCase_: Optional[int] = resid_pdrop
lowerCAmelCase_: Union[str, Any] = embd_pdrop
lowerCAmelCase_: Any = attn_pdrop
lowerCAmelCase_: Union[str, Any] = layer_norm_epsilon
lowerCAmelCase_: Optional[Any] = initializer_range
lowerCAmelCase_: int = scale_attn_weights
lowerCAmelCase_: int = use_cache
lowerCAmelCase_: int = attention_softmax_in_fpaa
lowerCAmelCase_: int = scale_attention_softmax_in_fpaa
lowerCAmelCase_: Union[str, Any] = multi_query
lowerCAmelCase_: Union[str, Any] = bos_token_id
lowerCAmelCase_: List[str] = eos_token_id
super().__init__(bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , **lowerCamelCase__ )
| 613
| 1
|
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__UpperCAmelCase :Union[str, Any] = logging.get_logger(__name__)
__UpperCAmelCase :Tuple = {
"""facebook/s2t-small-librispeech-asr""": (
"""https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json"""
),
# See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text
}
class a ( _a ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = "speech_to_text"
SCREAMING_SNAKE_CASE : int = ["past_key_values"]
SCREAMING_SNAKE_CASE : Optional[int] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
def __init__( self : int , snake_case : int=1_0000 , snake_case : List[str]=12 , snake_case : Optional[int]=2048 , snake_case : List[Any]=4 , snake_case : Optional[Any]=6 , snake_case : List[str]=2048 , snake_case : str=4 , snake_case : Dict=0.0 , snake_case : List[Any]=0.0 , snake_case : Optional[int]=True , snake_case : str=True , snake_case : Optional[Any]="relu" , snake_case : Optional[Any]=256 , snake_case : Union[str, Any]=0.1 , snake_case : str=0.0 , snake_case : Dict=0.0 , snake_case : Tuple=0.02 , snake_case : Dict=2 , snake_case : int=True , snake_case : Optional[Any]=1 , snake_case : int=0 , snake_case : Dict=2 , snake_case : Dict=6000 , snake_case : Optional[int]=1024 , snake_case : Any=2 , snake_case : int=(5, 5) , snake_case : Dict=1024 , snake_case : List[str]=80 , snake_case : List[str]=1 , **snake_case : Any , ) -> List[Any]:
__UpperCAmelCase : Any = vocab_size
__UpperCAmelCase : Tuple = d_model
__UpperCAmelCase : Optional[Any] = encoder_ffn_dim
__UpperCAmelCase : List[str] = encoder_layers
__UpperCAmelCase : List[str] = encoder_attention_heads
__UpperCAmelCase : int = decoder_ffn_dim
__UpperCAmelCase : Any = decoder_layers
__UpperCAmelCase : Dict = decoder_attention_heads
__UpperCAmelCase : List[str] = dropout
__UpperCAmelCase : int = attention_dropout
__UpperCAmelCase : str = activation_dropout
__UpperCAmelCase : Optional[int] = activation_function
__UpperCAmelCase : Tuple = init_std
__UpperCAmelCase : Optional[int] = encoder_layerdrop
__UpperCAmelCase : int = decoder_layerdrop
__UpperCAmelCase : List[Any] = use_cache
__UpperCAmelCase : Tuple = encoder_layers
__UpperCAmelCase : Optional[int] = scale_embedding # scale factor will be sqrt(d_model) if True
__UpperCAmelCase : Any = max_source_positions
__UpperCAmelCase : Optional[Any] = max_target_positions
__UpperCAmelCase : Any = num_conv_layers
__UpperCAmelCase : Union[str, Any] = list(snake_case )
__UpperCAmelCase : Union[str, Any] = conv_channels
__UpperCAmelCase : Optional[Any] = input_feat_per_channel
__UpperCAmelCase : Any = input_channels
if len(self.conv_kernel_sizes ) != self.num_conv_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` '''
f'but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, '
f'`config.num_conv_layers = {self.num_conv_layers}`.' )
super().__init__(
pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , is_encoder_decoder=snake_case , decoder_start_token_id=snake_case , **snake_case , )
| 706
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
__UpperCAmelCase :Optional[Any] = {
"configuration_layoutlmv2": ["LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv2Config"],
"processing_layoutlmv2": ["LayoutLMv2Processor"],
"tokenization_layoutlmv2": ["LayoutLMv2Tokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase :Any = ["LayoutLMv2TokenizerFast"]
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase :int = ["LayoutLMv2FeatureExtractor"]
__UpperCAmelCase :Optional[int] = ["LayoutLMv2ImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase :List[Any] = [
"LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST",
"LayoutLMv2ForQuestionAnswering",
"LayoutLMv2ForSequenceClassification",
"LayoutLMv2ForTokenClassification",
"LayoutLMv2Layer",
"LayoutLMv2Model",
"LayoutLMv2PreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig
from .processing_layoutlmva import LayoutLMvaProcessor
from .tokenization_layoutlmva import LayoutLMvaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_layoutlmva import (
LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaLayer,
LayoutLMvaModel,
LayoutLMvaPreTrainedModel,
)
else:
import sys
__UpperCAmelCase :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 266
| 0
|
from typing import Dict, List, Optional, Union
import numpy as np
from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_valid_image,
to_numpy_array,
valid_images,
)
from ...utils import logging
if is_vision_available():
import PIL
lowerCAmelCase = logging.get_logger(__name__)
def _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
if isinstance(SCREAMING_SNAKE_CASE , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ):
return videos
elif isinstance(SCREAMING_SNAKE_CASE , (list, tuple) ) and is_valid_image(videos[0] ):
return [videos]
elif is_valid_image(SCREAMING_SNAKE_CASE ):
return [[videos]]
raise ValueError(f'Could not make batched video from {videos}' )
class _a ( UpperCamelCase__ ):
_lowercase : Tuple = ['''pixel_values''']
def __init__( self: List[str] , UpperCamelCase_: bool = True , UpperCamelCase_: Dict[str, int] = None , UpperCamelCase_: PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase_: bool = True , UpperCamelCase_: Dict[str, int] = None , UpperCamelCase_: bool = True , UpperCamelCase_: Union[int, float] = 1 / 255 , UpperCamelCase_: bool = True , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[Union[float, List[float]]] = None , UpperCamelCase_: Optional[Union[float, List[float]]] = None , **UpperCamelCase_: List[str] , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase_ )
lowercase__ = size if size is not None else {'''shortest_edge''': 256}
lowercase__ = get_size_dict(UpperCamelCase_ , default_to_square=UpperCamelCase_ )
lowercase__ = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
lowercase__ = get_size_dict(UpperCamelCase_ , param_name='''crop_size''' )
lowercase__ = do_resize
lowercase__ = size
lowercase__ = do_center_crop
lowercase__ = crop_size
lowercase__ = resample
lowercase__ = do_rescale
lowercase__ = rescale_factor
lowercase__ = offset
lowercase__ = do_normalize
lowercase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
lowercase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def lowerCamelCase_ ( self: List[str] , UpperCamelCase_: np.ndarray , UpperCamelCase_: Dict[str, int] , UpperCamelCase_: PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase_: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase_: Union[str, Any] , ) -> np.ndarray:
"""simple docstring"""
lowercase__ = get_size_dict(UpperCamelCase_ , default_to_square=UpperCamelCase_ )
if "shortest_edge" in size:
lowercase__ = get_resize_output_image_size(UpperCamelCase_ , size['''shortest_edge'''] , default_to_square=UpperCamelCase_ )
elif "height" in size and "width" in size:
lowercase__ = (size['''height'''], size['''width'''])
else:
raise ValueError(f'Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}' )
return resize(UpperCamelCase_ , size=UpperCamelCase_ , resample=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ )
def lowerCamelCase_ ( self: Tuple , UpperCamelCase_: np.ndarray , UpperCamelCase_: Dict[str, int] , UpperCamelCase_: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase_: Tuple , ) -> np.ndarray:
"""simple docstring"""
lowercase__ = get_size_dict(UpperCamelCase_ )
if "height" not in size or "width" not in size:
raise ValueError(f'Size must have \'height\' and \'width\' as keys. Got {size.keys()}' )
return center_crop(UpperCamelCase_ , size=(size['''height'''], size['''width''']) , data_format=UpperCamelCase_ , **UpperCamelCase_ )
def lowerCamelCase_ ( self: Dict , UpperCamelCase_: np.ndarray , UpperCamelCase_: Union[int, float] , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase_: Optional[int] , ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ = image.astype(np.floataa )
if offset:
lowercase__ = image - (scale / 2)
return rescale(UpperCamelCase_ , scale=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ )
def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: np.ndarray , UpperCamelCase_: Union[float, List[float]] , UpperCamelCase_: Union[float, List[float]] , UpperCamelCase_: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase_: Any , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase_ , mean=UpperCamelCase_ , std=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ )
def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: ImageInput , UpperCamelCase_: bool = None , UpperCamelCase_: Dict[str, int] = None , UpperCamelCase_: PILImageResampling = None , UpperCamelCase_: bool = None , UpperCamelCase_: Dict[str, int] = None , UpperCamelCase_: bool = None , UpperCamelCase_: float = None , UpperCamelCase_: bool = None , UpperCamelCase_: bool = None , UpperCamelCase_: Optional[Union[float, List[float]]] = None , UpperCamelCase_: Optional[Union[float, List[float]]] = None , UpperCamelCase_: Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray:
"""simple docstring"""
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_center_crop and crop_size is None:
raise ValueError('''Crop size must be specified if do_center_crop is True.''' )
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )
if offset and not do_rescale:
raise ValueError('''For offset, do_rescale must also be set to True.''' )
# All transformations expect numpy arrays.
lowercase__ = to_numpy_array(UpperCamelCase_ )
if do_resize:
lowercase__ = self.resize(image=UpperCamelCase_ , size=UpperCamelCase_ , resample=UpperCamelCase_ )
if do_center_crop:
lowercase__ = self.center_crop(UpperCamelCase_ , size=UpperCamelCase_ )
if do_rescale:
lowercase__ = self.rescale(image=UpperCamelCase_ , scale=UpperCamelCase_ , offset=UpperCamelCase_ )
if do_normalize:
lowercase__ = self.normalize(image=UpperCamelCase_ , mean=UpperCamelCase_ , std=UpperCamelCase_ )
lowercase__ = to_channel_dimension_format(UpperCamelCase_ , UpperCamelCase_ )
return image
def lowerCamelCase_ ( self: List[Any] , UpperCamelCase_: ImageInput , UpperCamelCase_: bool = None , UpperCamelCase_: Dict[str, int] = None , UpperCamelCase_: PILImageResampling = None , UpperCamelCase_: bool = None , UpperCamelCase_: Dict[str, int] = None , UpperCamelCase_: bool = None , UpperCamelCase_: float = None , UpperCamelCase_: bool = None , UpperCamelCase_: bool = None , UpperCamelCase_: Optional[Union[float, List[float]]] = None , UpperCamelCase_: Optional[Union[float, List[float]]] = None , UpperCamelCase_: Optional[Union[str, TensorType]] = None , UpperCamelCase_: ChannelDimension = ChannelDimension.FIRST , **UpperCamelCase_: Tuple , ) -> PIL.Image.Image:
"""simple docstring"""
lowercase__ = do_resize if do_resize is not None else self.do_resize
lowercase__ = resample if resample is not None else self.resample
lowercase__ = do_center_crop if do_center_crop is not None else self.do_center_crop
lowercase__ = do_rescale if do_rescale is not None else self.do_rescale
lowercase__ = rescale_factor if rescale_factor is not None else self.rescale_factor
lowercase__ = offset if offset is not None else self.offset
lowercase__ = do_normalize if do_normalize is not None else self.do_normalize
lowercase__ = image_mean if image_mean is not None else self.image_mean
lowercase__ = image_std if image_std is not None else self.image_std
lowercase__ = size if size is not None else self.size
lowercase__ = get_size_dict(UpperCamelCase_ , default_to_square=UpperCamelCase_ )
lowercase__ = crop_size if crop_size is not None else self.crop_size
lowercase__ = get_size_dict(UpperCamelCase_ , param_name='''crop_size''' )
if not valid_images(UpperCamelCase_ ):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''' )
lowercase__ = make_batched(UpperCamelCase_ )
lowercase__ = [
[
self._preprocess_image(
image=UpperCamelCase_ , do_resize=UpperCamelCase_ , size=UpperCamelCase_ , resample=UpperCamelCase_ , do_center_crop=UpperCamelCase_ , crop_size=UpperCamelCase_ , do_rescale=UpperCamelCase_ , rescale_factor=UpperCamelCase_ , offset=UpperCamelCase_ , do_normalize=UpperCamelCase_ , image_mean=UpperCamelCase_ , image_std=UpperCamelCase_ , data_format=UpperCamelCase_ , )
for img in video
]
for video in videos
]
lowercase__ = {'''pixel_values''': videos}
return BatchFeature(data=UpperCamelCase_ , tensor_type=UpperCamelCase_ )
| 43
|
import unittest
from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
@require_sentencepiece
@slow # see https://github.com/huggingface/transformers/issues/11457
class lowerCAmelCase_ ( _lowercase , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ = BarthezTokenizer
UpperCAmelCase__ = BarthezTokenizerFast
UpperCAmelCase__ = True
UpperCAmelCase__ = True
def __lowercase( self ) -> Union[str, Any]:
super().setUp()
__UpperCamelCase = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' )
tokenizer.save_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname , legacy_format=_SCREAMING_SNAKE_CASE )
__UpperCamelCase = tokenizer
def __lowercase( self ) -> Union[str, Any]:
__UpperCamelCase = '<pad>'
__UpperCamelCase = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
def __lowercase( self ) -> Optional[Any]:
__UpperCamelCase = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '<s>' )
self.assertEqual(vocab_keys[1] , '<pad>' )
self.assertEqual(vocab_keys[-1] , '<mask>' )
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 101_122 )
def __lowercase( self ) -> Any:
self.assertEqual(self.get_tokenizer().vocab_size , 101_122 )
@require_torch
def __lowercase( self ) -> Optional[Any]:
__UpperCamelCase = ['A long paragraph for summarization.', 'Another paragraph for summarization.']
__UpperCamelCase = [0, 57, 3_018, 70_307, 91, 2]
__UpperCamelCase = self.tokenizer(
_SCREAMING_SNAKE_CASE , max_length=len(_SCREAMING_SNAKE_CASE ) , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
self.assertEqual((2, 6) , batch.input_ids.shape )
self.assertEqual((2, 6) , batch.attention_mask.shape )
__UpperCamelCase = batch.input_ids.tolist()[0]
self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def __lowercase( self ) -> int:
if not self.test_rust_tokenizer:
return
__UpperCamelCase = self.get_tokenizer()
__UpperCamelCase = self.get_rust_tokenizer()
__UpperCamelCase = 'I was born in 92000, and this is falsé.'
__UpperCamelCase = tokenizer.tokenize(_SCREAMING_SNAKE_CASE )
__UpperCamelCase = rust_tokenizer.tokenize(_SCREAMING_SNAKE_CASE )
self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
__UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE )
__UpperCamelCase = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE )
self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
__UpperCamelCase = self.get_rust_tokenizer()
__UpperCamelCase = tokenizer.encode(_SCREAMING_SNAKE_CASE )
__UpperCamelCase = rust_tokenizer.encode(_SCREAMING_SNAKE_CASE )
self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
@slow
def __lowercase( self ) -> List[str]:
# fmt: off
__UpperCamelCase = {'input_ids': [[0, 490, 14_328, 4_507, 354, 47, 43_669, 95, 25, 78_117, 20_215, 19_779, 190, 22, 400, 4, 35_343, 80_310, 603, 86, 24_937, 105, 33_438, 94_762, 196, 39_642, 7, 15, 15_933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10_534, 87, 25, 66, 3_358, 196, 55_289, 8, 82_961, 81, 2_204, 75_203, 7, 15, 763, 12_956, 216, 178, 14_328, 9_595, 1_377, 69_693, 7, 448, 71_021, 196, 18_106, 1_437, 13_974, 108, 9_083, 4, 49_315, 7, 39, 86, 1_326, 2_793, 46_333, 4, 448, 196, 74_588, 7, 49_315, 7, 39, 21, 822, 38_470, 74, 21, 66_723, 62_480, 8, 22_050, 5, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501
# fmt: on
# moussaKam/mbarthez is a french model. So we also use french texts.
__UpperCamelCase = [
'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, '
'utilisé principalement dans le domaine du traitement automatique des langues (TAL).',
'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus '
'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches '
'telles que la traduction et la synthèse de texte.',
]
self.tokenizer_integration_test_util(
expected_encoding=_SCREAMING_SNAKE_CASE , model_name='moussaKam/mbarthez' , revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' , sequences=_SCREAMING_SNAKE_CASE , )
| 383
| 0
|
'''simple docstring'''
import json
from typing import Iterator, List, Union
from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers
from tokenizers.implementations.base_tokenizer import BaseTokenizer
from tokenizers.models import Unigram
from tokenizers.processors import TemplateProcessing
class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
def __init__( self : Dict , lowercase : str = "▁" , lowercase : bool = True , lowercase : Union[str, AddedToken] = "<unk>" , lowercase : Union[str, AddedToken] = "</s>" , lowercase : Union[str, AddedToken] = "<pad>" , ) -> Optional[Any]:
'''simple docstring'''
UpperCamelCase__ = {
"""pad""": {"""id""": 0, """token""": pad_token},
"""eos""": {"""id""": 1, """token""": eos_token},
"""unk""": {"""id""": 2, """token""": unk_token},
}
UpperCamelCase__ = [None] * len(self.special_tokens )
for token_dict in self.special_tokens.values():
UpperCamelCase__ = token_dict["""token"""]
UpperCamelCase__ = Tokenizer(Unigram() )
UpperCamelCase__ = normalizers.Sequence(
[
normalizers.Nmt(),
normalizers.NFKC(),
normalizers.Replace(Regex(""" {2,}""" ) , """ """ ),
normalizers.Lowercase(),
] )
UpperCamelCase__ = pre_tokenizers.Sequence(
[
pre_tokenizers.Metaspace(replacement=lowercase , add_prefix_space=lowercase ),
pre_tokenizers.Digits(individual_digits=lowercase ),
pre_tokenizers.Punctuation(),
] )
UpperCamelCase__ = decoders.Metaspace(replacement=lowercase , add_prefix_space=lowercase )
UpperCamelCase__ = TemplateProcessing(
single=f"$A {self.special_tokens['eos']['token']}" , special_tokens=[(self.special_tokens["""eos"""]["""token"""], self.special_tokens["""eos"""]["""id"""])] , )
UpperCamelCase__ = {
"""model""": """SentencePieceUnigram""",
"""replacement""": replacement,
"""add_prefix_space""": add_prefix_space,
}
super().__init__(lowercase , lowercase )
def A ( self : Tuple , lowercase : Union[str, List[str]] , lowercase : int = 8_0_0_0 , lowercase : bool = True , ) -> Any:
'''simple docstring'''
UpperCamelCase__ = trainers.UnigramTrainer(
vocab_size=lowercase , special_tokens=self.special_tokens_list , show_progress=lowercase , )
if isinstance(lowercase , lowercase ):
UpperCamelCase__ = [files]
self._tokenizer.train(lowercase , trainer=lowercase )
self.add_unk_id()
def A ( self : Dict , lowercase : Union[Iterator[str], Iterator[Iterator[str]]] , lowercase : int = 8_0_0_0 , lowercase : bool = True , ) -> str:
'''simple docstring'''
UpperCamelCase__ = trainers.UnigramTrainer(
vocab_size=lowercase , special_tokens=self.special_tokens_list , show_progress=lowercase , )
self._tokenizer.train_from_iterator(lowercase , trainer=lowercase )
self.add_unk_id()
def A ( self : Tuple ) -> List[Any]:
'''simple docstring'''
UpperCamelCase__ = json.loads(self._tokenizer.to_str() )
UpperCamelCase__ = self.special_tokens["""unk"""]["""id"""]
UpperCamelCase__ = Tokenizer.from_str(json.dumps(lowercase ) )
| 718
|
'''simple docstring'''
import logging
import os
from logging import (
CRITICAL, # NOQA
DEBUG, # NOQA
ERROR, # NOQA
FATAL, # NOQA
INFO, # NOQA
NOTSET, # NOQA
WARN, # NOQA
WARNING, # NOQA
)
from typing import Optional
from tqdm import auto as tqdm_lib
lowerCamelCase_ : Any = {
'''debug''': logging.DEBUG,
'''info''': logging.INFO,
'''warning''': logging.WARNING,
'''error''': logging.ERROR,
'''critical''': logging.CRITICAL,
}
lowerCamelCase_ : Optional[int] = logging.WARNING
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = os.getenv("""DATASETS_VERBOSITY""" , _A )
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(
f"Unknown option DATASETS_VERBOSITY={env_level_str}, "
f"has to be one of: { ', '.join(log_levels.keys() ) }" )
return _default_log_level
def __magic_name__( ):
'''simple docstring'''
return __name__.split(""".""" )[0]
def __magic_name__( ):
'''simple docstring'''
return logging.getLogger(_get_library_name() )
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = _get_library_root_logger()
library_root_logger.setLevel(_get_default_logging_level() )
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = _get_library_root_logger()
library_root_logger.setLevel(logging.NOTSET )
def __magic_name__( _A = None ):
'''simple docstring'''
if name is None:
UpperCamelCase__ = _get_library_name()
return logging.getLogger(_A )
def __magic_name__( ):
'''simple docstring'''
return _get_library_root_logger().getEffectiveLevel()
def __magic_name__( _A ):
'''simple docstring'''
_get_library_root_logger().setLevel(_A )
def __magic_name__( ):
'''simple docstring'''
return set_verbosity(_A )
def __magic_name__( ):
'''simple docstring'''
return set_verbosity(_A )
def __magic_name__( ):
'''simple docstring'''
return set_verbosity(_A )
def __magic_name__( ):
'''simple docstring'''
return set_verbosity(_A )
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = False
def __magic_name__( ):
'''simple docstring'''
UpperCamelCase__ = True
# Configure the library root logger at the module level (singleton-like)
_configure_library_root_logger()
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : int , *lowercase : Any , **lowercase : int ) -> List[Any]: # pylint: disable=unused-argument
'''simple docstring'''
UpperCamelCase__ = args[0] if args else None
def __iter__( self : str ) -> List[str]:
'''simple docstring'''
return iter(self._iterator )
def __getattr__( self : Optional[int] , lowercase : Tuple ) -> int:
'''simple docstring'''
def empty_fn(*lowercase : List[Any] , **lowercase : Dict ): # pylint: disable=unused-argument
return
return empty_fn
def __enter__( self : Dict ) -> Tuple:
'''simple docstring'''
return self
def __exit__( self : Tuple , lowercase : Optional[Any] , lowercase : Any , lowercase : int ) -> Any:
'''simple docstring'''
return
lowerCamelCase_ : str = True
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __call__( self : List[Any] , *lowercase : str , lowercase : Optional[int]=False , **lowercase : Optional[int] ) -> Optional[int]:
'''simple docstring'''
if _tqdm_active and not disable:
return tqdm_lib.tqdm(*lowercase , **lowercase )
else:
return EmptyTqdm(*lowercase , **lowercase )
def A ( self : Optional[Any] , *lowercase : Tuple , **lowercase : Any ) -> Any:
'''simple docstring'''
UpperCamelCase__ = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*lowercase , **lowercase )
def A ( self : Optional[Any] ) -> Optional[Any]:
'''simple docstring'''
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
lowerCamelCase_ : int = _tqdm_cls()
def __magic_name__( ):
'''simple docstring'''
global _tqdm_active
return bool(_tqdm_active )
def __magic_name__( ):
'''simple docstring'''
global _tqdm_active
UpperCamelCase__ = True
def __magic_name__( ):
'''simple docstring'''
global _tqdm_active
UpperCamelCase__ = False
| 265
| 0
|
import argparse
import torch
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
if __name__ == "__main__":
A = argparse.ArgumentParser()
parser.add_argument(
'--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
)
# !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
parser.add_argument(
'--original_config_file',
default=None,
type=str,
help='The YAML config file corresponding to the original architecture.',
)
parser.add_argument(
'--num_in_channels',
default=None,
type=int,
help='The number of input channels. If `None` number of input channels will be automatically inferred.',
)
parser.add_argument(
'--scheduler_type',
default='pndm',
type=str,
help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']',
)
parser.add_argument(
'--pipeline_type',
default=None,
type=str,
help=(
'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\''
'. If `None` pipeline will be automatically inferred.'
),
)
parser.add_argument(
'--image_size',
default=None,
type=int,
help=(
'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
' Base. Use 768 for Stable Diffusion v2.'
),
)
parser.add_argument(
'--prediction_type',
default=None,
type=str,
help=(
'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable'
' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.'
),
)
parser.add_argument(
'--extract_ema',
action='store_true',
help=(
'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
),
)
parser.add_argument(
'--upcast_attention',
action='store_true',
help=(
'Whether the attention computation should always be upcasted. This is necessary when running stable'
' diffusion 2.1.'
),
)
parser.add_argument(
'--from_safetensors',
action='store_true',
help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
)
parser.add_argument(
'--to_safetensors',
action='store_true',
help='Whether to store pipeline in safetensors format or not.',
)
parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
parser.add_argument(
'--stable_unclip',
type=str,
default=None,
required=False,
help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.',
)
parser.add_argument(
'--stable_unclip_prior',
type=str,
default=None,
required=False,
help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.',
)
parser.add_argument(
'--clip_stats_path',
type=str,
help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.',
required=False,
)
parser.add_argument(
'--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.'
)
parser.add_argument('--half', action='store_true', help='Save weights in half precision.')
parser.add_argument(
'--vae_path',
type=str,
default=None,
required=False,
help='Set to a path, hub id to an already converted vae to not convert it again.',
)
A = parser.parse_args()
A = download_from_original_stable_diffusion_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
prediction_type=args.prediction_type,
model_type=args.pipeline_type,
extract_ema=args.extract_ema,
scheduler_type=args.scheduler_type,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
stable_unclip=args.stable_unclip,
stable_unclip_prior=args.stable_unclip_prior,
clip_stats_path=args.clip_stats_path,
controlnet=args.controlnet,
vae_path=args.vae_path,
)
if args.half:
pipe.to(torch_dtype=torch.floataa)
if args.controlnet:
# only save the controlnet model
pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
else:
pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
| 187
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
A = logging.get_logger(__name__)
A = {
'google/bit-50': 'https://huggingface.co/google/bit-50/resolve/main/config.json',
}
class SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ):
"""simple docstring"""
__A = """bit"""
__A = ["""preactivation""", """bottleneck"""]
__A = ["""SAME""", """VALID"""]
def __init__( self , __UpperCamelCase=3 , __UpperCamelCase=64 , __UpperCamelCase=[2_56, 5_12, 10_24, 20_48] , __UpperCamelCase=[3, 4, 6, 3] , __UpperCamelCase="preactivation" , __UpperCamelCase="relu" , __UpperCamelCase=None , __UpperCamelCase=32 , __UpperCamelCase=0.0 , __UpperCamelCase=False , __UpperCamelCase=32 , __UpperCamelCase=1 , __UpperCamelCase=None , __UpperCamelCase=None , **__UpperCamelCase , ):
"""simple docstring"""
super().__init__(**__UpperCamelCase )
if layer_type not in self.layer_types:
raise ValueError(f"""layer_type={layer_type} is not one of {','.join(self.layer_types )}""" )
if global_padding is not None:
if global_padding.upper() in self.supported_padding:
snake_case_ = global_padding.upper()
else:
raise ValueError(f"""Padding strategy {global_padding} not supported""" )
snake_case_ = num_channels
snake_case_ = embedding_size
snake_case_ = hidden_sizes
snake_case_ = depths
snake_case_ = layer_type
snake_case_ = hidden_act
snake_case_ = global_padding
snake_case_ = num_groups
snake_case_ = drop_path_rate
snake_case_ = embedding_dynamic_padding
snake_case_ = output_stride
snake_case_ = width_factor
snake_case_ = ['stem'] + [f"""stage{idx}""" for idx in range(1 , len(__UpperCamelCase ) + 1 )]
snake_case_ , snake_case_ = get_aligned_output_features_output_indices(
out_features=__UpperCamelCase , out_indices=__UpperCamelCase , stage_names=self.stage_names )
| 187
| 1
|
'''simple docstring'''
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConformerConfig,
WavaVecaConformerForCTC,
WavaVecaConformerForPreTraining,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
A_ = logging.get_logger(__name__)
A_ = {
"post_extract_proj": "feature_projection.projection",
"encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
"self_attn.linear_k": "encoder.layers.*.self_attn.linear_k",
"self_attn.linear_v": "encoder.layers.*.self_attn.linear_v",
"self_attn.linear_q": "encoder.layers.*.self_attn.linear_q",
"self_attn.pos_bias_u": "encoder.layers.*.self_attn.pos_bias_u",
"self_attn.pos_bias_v": "encoder.layers.*.self_attn.pos_bias_v",
"self_attn.linear_out": "encoder.layers.*.self_attn.linear_out",
"self_attn.linear_pos": "encoder.layers.*.self_attn.linear_pos",
"self_attn.rotary_emb": "encoder.embed_positions",
"self_attn_layer_norm": "encoder.layers.*.self_attn_layer_norm",
"conv_module.pointwise_conv1": "encoder.layers.*.conv_module.pointwise_conv1",
"conv_module.pointwise_conv2": "encoder.layers.*.conv_module.pointwise_conv2",
"conv_module.depthwise_conv": "encoder.layers.*.conv_module.depthwise_conv",
"conv_module.batch_norm": "encoder.layers.*.conv_module.batch_norm",
"conv_module.layer_norm": "encoder.layers.*.conv_module.layer_norm",
"ffn1.w_1": "encoder.layers.*.ffn1.intermediate_dense",
"ffn1.w_2": "encoder.layers.*.ffn1.output_dense",
"ffn1.layer_norm": "encoder.layers.*.ffn1_layer_norm",
"ffn2.w_1": "encoder.layers.*.ffn2.intermediate_dense",
"ffn2.w_2": "encoder.layers.*.ffn2.output_dense",
"ffn2.layer_norm": "encoder.layers.*.ffn2_layer_norm",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"w2v_model.layer_norm": "feature_projection.layer_norm",
"quantizer.weight_proj": "quantizer.weight_proj",
"quantizer.vars": "quantizer.codevectors",
"project_q": "project_q",
"final_proj": "project_hid",
"w2v_encoder.proj": "lm_head",
"mask_emb": "masked_spec_embed",
}
A_ = [
"lm_head",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
]
def A ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Tuple ) -> List[str]:
'''simple docstring'''
for attribute in key.split('.' ):
__lowerCAmelCase : Any = getattr(_UpperCAmelCase ,_UpperCAmelCase )
if weight_type is not None:
__lowerCAmelCase : Dict = getattr(_UpperCAmelCase ,_UpperCAmelCase ).shape
else:
__lowerCAmelCase : Tuple = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"""
F""" {value.shape} for {full_name}""" )
if weight_type == "weight":
__lowerCAmelCase : Any = value
elif weight_type == "weight_g":
__lowerCAmelCase : Optional[int] = value
elif weight_type == "weight_v":
__lowerCAmelCase : Dict = value
elif weight_type == "bias":
__lowerCAmelCase : Union[str, Any] = value
elif weight_type == "running_mean":
__lowerCAmelCase : Optional[Any] = value
elif weight_type == "running_var":
__lowerCAmelCase : List[str] = value
elif weight_type == "num_batches_tracked":
__lowerCAmelCase : Tuple = value
elif weight_type == "inv_freq":
__lowerCAmelCase : Optional[Any] = value
else:
__lowerCAmelCase : List[Any] = value
logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" )
def A ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
__lowerCAmelCase : List[str] = []
__lowerCAmelCase : Optional[int] = fairseq_model.state_dict()
__lowerCAmelCase : List[str] = hf_model.wavaveca_conformer.feature_extractor
for name, value in fairseq_dict.items():
__lowerCAmelCase : Optional[int] = False
if "conv_layers" in name:
load_conv_layer(
_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,hf_model.config.feat_extract_norm == 'group' ,)
__lowerCAmelCase : int = True
else:
for key, mapped_key in MAPPING.items():
__lowerCAmelCase : int = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
__lowerCAmelCase : Optional[Any] = True
if "*" in mapped_key:
__lowerCAmelCase : str = name.split(_UpperCAmelCase )[0].split('.' )[-2]
__lowerCAmelCase : List[str] = mapped_key.replace('*' ,_UpperCAmelCase )
if "pos_bias_u" in name:
__lowerCAmelCase : Optional[int] = None
elif "pos_bias_v" in name:
__lowerCAmelCase : Union[str, Any] = None
elif "weight_g" in name:
__lowerCAmelCase : List[Any] = 'weight_g'
elif "weight_v" in name:
__lowerCAmelCase : str = 'weight_v'
elif "bias" in name:
__lowerCAmelCase : Union[str, Any] = 'bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
__lowerCAmelCase : Union[str, Any] = 'weight'
elif "running_mean" in name:
__lowerCAmelCase : List[Any] = 'running_mean'
elif "inv_freq" in name:
__lowerCAmelCase : Union[str, Any] = 'inv_freq'
elif "running_var" in name:
__lowerCAmelCase : int = 'running_var'
elif "num_batches_tracked" in name:
__lowerCAmelCase : Optional[Any] = 'num_batches_tracked'
else:
__lowerCAmelCase : Any = None
set_recursively(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase )
continue
if not is_used:
unused_weights.append(_UpperCAmelCase )
logger.warning(F"""Unused weights: {unused_weights}""" )
def A ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : str ) -> Union[str, Any]:
'''simple docstring'''
__lowerCAmelCase : List[str] = full_name.split('conv_layers.' )[-1]
__lowerCAmelCase : Union[str, Any] = name.split('.' )
__lowerCAmelCase : Optional[Any] = int(items[0] )
__lowerCAmelCase : int = int(items[1] )
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" )
__lowerCAmelCase : Optional[int] = value
logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" )
__lowerCAmelCase : List[str] = value
logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" )
__lowerCAmelCase : List[str] = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" )
__lowerCAmelCase : str = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(_UpperCAmelCase )
@torch.no_grad()
def A ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int=None ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=True ) -> List[str]:
'''simple docstring'''
if config_path is not None:
__lowerCAmelCase : Dict = WavaVecaConformerConfig.from_pretrained(_UpperCAmelCase ,hidden_act='swish' )
else:
__lowerCAmelCase : Dict = WavaVecaConformerConfig()
if "rope" in checkpoint_path:
__lowerCAmelCase : List[Any] = 'rotary'
if is_finetuned:
if dict_path:
__lowerCAmelCase : Any = Dictionary.load(_UpperCAmelCase )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__lowerCAmelCase : List[str] = target_dict.pad_index
__lowerCAmelCase : Dict = target_dict.bos_index
__lowerCAmelCase : Any = target_dict.eos_index
__lowerCAmelCase : Optional[Any] = len(target_dict.symbols )
__lowerCAmelCase : List[str] = os.path.join(_UpperCAmelCase ,'vocab.json' )
if not os.path.isdir(_UpperCAmelCase ):
logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_UpperCAmelCase ) )
return
os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase )
__lowerCAmelCase : Union[str, Any] = target_dict.indices
# fairseq has the <pad> and <s> switched
__lowerCAmelCase : Optional[int] = 0
__lowerCAmelCase : List[Any] = 1
with open(_UpperCAmelCase ,'w' ,encoding='utf-8' ) as vocab_handle:
json.dump(_UpperCAmelCase ,_UpperCAmelCase )
__lowerCAmelCase : Union[str, Any] = WavaVecaCTCTokenizer(
_UpperCAmelCase ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token='|' ,do_lower_case=_UpperCAmelCase ,)
__lowerCAmelCase : str = True if config.feat_extract_norm == 'layer' else False
__lowerCAmelCase : Optional[int] = WavaVecaFeatureExtractor(
feature_size=1 ,sampling_rate=1_6_0_0_0 ,padding_value=0 ,do_normalize=_UpperCAmelCase ,return_attention_mask=_UpperCAmelCase ,)
__lowerCAmelCase : Tuple = WavaVecaProcessor(feature_extractor=_UpperCAmelCase ,tokenizer=_UpperCAmelCase )
processor.save_pretrained(_UpperCAmelCase )
__lowerCAmelCase : Optional[int] = WavaVecaConformerForCTC(_UpperCAmelCase )
else:
__lowerCAmelCase : List[Any] = WavaVecaConformerForPreTraining(_UpperCAmelCase )
if is_finetuned:
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] ,arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
else:
__lowerCAmelCase : Union[str, Any] = argparse.Namespace(task='audio_pretraining' )
__lowerCAmelCase : Optional[int] = fairseq.tasks.setup_task(_UpperCAmelCase )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=_UpperCAmelCase )
__lowerCAmelCase : int = model[0].eval()
recursively_load_weights(_UpperCAmelCase ,_UpperCAmelCase ,not is_finetuned )
hf_wavavec.save_pretrained(_UpperCAmelCase )
if __name__ == "__main__":
A_ = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
)
A_ = parser.parse_args()
convert_wavaveca_conformer_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 123
|
'''simple docstring'''
from math import factorial
A_ = {str(digit): factorial(digit) for digit in range(10)}
def A ( _UpperCAmelCase : int ) -> int:
'''simple docstring'''
if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ):
raise TypeError('Parameter number must be int' )
if number < 0:
raise ValueError('Parameter number must be greater than or equal to 0' )
# Converts number in string to iterate on its digits and adds its factorial.
return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) )
def A ( _UpperCAmelCase : int = 6_0 ,_UpperCAmelCase : int = 1_0_0_0_0_0_0 ) -> int:
'''simple docstring'''
if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ):
raise TypeError('Parameters chain_length and number_limit must be int' )
if chain_length <= 0 or number_limit <= 0:
raise ValueError(
'Parameters chain_length and number_limit must be greater than 0' )
# the counter for the chains with the exact desired length
__lowerCAmelCase : Any = 0
# the cached sizes of the previous chains
__lowerCAmelCase : dict[int, int] = {}
for start_chain_element in range(1 ,_UpperCAmelCase ):
# The temporary set will contain the elements of the chain
__lowerCAmelCase : Union[str, Any] = set()
__lowerCAmelCase : Union[str, Any] = 0
# Stop computing the chain when you find a cached size, a repeating item or the
# length is greater then the desired one.
__lowerCAmelCase : List[str] = start_chain_element
while (
chain_element not in chain_sets_lengths
and chain_element not in chain_set
and chain_set_length <= chain_length
):
chain_set.add(_UpperCAmelCase )
chain_set_length += 1
__lowerCAmelCase : Optional[Any] = digit_factorial_sum(_UpperCAmelCase )
if chain_element in chain_sets_lengths:
chain_set_length += chain_sets_lengths[chain_element]
__lowerCAmelCase : Any = chain_set_length
# If chain contains the exact amount of elements increase the counter
if chain_set_length == chain_length:
chains_counter += 1
return chains_counter
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F'''{solution()}''')
| 123
| 1
|
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import doctest
import sys
import warnings
from os.path import abspath, dirname, join
import _pytest
from transformers.testing_utils import HfDoctestModule, HfDocTestParser
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__snake_case :Optional[Any] =abspath(join(dirname(__file__), 'src'))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='ignore', category=FutureWarning)
def lowerCamelCase_ ( lowerCAmelCase__ : Union[str, Any] ) -> Any:
'''simple docstring'''
config.addinivalue_line(
'markers' , 'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested' )
config.addinivalue_line(
'markers' , 'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested' )
config.addinivalue_line('markers' , 'is_pipeline_test: mark test to run only when pipelines are tested' )
config.addinivalue_line('markers' , 'is_staging_test: mark test to run only in the staging environment' )
config.addinivalue_line('markers' , 'accelerate_tests: mark test that require accelerate' )
config.addinivalue_line('markers' , 'tool_tests: mark the tool tests that are run on their specific schedule' )
def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Any:
'''simple docstring'''
from transformers.testing_utils import pytest_addoption_shared
pytest_addoption_shared(lowerCAmelCase__ )
def lowerCamelCase_ ( lowerCAmelCase__ : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
from transformers.testing_utils import pytest_terminal_summary_main
A = terminalreporter.config.getoption('--make-reports' )
if make_reports:
pytest_terminal_summary_main(lowerCAmelCase__ , id=lowerCAmelCase__ )
def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] ) -> List[Any]:
'''simple docstring'''
if exitstatus == 5:
A = 0
# Doctest custom flag to ignore output.
__snake_case :int =doctest.register_optionflag('IGNORE_RESULT')
__snake_case :List[str] =doctest.OutputChecker
class lowerCAmelCase__ ( _lowerCamelCase ):
def __UpperCamelCase ( self : Tuple , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[int] , __UpperCamelCase : str ) -> List[Any]:
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
__snake_case :str =CustomOutputChecker
__snake_case :List[Any] =HfDoctestModule
__snake_case :str =HfDocTestParser
| 106
|
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ,lowerCAmelCase__ ):
if number < 0 or shift_amount < 0:
raise ValueError('both inputs must be positive integers' )
lowerCamelCase_ : int = str(bin(lowerCAmelCase__ ) )
binary_number += "0" * shift_amount
return binary_number
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ,lowerCAmelCase__ ):
if number < 0 or shift_amount < 0:
raise ValueError('both inputs must be positive integers' )
lowerCamelCase_ : Union[str, Any] = str(bin(lowerCAmelCase__ ) )[2:]
if shift_amount >= len(lowerCAmelCase__ ):
return "0b0"
lowerCamelCase_ : List[str] = binary_number[: len(lowerCAmelCase__ ) - shift_amount]
return "0b" + shifted_binary_number
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ,lowerCAmelCase__ ):
if number >= 0: # Get binary representation of positive number
lowerCamelCase_ : List[Any] = '0' + str(bin(lowerCAmelCase__ ) ).strip('-' )[2:]
else: # Get binary (2's complement) representation of negative number
lowerCamelCase_ : Any = len(bin(lowerCAmelCase__ )[3:] ) # Find 2's complement of number
lowerCamelCase_ : List[str] = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:]
lowerCamelCase_ : List[str] = (
'1' + '0' * (binary_number_length - len(lowerCAmelCase__ )) + binary_number
)
if shift_amount >= len(lowerCAmelCase__ ):
return "0b" + binary_number[0] * len(lowerCAmelCase__ )
return (
"0b"
+ binary_number[0] * shift_amount
+ binary_number[: len(lowerCAmelCase__ ) - shift_amount]
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 364
| 0
|
"""simple docstring"""
import os
import sys
import unittest
lowerCamelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))
import check_dummies # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402
# Align TRANSFORMERS_PATH in check_dummies with the current path
lowerCamelCase = os.path.join(git_repo_path, """src""", """diffusers""")
class lowercase__ ( unittest.TestCase ):
'''simple docstring'''
def lowercase__ ( self : Dict ) -> List[Any]:
'''simple docstring'''
UpperCAmelCase_ = find_backend(" if not is_torch_available():" )
self.assertEqual(_UpperCAmelCase , "torch" )
# backend_with_underscore = find_backend(" if not is_tensorflow_text_available():")
# self.assertEqual(backend_with_underscore, "tensorflow_text")
UpperCAmelCase_ = find_backend(" if not (is_torch_available() and is_transformers_available()):" )
self.assertEqual(_UpperCAmelCase , "torch_and_transformers" )
# double_backend_with_underscore = find_backend(
# " if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
# )
# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")
UpperCAmelCase_ = find_backend(
" if not (is_torch_available() and is_transformers_available() and is_onnx_available()):" )
self.assertEqual(_UpperCAmelCase , "torch_and_transformers_and_onnx" )
def lowercase__ ( self : Any ) -> Optional[Any]:
'''simple docstring'''
UpperCAmelCase_ = read_init()
# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
self.assertIn("torch" , _UpperCAmelCase )
self.assertIn("torch_and_transformers" , _UpperCAmelCase )
self.assertIn("flax_and_transformers" , _UpperCAmelCase )
self.assertIn("torch_and_transformers_and_onnx" , _UpperCAmelCase )
# Likewise, we can't assert on the exact content of a key
self.assertIn("UNet2DModel" , objects["torch"] )
self.assertIn("FlaxUNet2DConditionModel" , objects["flax"] )
self.assertIn("StableDiffusionPipeline" , objects["torch_and_transformers"] )
self.assertIn("FlaxStableDiffusionPipeline" , objects["flax_and_transformers"] )
self.assertIn("LMSDiscreteScheduler" , objects["torch_and_scipy"] )
self.assertIn("OnnxStableDiffusionPipeline" , objects["torch_and_transformers_and_onnx"] )
def lowercase__ ( self : str ) -> Any:
'''simple docstring'''
UpperCAmelCase_ = create_dummy_object("CONSTANT" , "'torch'" )
self.assertEqual(_UpperCAmelCase , "\nCONSTANT = None\n" )
UpperCAmelCase_ = create_dummy_object("function" , "'torch'" )
self.assertEqual(
_UpperCAmelCase , "\ndef function(*args, **kwargs):\n requires_backends(function, 'torch')\n" )
UpperCAmelCase_ = "\nclass FakeClass(metaclass=DummyObject):\n _backends = 'torch'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, 'torch')\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, 'torch')\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, 'torch')\n"
UpperCAmelCase_ = create_dummy_object("FakeClass" , "'torch'" )
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
def lowercase__ ( self : Union[str, Any] ) -> int:
'''simple docstring'''
UpperCAmelCase_ = "# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = [\"torch\"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, [\"torch\"])\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, [\"torch\"])\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, [\"torch\"])\n"
UpperCAmelCase_ = create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]} )
self.assertEqual(dummy_files["torch"] , _UpperCAmelCase )
| 14
|
"""simple docstring"""
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_valid_image,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
lowerCamelCase = logging.get_logger(__name__)
def a__ ( lowerCAmelCase__ ):
if isinstance(lowerCAmelCase__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ):
return videos
elif isinstance(lowerCAmelCase__ , (list, tuple) ) and is_valid_image(videos[0] ):
return [videos]
elif is_valid_image(lowerCAmelCase__ ):
return [[videos]]
raise ValueError(f"""Could not make batched video from {videos}""" )
class lowercase__ ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
UpperCamelCase = ['''pixel_values''']
def __init__( self : Tuple , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 255 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , **_UpperCAmelCase : Any , ) -> None:
'''simple docstring'''
super().__init__(**_UpperCAmelCase )
UpperCAmelCase_ = size if size is not None else {"shortest_edge": 224}
UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase )
UpperCAmelCase_ = crop_size if crop_size is not None else {"height": 224, "width": 224}
UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , param_name="crop_size" )
UpperCAmelCase_ = do_resize
UpperCAmelCase_ = size
UpperCAmelCase_ = do_center_crop
UpperCAmelCase_ = crop_size
UpperCAmelCase_ = resample
UpperCAmelCase_ = do_rescale
UpperCAmelCase_ = rescale_factor
UpperCAmelCase_ = do_normalize
UpperCAmelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
UpperCAmelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def lowercase__ ( self : Tuple , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Tuple , ) -> np.ndarray:
'''simple docstring'''
UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase )
if "shortest_edge" in size:
UpperCAmelCase_ = get_resize_output_image_size(_UpperCAmelCase , size["shortest_edge"] , default_to_square=_UpperCAmelCase )
elif "height" in size and "width" in size:
UpperCAmelCase_ = (size["height"], size["width"])
else:
raise ValueError(F"""Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" )
return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase )
def lowercase__ ( self : Union[str, Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Union[str, Any] , ) -> np.ndarray:
'''simple docstring'''
UpperCAmelCase_ = get_size_dict(_UpperCAmelCase )
if "height" not in size or "width" not in size:
raise ValueError(F"""Size must have 'height' and 'width' as keys. Got {size.keys()}""" )
return center_crop(_UpperCAmelCase , size=(size["height"], size["width"]) , data_format=_UpperCAmelCase , **_UpperCAmelCase )
def lowercase__ ( self : List[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : str , ) -> List[str]:
'''simple docstring'''
return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase )
def lowercase__ ( self : Optional[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Tuple , ) -> np.ndarray:
'''simple docstring'''
return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase )
def lowercase__ ( self : Any , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray:
'''simple docstring'''
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_center_crop and crop_size is None:
raise ValueError("Crop size must be specified if do_center_crop is True." )
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True." )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("Image mean and std must be specified if do_normalize is True." )
# All transformations expect numpy arrays.
UpperCAmelCase_ = to_numpy_array(_UpperCAmelCase )
if do_resize:
UpperCAmelCase_ = self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase )
if do_center_crop:
UpperCAmelCase_ = self.center_crop(_UpperCAmelCase , size=_UpperCAmelCase )
if do_rescale:
UpperCAmelCase_ = self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase )
if do_normalize:
UpperCAmelCase_ = self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase )
UpperCAmelCase_ = to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase )
return image
def lowercase__ ( self : Optional[Any] , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCAmelCase : int , ) -> PIL.Image.Image:
'''simple docstring'''
UpperCAmelCase_ = do_resize if do_resize is not None else self.do_resize
UpperCAmelCase_ = resample if resample is not None else self.resample
UpperCAmelCase_ = do_center_crop if do_center_crop is not None else self.do_center_crop
UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale
UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor
UpperCAmelCase_ = do_normalize if do_normalize is not None else self.do_normalize
UpperCAmelCase_ = image_mean if image_mean is not None else self.image_mean
UpperCAmelCase_ = image_std if image_std is not None else self.image_std
UpperCAmelCase_ = size if size is not None else self.size
UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , default_to_square=_UpperCAmelCase )
UpperCAmelCase_ = crop_size if crop_size is not None else self.crop_size
UpperCAmelCase_ = get_size_dict(_UpperCAmelCase , param_name="crop_size" )
if not valid_images(_UpperCAmelCase ):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray." )
UpperCAmelCase_ = make_batched(_UpperCAmelCase )
UpperCAmelCase_ = [
[
self._preprocess_image(
image=_UpperCAmelCase , do_resize=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , do_center_crop=_UpperCAmelCase , crop_size=_UpperCAmelCase , do_rescale=_UpperCAmelCase , rescale_factor=_UpperCAmelCase , do_normalize=_UpperCAmelCase , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase , data_format=_UpperCAmelCase , )
for img in video
]
for video in videos
]
UpperCAmelCase_ = {"pixel_values": videos}
return BatchFeature(data=_UpperCAmelCase , tensor_type=_UpperCAmelCase )
| 14
| 1
|
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
class A_ ( unittest.TestCase , a_ ):
def _UpperCAmelCase ( self : Tuple ):
__a = load_tool("text-classification" )
self.tool.setup()
__a = load_tool("text-classification" , remote=__SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( self : Dict ):
__a = self.tool("That's quite cool" , ["positive", "negative"] )
self.assertEqual(__SCREAMING_SNAKE_CASE , "positive" )
def _UpperCAmelCase ( self : List[Any] ):
__a = self.remote_tool("That's quite cool" , ["positive", "negative"] )
self.assertEqual(__SCREAMING_SNAKE_CASE , "positive" )
def _UpperCAmelCase ( self : Union[str, Any] ):
__a = self.tool(text="That's quite cool" , labels=["positive", "negative"] )
self.assertEqual(__SCREAMING_SNAKE_CASE , "positive" )
def _UpperCAmelCase ( self : List[str] ):
__a = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] )
self.assertEqual(__SCREAMING_SNAKE_CASE , "positive" )
| 197
|
from typing import TYPE_CHECKING
from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
SCREAMING_SNAKE_CASE : Optional[int] = {
"""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:
SCREAMING_SNAKE_CASE : Optional[Any] = [
"""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
SCREAMING_SNAKE_CASE : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 197
| 1
|
import random
import unittest
import torch
from diffusers import IFInpaintingPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device
from ..pipeline_params import (
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class __lowercase ( a__ , a__ , unittest.TestCase ):
_lowerCAmelCase = IFInpaintingPipeline
_lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"}
_lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
_lowerCAmelCase = PipelineTesterMixin.required_optional_params - {"latents"}
def __magic_name__ ( self : List[str] ):
return self._get_dummy_components()
def __magic_name__ ( self : Optional[Any] , lowercase__ : Tuple , lowercase__ : Dict=0 ):
if str(lowercase__ ).startswith('''mps''' ):
a_ = torch.manual_seed(lowercase__ )
else:
a_ = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ )
a_ = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(lowercase__ ) ).to(lowercase__ )
a_ = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(lowercase__ ) ).to(lowercase__ )
a_ = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''image''': image,
'''mask_image''': mask_image,
'''generator''': generator,
'''num_inference_steps''': 2,
'''output_type''': '''numpy''',
}
return inputs
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def __magic_name__ ( self : List[str] ):
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 )
def __magic_name__ ( self : List[Any] ):
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' )
def __magic_name__ ( self : Any ):
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
super().test_save_load_floataa(expected_max_diff=1e-1 )
def __magic_name__ ( self : str ):
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 )
def __magic_name__ ( self : List[Any] ):
self._test_save_load_local()
def __magic_name__ ( self : Any ):
self._test_inference_batch_single_identical(
expected_max_diff=1e-2 , )
| 143
|
import qiskit
def UpperCAmelCase__ ( _A , _A ):
"""simple docstring"""
a_ = qiskit.Aer.get_backend('''aer_simulator''' )
a_ = qiskit.QuantumCircuit(4 , 2 )
# encode inputs in qubits 0 and 1
if bita == 1:
qc_ha.x(0 )
if bita == 1:
qc_ha.x(1 )
qc_ha.barrier()
# use cnots to write XOR of the inputs on qubit2
qc_ha.cx(0 , 2 )
qc_ha.cx(1 , 2 )
# use ccx / toffoli gate to write AND of the inputs on qubit3
qc_ha.ccx(0 , 1 , 3 )
qc_ha.barrier()
# extract outputs
qc_ha.measure(2 , 0 ) # extract XOR value
qc_ha.measure(3 , 1 ) # extract AND value
# Execute the circuit on the qasm simulator
a_ = qiskit.execute(_A , _A , shots=1_000 )
# Return the histogram data of the results of the experiment
return job.result().get_counts(_A )
if __name__ == "__main__":
UpperCamelCase__ = half_adder(1, 1)
print(F"""Half Adder Output Qubit Counts: {counts}""")
| 143
| 1
|
'''simple docstring'''
import inspect
import unittest
from transformers import ViTConfig
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowercase__ :
'''simple docstring'''
def __init__( self , lowerCamelCase__ , lowerCamelCase__=1_3 , lowerCamelCase__=3_0 , lowerCamelCase__=2 , lowerCamelCase__=3 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=3_2 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=3_7 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=1_0 , lowerCamelCase__=0.02 , lowerCamelCase__=None , lowerCamelCase__=2 , ):
'''simple docstring'''
UpperCamelCase = parent
UpperCamelCase = batch_size
UpperCamelCase = image_size
UpperCamelCase = patch_size
UpperCamelCase = num_channels
UpperCamelCase = is_training
UpperCamelCase = use_labels
UpperCamelCase = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = intermediate_size
UpperCamelCase = hidden_act
UpperCamelCase = hidden_dropout_prob
UpperCamelCase = attention_probs_dropout_prob
UpperCamelCase = type_sequence_label_size
UpperCamelCase = initializer_range
UpperCamelCase = scope
UpperCamelCase = encoder_stride
# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
UpperCamelCase = (image_size // patch_size) ** 2
UpperCamelCase = num_patches + 1
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
UpperCamelCase = None
if self.use_labels:
UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCamelCase = self.get_config()
return config, pixel_values, labels
def UpperCAmelCase ( self ):
'''simple docstring'''
return ViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
UpperCamelCase = ViTModel(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
UpperCamelCase = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
UpperCamelCase = ViTForMaskedImageModeling(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
UpperCamelCase = model(lowerCamelCase__ )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
UpperCamelCase = 1
UpperCamelCase = ViTForMaskedImageModeling(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
UpperCamelCase = model(lowerCamelCase__ )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
UpperCamelCase = self.type_sequence_label_size
UpperCamelCase = ViTForImageClassification(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
UpperCamelCase = model(lowerCamelCase__ , labels=lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
UpperCamelCase = 1
UpperCamelCase = ViTForImageClassification(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
UpperCamelCase = model(lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.prepare_config_and_inputs()
(
(
UpperCamelCase
) , (
UpperCamelCase
) , (
UpperCamelCase
) ,
) = config_and_inputs
UpperCamelCase = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class lowercase__ ( snake_case_, snake_case_, unittest.TestCase ):
'''simple docstring'''
_snake_case = (
(
ViTModel,
ViTForImageClassification,
ViTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
_snake_case = (
{'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
if is_torch_available()
else {}
)
_snake_case = True
_snake_case = False
_snake_case = False
_snake_case = False
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTModelTester(self )
UpperCamelCase = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=3_7 )
def UpperCAmelCase ( self ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''ViT does not use inputs_embeds''' )
def UpperCAmelCase ( self ):
'''simple docstring'''
pass
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(lowerCamelCase__ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCamelCase = model_class(lowerCamelCase__ )
UpperCamelCase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCamelCase = [*signature.parameters.keys()]
UpperCamelCase = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , lowerCamelCase__ )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase__ )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__ )
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ )
@slow
def UpperCAmelCase ( self ):
'''simple docstring'''
for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCamelCase = ViTModel.from_pretrained(lowerCamelCase__ )
self.assertIsNotNone(lowerCamelCase__ )
def __snake_case ( ):
UpperCamelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
return image
@require_torch
@require_vision
class lowercase__ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def UpperCAmelCase ( self ):
'''simple docstring'''
return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None
@slow
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' ).to(lowerCamelCase__ )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=lowerCamelCase__ , return_tensors='''pt''' ).to(lowerCamelCase__ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(**lowerCamelCase__ )
# verify the logits
UpperCamelCase = torch.Size((1, 1_0_0_0) )
self.assertEqual(outputs.logits.shape , lowerCamelCase__ )
UpperCamelCase = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase__ , atol=1e-4 ) )
@slow
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTModel.from_pretrained('''facebook/dino-vits8''' ).to(lowerCamelCase__ )
UpperCamelCase = ViTImageProcessor.from_pretrained('''facebook/dino-vits8''' , size=4_8_0 )
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=lowerCamelCase__ , return_tensors='''pt''' )
UpperCamelCase = inputs.pixel_values.to(lowerCamelCase__ )
# forward pass
with torch.no_grad():
UpperCamelCase = model(lowerCamelCase__ , interpolate_pos_encoding=lowerCamelCase__ )
# verify the logits
UpperCamelCase = torch.Size((1, 3_6_0_1, 3_8_4) )
self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase__ )
UpperCamelCase = torch.tensor(
[[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase__ )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase__ , atol=1e-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def UpperCAmelCase ( self ):
'''simple docstring'''
UpperCamelCase = ViTModel.from_pretrained('''facebook/dino-vits8''' , torch_dtype=torch.floataa , device_map='''auto''' )
UpperCamelCase = self.default_image_processor
UpperCamelCase = prepare_img()
UpperCamelCase = image_processor(images=lowerCamelCase__ , return_tensors='''pt''' )
UpperCamelCase = inputs.pixel_values.to(lowerCamelCase__ )
# forward pass to make sure inference works in fp16
with torch.no_grad():
UpperCamelCase = model(lowerCamelCase__ )
| 212
|
'''simple docstring'''
import pytest
from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict
@pytest.mark.parametrize(
'''split_dict''', [
SplitDict(),
SplitDict({'''train''': SplitInfo(name='''train''', num_bytes=1337, num_examples=42, dataset_name='''my_dataset''')}),
SplitDict({'''train''': SplitInfo(name='''train''', num_bytes=1337, num_examples=42)}),
SplitDict({'''train''': SplitInfo()}),
], )
def __snake_case ( _UpperCAmelCase : SplitDict):
UpperCamelCase = split_dict._to_yaml_list()
assert len(_UpperCAmelCase) == len(_UpperCAmelCase)
UpperCamelCase = SplitDict._from_yaml_list(_UpperCAmelCase)
for split_name, split_info in split_dict.items():
# dataset_name field is deprecated, and is therefore not part of the YAML dump
UpperCamelCase = None
# the split name of split_dict takes over the name of the split info object
UpperCamelCase = split_name
assert split_dict == reloaded
@pytest.mark.parametrize(
'''split_info''', [SplitInfo(), SplitInfo(dataset_name=_UpperCAmelCase), SplitInfo(dataset_name='''my_dataset''')])
def __snake_case ( _UpperCAmelCase : Dict):
# For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name"
# field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files
UpperCamelCase = asdict(SplitDict({'''train''': split_info}))
assert "dataset_name" in split_dict_asdict["train"]
assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
| 212
| 1
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available
lowercase : Optional[int] = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase : List[Any] = ['''GPTSw3Tokenizer''']
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_gpt_swa import GPTSwaTokenizer
else:
import sys
lowercase : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 709
|
import os
import sys
import unittest
lowercase : Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))
import check_dummies # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402
# Align TRANSFORMERS_PATH in check_dummies with the current path
lowercase : int = os.path.join(git_repo_path, """src""", """transformers""")
lowercase : str = """
{0} = None
"""
lowercase : Union[str, Any] = """
class {0}(metaclass=DummyObject):
_backends = {1}
def __init__(self, *args, **kwargs):
requires_backends(self, {1})
"""
lowercase : Optional[Any] = """
def {0}(*args, **kwargs):
requires_backends({0}, {1})
"""
class __A( unittest.TestCase ):
def _UpperCamelCase ( self ):
"""simple docstring"""
_UpperCamelCase = find_backend(''' _import_structure["models.albert"].append("AlbertTokenizerFast")''' )
self.assertIsNone(A )
_UpperCamelCase = find_backend(''' if not is_tokenizers_available():''' )
self.assertEqual(A, '''tokenizers''' )
_UpperCamelCase = find_backend(''' if not is_tensorflow_text_available():''' )
self.assertEqual(A, '''tensorflow_text''' )
_UpperCamelCase = find_backend(''' if not (is_sentencepiece_available() and is_tokenizers_available()):''' )
self.assertEqual(A, '''sentencepiece_and_tokenizers''' )
_UpperCamelCase = find_backend(
''' if not (is_sentencepiece_available() and is_tensorflow_text_available()):''' )
self.assertEqual(A, '''sentencepiece_and_tensorflow_text''' )
_UpperCamelCase = find_backend(
''' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''' )
self.assertEqual(A, '''sentencepiece_and_tokenizers_and_vision''' )
def _UpperCamelCase ( self ):
"""simple docstring"""
_UpperCamelCase = read_init()
# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
self.assertIn('''torch''', A )
self.assertIn('''tensorflow_text''', A )
self.assertIn('''sentencepiece_and_tokenizers''', A )
# Likewise, we can't assert on the exact content of a key
self.assertIn('''BertModel''', objects['''torch'''] )
self.assertIn('''TFBertModel''', objects['''tf'''] )
self.assertIn('''FlaxBertModel''', objects['''flax'''] )
self.assertIn('''BertModel''', objects['''torch'''] )
self.assertIn('''TFBertTokenizer''', objects['''tensorflow_text'''] )
self.assertIn('''convert_slow_tokenizer''', objects['''sentencepiece_and_tokenizers'''] )
def _UpperCamelCase ( self ):
"""simple docstring"""
_UpperCamelCase = create_dummy_object('''CONSTANT''', '''\'torch\'''' )
self.assertEqual(A, '''\nCONSTANT = None\n''' )
_UpperCamelCase = create_dummy_object('''function''', '''\'torch\'''' )
self.assertEqual(
A, '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' )
_UpperCamelCase = '''
class FakeClass(metaclass=DummyObject):
_backends = \'torch\'
def __init__(self, *args, **kwargs):
requires_backends(self, \'torch\')
'''
_UpperCamelCase = create_dummy_object('''FakeClass''', '''\'torch\'''' )
self.assertEqual(A, A )
def _UpperCamelCase ( self ):
"""simple docstring"""
_UpperCamelCase = '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends
CONSTANT = None
def function(*args, **kwargs):
requires_backends(function, ["torch"])
class FakeClass(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
'''
_UpperCamelCase = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} )
self.assertEqual(dummy_files['''torch'''], A )
| 105
| 0
|
"""simple docstring"""
import unittest
from knapsack import knapsack as k
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def _lowerCAmelCase ( self : List[str] ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = 0
SCREAMING_SNAKE_CASE : int = [0]
SCREAMING_SNAKE_CASE : Optional[int] = [0]
SCREAMING_SNAKE_CASE : Optional[Any] = len(_SCREAMING_SNAKE_CASE )
self.assertEqual(k.knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 0 )
SCREAMING_SNAKE_CASE : List[str] = [60]
SCREAMING_SNAKE_CASE : Tuple = [10]
SCREAMING_SNAKE_CASE : int = len(_SCREAMING_SNAKE_CASE )
self.assertEqual(k.knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 0 )
def _lowerCAmelCase ( self : Dict ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = 3
SCREAMING_SNAKE_CASE : int = [1, 2, 3]
SCREAMING_SNAKE_CASE : str = [3, 2, 1]
SCREAMING_SNAKE_CASE : Dict = len(_SCREAMING_SNAKE_CASE )
self.assertEqual(k.knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 5 )
def _lowerCAmelCase ( self : List[str] ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = 50
SCREAMING_SNAKE_CASE : Dict = [60, 100, 120]
SCREAMING_SNAKE_CASE : str = [10, 20, 30]
SCREAMING_SNAKE_CASE : Dict = len(_SCREAMING_SNAKE_CASE )
self.assertEqual(k.knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , 220 )
if __name__ == "__main__":
unittest.main()
| 265
|
"""simple docstring"""
A_ : Optional[Any] = '0.18.2'
from .configuration_utils import ConfigMixin
from .utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_inflect_available,
is_invisible_watermark_available,
is_k_diffusion_available,
is_k_diffusion_version,
is_librosa_available,
is_note_seq_available,
is_onnx_available,
is_scipy_available,
is_torch_available,
is_torchsde_available,
is_transformers_available,
is_transformers_version,
is_unidecode_available,
logging,
)
try:
if not is_onnx_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_onnx_objects import * # noqa F403
else:
from .pipelines import OnnxRuntimeModel
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_pt_objects import * # noqa F403
else:
from .models import (
AutoencoderKL,
ControlNetModel,
ModelMixin,
PriorTransformer,
TaFilmDecoder,
TransformeraDModel,
UNetaDModel,
UNetaDConditionModel,
UNetaDModel,
UNetaDConditionModel,
VQModel,
)
from .optimization import (
get_constant_schedule,
get_constant_schedule_with_warmup,
get_cosine_schedule_with_warmup,
get_cosine_with_hard_restarts_schedule_with_warmup,
get_linear_schedule_with_warmup,
get_polynomial_decay_schedule_with_warmup,
get_scheduler,
)
from .pipelines import (
AudioPipelineOutput,
ConsistencyModelPipeline,
DanceDiffusionPipeline,
DDIMPipeline,
DDPMPipeline,
DiffusionPipeline,
DiTPipeline,
ImagePipelineOutput,
KarrasVePipeline,
LDMPipeline,
LDMSuperResolutionPipeline,
PNDMPipeline,
RePaintPipeline,
ScoreSdeVePipeline,
)
from .schedulers import (
CMStochasticIterativeScheduler,
DDIMInverseScheduler,
DDIMParallelScheduler,
DDIMScheduler,
DDPMParallelScheduler,
DDPMScheduler,
DEISMultistepScheduler,
DPMSolverMultistepInverseScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
HeunDiscreteScheduler,
IPNDMScheduler,
KarrasVeScheduler,
KDPMaAncestralDiscreteScheduler,
KDPMaDiscreteScheduler,
PNDMScheduler,
RePaintScheduler,
SchedulerMixin,
ScoreSdeVeScheduler,
UnCLIPScheduler,
UniPCMultistepScheduler,
VQDiffusionScheduler,
)
from .training_utils import EMAModel
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 .schedulers 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 .schedulers import DPMSolverSDEScheduler
try:
if not (is_torch_available() and is_transformers_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .pipelines import (
AltDiffusionImgaImgPipeline,
AltDiffusionPipeline,
AudioLDMPipeline,
CycleDiffusionPipeline,
IFImgaImgPipeline,
IFImgaImgSuperResolutionPipeline,
IFInpaintingPipeline,
IFInpaintingSuperResolutionPipeline,
IFPipeline,
IFSuperResolutionPipeline,
ImageTextPipelineOutput,
KandinskyImgaImgPipeline,
KandinskyInpaintPipeline,
KandinskyPipeline,
KandinskyPriorPipeline,
KandinskyVaaControlnetImgaImgPipeline,
KandinskyVaaControlnetPipeline,
KandinskyVaaImgaImgPipeline,
KandinskyVaaInpaintPipeline,
KandinskyVaaPipeline,
KandinskyVaaPriorEmbaEmbPipeline,
KandinskyVaaPriorPipeline,
LDMTextToImagePipeline,
PaintByExamplePipeline,
SemanticStableDiffusionPipeline,
ShapEImgaImgPipeline,
ShapEPipeline,
StableDiffusionAttendAndExcitePipeline,
StableDiffusionControlNetImgaImgPipeline,
StableDiffusionControlNetInpaintPipeline,
StableDiffusionControlNetPipeline,
StableDiffusionDepthaImgPipeline,
StableDiffusionDiffEditPipeline,
StableDiffusionImageVariationPipeline,
StableDiffusionImgaImgPipeline,
StableDiffusionInpaintPipeline,
StableDiffusionInpaintPipelineLegacy,
StableDiffusionInstructPixaPixPipeline,
StableDiffusionLatentUpscalePipeline,
StableDiffusionLDMaDPipeline,
StableDiffusionModelEditingPipeline,
StableDiffusionPanoramaPipeline,
StableDiffusionParadigmsPipeline,
StableDiffusionPipeline,
StableDiffusionPipelineSafe,
StableDiffusionPixaPixZeroPipeline,
StableDiffusionSAGPipeline,
StableDiffusionUpscalePipeline,
StableUnCLIPImgaImgPipeline,
StableUnCLIPPipeline,
TextToVideoSDPipeline,
TextToVideoZeroPipeline,
UnCLIPImageVariationPipeline,
UnCLIPPipeline,
UniDiffuserModel,
UniDiffuserPipeline,
UniDiffuserTextDecoder,
VersatileDiffusionDualGuidedPipeline,
VersatileDiffusionImageVariationPipeline,
VersatileDiffusionPipeline,
VersatileDiffusionTextToImagePipeline,
VideoToVideoSDPipeline,
VQDiffusionPipeline,
)
try:
if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403
else:
from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline
try:
if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
else:
from .pipelines import StableDiffusionKDiffusionPipeline
try:
if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
else:
from .pipelines import (
OnnxStableDiffusionImgaImgPipeline,
OnnxStableDiffusionInpaintPipeline,
OnnxStableDiffusionInpaintPipelineLegacy,
OnnxStableDiffusionPipeline,
OnnxStableDiffusionUpscalePipeline,
StableDiffusionOnnxPipeline,
)
try:
if not (is_torch_available() and is_librosa_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_torch_and_librosa_objects import * # noqa F403
else:
from .pipelines import AudioDiffusionPipeline, Mel
try:
if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
else:
from .pipelines import SpectrogramDiffusionPipeline
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_flax_objects import * # noqa F403
else:
from .models.controlnet_flax import FlaxControlNetModel
from .models.modeling_flax_utils import FlaxModelMixin
from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
from .models.vae_flax import FlaxAutoencoderKL
from .pipelines import FlaxDiffusionPipeline
from .schedulers import (
FlaxDDIMScheduler,
FlaxDDPMScheduler,
FlaxDPMSolverMultistepScheduler,
FlaxKarrasVeScheduler,
FlaxLMSDiscreteScheduler,
FlaxPNDMScheduler,
FlaxSchedulerMixin,
FlaxScoreSdeVeScheduler,
)
try:
if not (is_flax_available() and is_transformers_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_flax_and_transformers_objects import * # noqa F403
else:
from .pipelines import (
FlaxStableDiffusionControlNetPipeline,
FlaxStableDiffusionImgaImgPipeline,
FlaxStableDiffusionInpaintPipeline,
FlaxStableDiffusionPipeline,
)
try:
if not (is_note_seq_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from .utils.dummy_note_seq_objects import * # noqa F403
else:
from .pipelines import MidiProcessor
| 265
| 1
|
import warnings
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ):
A__ : List[str] = ['''image_processor''', '''tokenizer''']
A__ : Tuple = '''CLIPImageProcessor'''
A__ : List[str] = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''')
def __init__( self : Optional[int] , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , **__lowerCamelCase : List[Any] ):
"""simple docstring"""
_snake_case = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __lowerCamelCase , )
_snake_case = kwargs.pop('''feature_extractor''' )
_snake_case = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''' )
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''' )
super().__init__(__lowerCamelCase , __lowerCamelCase )
def __call__( self : str , __lowerCamelCase : Dict=None , __lowerCamelCase : int=None , __lowerCamelCase : Union[str, Any]=None , **__lowerCamelCase : List[str] ):
"""simple docstring"""
if text is None and images is None:
raise ValueError('''You have to specify either text or images. Both cannot be none.''' )
if text is not None:
_snake_case = self.tokenizer(__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase )
if images is not None:
_snake_case = self.image_processor(__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase )
if text is not None and images is not None:
_snake_case = image_features.pixel_values
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**__lowerCamelCase ) , tensor_type=__lowerCamelCase )
def __UpperCAmelCase ( self : Optional[int] , *__lowerCamelCase : List[str] , **__lowerCamelCase : Optional[Any] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*__lowerCamelCase , **__lowerCamelCase )
def __UpperCAmelCase ( self : Any , *__lowerCamelCase : List[str] , **__lowerCamelCase : str ):
"""simple docstring"""
return self.tokenizer.decode(*__lowerCamelCase , **__lowerCamelCase )
@property
def __UpperCAmelCase ( self : int ):
"""simple docstring"""
_snake_case = self.tokenizer.model_input_names
_snake_case = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
| 715
|
"""simple docstring"""
def snake_case ( lowerCAmelCase_ ) -> None:
_snake_case = generate_pascal_triangle(lowerCAmelCase_ )
for row_idx in range(lowerCAmelCase_ ):
# Print left spaces
for _ in range(num_rows - row_idx - 1 ):
print(end=''' ''' )
# Print row values
for col_idx in range(row_idx + 1 ):
if col_idx != row_idx:
print(triangle[row_idx][col_idx] , end=''' ''' )
else:
print(triangle[row_idx][col_idx] , end='''''' )
print()
def snake_case ( lowerCAmelCase_ ) -> list[list[int]]:
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise TypeError('''The input value of \'num_rows\' should be \'int\'''' )
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
'''The input value of \'num_rows\' should be greater than or equal to 0''' )
_snake_case = []
for current_row_idx in range(lowerCAmelCase_ ):
_snake_case = populate_current_row(lowerCAmelCase_ , lowerCAmelCase_ )
triangle.append(lowerCAmelCase_ )
return triangle
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[int]:
_snake_case = [-1] * (current_row_idx + 1)
# first and last elements of current row are equal to 1
_snake_case , _snake_case = 1, 1
for current_col_idx in range(1 , lowerCAmelCase_ ):
calculate_current_element(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
return current_row
def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) -> None:
_snake_case = triangle[current_row_idx - 1][current_col_idx - 1]
_snake_case = triangle[current_row_idx - 1][current_col_idx]
_snake_case = above_to_left_elt + above_to_right_elt
def snake_case ( lowerCAmelCase_ ) -> list[list[int]]:
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
raise TypeError('''The input value of \'num_rows\' should be \'int\'''' )
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
'''The input value of \'num_rows\' should be greater than or equal to 0''' )
_snake_case = [[1]]
for row_index in range(1 , lowerCAmelCase_ ):
_snake_case = [0] + result[-1] + [0]
_snake_case = row_index + 1
# Calculate the number of distinct elements in a row
_snake_case = sum(divmod(lowerCAmelCase_ , 2 ) )
_snake_case = [
temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 )
]
_snake_case = row_first_half[: (row_index + 1) // 2]
row_second_half.reverse()
_snake_case = row_first_half + row_second_half
result.append(lowerCAmelCase_ )
return result
def snake_case ( ) -> None:
from collections.abc import Callable
from timeit import timeit
def benchmark_a_function(lowerCAmelCase_ , lowerCAmelCase_ ) -> None:
_snake_case = f"""{func.__name__}({value})"""
_snake_case = timeit(f"""__main__.{call}""" , setup='''import __main__''' )
# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
print(f"""{call:38} -- {timing:.4f} seconds""" )
for value in range(15 ): # (1, 7, 14):
for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
benchmark_a_function(lowerCAmelCase_ , lowerCAmelCase_ )
print()
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 404
| 0
|
"""simple docstring"""
from __future__ import annotations
import inspect
import unittest
import numpy as np
from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFResNetForImageClassification, TFResNetModel
from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class A:
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE__=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__="relu" , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=None , ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase :Tuple = parent
_UpperCamelCase :Union[str, Any] = batch_size
_UpperCamelCase :str = image_size
_UpperCamelCase :Optional[int] = num_channels
_UpperCamelCase :str = embeddings_size
_UpperCamelCase :List[Any] = hidden_sizes
_UpperCamelCase :List[str] = depths
_UpperCamelCase :Dict = is_training
_UpperCamelCase :List[str] = use_labels
_UpperCamelCase :Dict = hidden_act
_UpperCamelCase :Optional[int] = num_labels
_UpperCamelCase :Tuple = scope
_UpperCamelCase :List[Any] = len(SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self ) -> List[str]:
"""simple docstring"""
_UpperCamelCase :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_UpperCamelCase :Any = None
if self.use_labels:
_UpperCamelCase :int = ids_tensor([self.batch_size] , self.num_labels )
_UpperCamelCase :Dict = self.get_config()
return config, pixel_values, labels
def _UpperCamelCase( self ) -> Optional[Any]:
"""simple docstring"""
return ResNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , )
def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]:
"""simple docstring"""
_UpperCamelCase :Tuple = TFResNetModel(config=SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]:
"""simple docstring"""
_UpperCamelCase :List[Any] = self.num_labels
_UpperCamelCase :Tuple = TFResNetForImageClassification(SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :List[str] = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _UpperCamelCase( self ) -> int:
"""simple docstring"""
_UpperCamelCase :Union[str, Any] = self.prepare_config_and_inputs()
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase :str = config_and_inputs
_UpperCamelCase :List[str] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_tf
class A( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ):
"""simple docstring"""
A = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
A = (
{"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
if is_tf_available()
else {}
)
A = False
A = False
A = False
A = False
A = False
def _UpperCamelCase( self ) -> List[str]:
"""simple docstring"""
_UpperCamelCase :str = TFResNetModelTester(self )
_UpperCamelCase :Optional[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self ) -> Tuple:
"""simple docstring"""
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def _UpperCamelCase( self ) -> List[Any]:
"""simple docstring"""
return
@unittest.skip(reason='''ResNet does not use inputs_embeds''' )
def _UpperCamelCase( self ) -> Tuple:
"""simple docstring"""
pass
@unittest.skip(reason='''ResNet does not support input and output embeddings''' )
def _UpperCamelCase( self ) -> Dict:
"""simple docstring"""
pass
def _UpperCamelCase( self ) -> List[str]:
"""simple docstring"""
_UpperCamelCase , _UpperCamelCase :str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :Optional[Any] = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase :Union[str, Any] = [*signature.parameters.keys()]
_UpperCamelCase :List[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self ) -> int:
"""simple docstring"""
_UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self ) -> Optional[Any]:
"""simple docstring"""
def check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
_UpperCamelCase :List[str] = model_class(SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
_UpperCamelCase :Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
_UpperCamelCase :Dict = self.model_tester.num_stages
self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , expected_num_stages + 1 )
# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , )
_UpperCamelCase , _UpperCamelCase :str = self.model_tester.prepare_config_and_inputs_for_common()
_UpperCamelCase :Any = ['''basic''', '''bottleneck''']
for model_class in self.all_model_classes:
for layer_type in layers_type:
_UpperCamelCase :str = layer_type
_UpperCamelCase :Dict = True
check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_UpperCamelCase :Optional[int] = True
check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def _UpperCamelCase( self ) -> Tuple:
"""simple docstring"""
_UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ )
@slow
def _UpperCamelCase( self ) -> Dict:
"""simple docstring"""
for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase :Optional[int] = TFResNetModel.from_pretrained(SCREAMING_SNAKE_CASE_ )
self.assertIsNotNone(SCREAMING_SNAKE_CASE_ )
def A_ ( ) -> Tuple:
_UpperCamelCase :List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_tf
@require_vision
class A( unittest.TestCase ):
"""simple docstring"""
@cached_property
def _UpperCamelCase( self ) -> Union[str, Any]:
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def _UpperCamelCase( self ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase :Any = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
_UpperCamelCase :Optional[int] = self.default_image_processor
_UpperCamelCase :int = prepare_img()
_UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''tf''' )
# forward pass
_UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ )
# verify the logits
_UpperCamelCase :Optional[Any] = tf.TensorShape((1, 10_00) )
self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ )
_UpperCamelCase :Tuple = tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7] )
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
| 355
|
import inspect
import os
import re
from transformers.configuration_utils import PretrainedConfig
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_config_docstrings.py
lowercase_ = 'src/transformers'
# This is to make sure the transformers module imported is the one in the repo.
lowercase_ = direct_transformers_import(PATH_TO_TRANSFORMERS)
lowercase_ = transformers.models.auto.configuration_auto.CONFIG_MAPPING
lowercase_ = {
# used to compute the property `self.chunk_length`
'EncodecConfig': ['overlap'],
# used as `self.bert_model = BertModel(config, ...)`
'DPRConfig': True,
# not used in modeling files, but it's an important information
'FSMTConfig': ['langs'],
# used internally in the configuration class file
'GPTNeoConfig': ['attention_types'],
# used internally in the configuration class file
'EsmConfig': ['is_folding_model'],
# used during training (despite we don't have training script for these models yet)
'Mask2FormerConfig': ['ignore_value'],
# `ignore_value` used during training (despite we don't have training script for these models yet)
# `norm` used in conversion script (despite not using in the modeling file)
'OneFormerConfig': ['ignore_value', 'norm'],
# used during preprocessing and collation, see `collating_graphormer.py`
'GraphormerConfig': ['spatial_pos_max'],
# used internally in the configuration class file
'T5Config': ['feed_forward_proj'],
# used internally in the configuration class file
# `tokenizer_class` get default value `T5Tokenizer` intentionally
'MT5Config': ['feed_forward_proj', 'tokenizer_class'],
'UMT5Config': ['feed_forward_proj', 'tokenizer_class'],
# used internally in the configuration class file
'LongT5Config': ['feed_forward_proj'],
# used internally in the configuration class file
'SwitchTransformersConfig': ['feed_forward_proj'],
# having default values other than `1e-5` - we can't fix them without breaking
'BioGptConfig': ['layer_norm_eps'],
# having default values other than `1e-5` - we can't fix them without breaking
'GLPNConfig': ['layer_norm_eps'],
# having default values other than `1e-5` - we can't fix them without breaking
'SegformerConfig': ['layer_norm_eps'],
# having default values other than `1e-5` - we can't fix them without breaking
'CvtConfig': ['layer_norm_eps'],
# having default values other than `1e-5` - we can't fix them without breaking
'PerceiverConfig': ['layer_norm_eps'],
# used internally to calculate the feature size
'InformerConfig': ['num_static_real_features', 'num_time_features'],
# used internally to calculate the feature size
'TimeSeriesTransformerConfig': ['num_static_real_features', 'num_time_features'],
# used internally to calculate the feature size
'AutoformerConfig': ['num_static_real_features', 'num_time_features'],
# used internally to calculate `mlp_dim`
'SamVisionConfig': ['mlp_ratio'],
# For (head) training, but so far not implemented
'ClapAudioConfig': ['num_classes'],
# Not used, but providing useful information to users
'SpeechT5HifiGanConfig': ['sampling_rate'],
}
# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure
SPECIAL_CASES_TO_ALLOW.update(
{
'CLIPSegConfig': True,
'DeformableDetrConfig': True,
'DetaConfig': True,
'DinatConfig': True,
'DonutSwinConfig': True,
'EfficientFormerConfig': True,
'FSMTConfig': True,
'JukeboxConfig': True,
'LayoutLMv2Config': True,
'MaskFormerSwinConfig': True,
'MT5Config': True,
'NatConfig': True,
'OneFormerConfig': True,
'PerceiverConfig': True,
'RagConfig': True,
'SpeechT5Config': True,
'SwinConfig': True,
'Swin2SRConfig': True,
'Swinv2Config': True,
'SwitchTransformersConfig': True,
'TableTransformerConfig': True,
'TapasConfig': True,
'TransfoXLConfig': True,
'UniSpeechConfig': True,
'UniSpeechSatConfig': True,
'WavLMConfig': True,
'WhisperConfig': True,
# TODO: @Arthur (for `alignment_head` and `alignment_layer`)
'JukeboxPriorConfig': True,
# TODO: @Younes (for `is_decoder`)
'Pix2StructTextConfig': True,
}
)
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> str:
_a = False
for attribute in attributes:
for modeling_source in source_strings:
# check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)`
if (
f"""config.{attribute}""" in modeling_source
or f"""getattr(config, \"{attribute}\"""" in modeling_source
or f"""getattr(self.config, \"{attribute}\"""" in modeling_source
):
_a = True
# Deal with multi-line cases
elif (
re.search(
Rf"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""" , _UpperCAmelCase , )
is not None
):
_a = True
# `SequenceSummary` is called with `SequenceSummary(config)`
elif attribute in [
"summary_type",
"summary_use_proj",
"summary_activation",
"summary_last_dropout",
"summary_proj_to_labels",
"summary_first_dropout",
]:
if "SequenceSummary" in modeling_source:
_a = True
if attribute_used:
break
if attribute_used:
break
# common and important attributes, even if they do not always appear in the modeling files
_a = [
'bos_index',
'eos_index',
'pad_index',
'unk_index',
'mask_index',
'image_size',
'use_cache',
'out_features',
'out_indices',
]
_a = ['encoder_no_repeat_ngram_size']
# Special cases to be allowed
_a = True
if not attribute_used:
_a = False
for attribute in attributes:
# Allow if the default value in the configuration class is different from the one in `PretrainedConfig`
if attribute in ["is_encoder_decoder"] and default_value is True:
_a = True
elif attribute in ["tie_word_embeddings"] and default_value is False:
_a = True
# Allow cases without checking the default value in the configuration class
elif attribute in attributes_to_allow + attributes_used_in_generation:
_a = True
elif attribute.endswith('_token_id' ):
_a = True
# configuration class specific cases
if not case_allowed:
_a = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] )
_a = allowed_cases is True or attribute in allowed_cases
return attribute_used or case_allowed
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Dict:
_a = dict(inspect.signature(config_class.__init__ ).parameters )
_a = [x for x in list(signature.keys() ) if x not in ['self', 'kwargs']]
_a = [signature[param].default for param in parameter_names]
# If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long
# as one variant is used, the test should pass
_a = {}
if len(config_class.attribute_map ) > 0:
_a = {v: k for k, v in config_class.attribute_map.items()}
# Get the path to modeling source files
_a = inspect.getsourcefile(_UpperCAmelCase )
_a = os.path.dirname(_UpperCAmelCase )
# Let's check against all frameworks: as long as one framework uses an attribute, we are good.
_a = [os.path.join(_UpperCAmelCase , _UpperCAmelCase ) for fn in os.listdir(_UpperCAmelCase ) if fn.startswith('modeling_' )]
# Get the source code strings
_a = []
for path in modeling_paths:
if os.path.isfile(_UpperCAmelCase ):
with open(_UpperCAmelCase ) as fp:
modeling_sources.append(fp.read() )
_a = []
for config_param, default_value in zip(_UpperCAmelCase , _UpperCAmelCase ):
# `attributes` here is all the variant names for `config_param`
_a = [config_param]
# some configuration classes have non-empty `attribute_map`, and both names could be used in the
# corresponding modeling files. As long as one of them appears, it is fine.
if config_param in reversed_attribute_map:
attributes.append(reversed_attribute_map[config_param] )
if not check_attribute_being_used(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
unused_attributes.append(attributes[0] )
return sorted(_UpperCAmelCase )
def SCREAMING_SNAKE_CASE ( ) -> str:
_a = {}
for _config_class in list(CONFIG_MAPPING.values() ):
# Skip deprecated models
if "models.deprecated" in _config_class.__module__:
continue
# Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)
_a = [
cls
for name, cls in inspect.getmembers(
inspect.getmodule(_config_class ) , lambda _UpperCAmelCase : inspect.isclass(_UpperCAmelCase )
and issubclass(_UpperCAmelCase , _UpperCAmelCase )
and inspect.getmodule(_UpperCAmelCase ) == inspect.getmodule(_config_class ) , )
]
for config_class in config_classes_in_module:
_a = check_config_attributes_being_used(_UpperCAmelCase )
if len(_UpperCAmelCase ) > 0:
_a = unused_attributes
if len(_UpperCAmelCase ) > 0:
_a = 'The following configuration classes contain unused attributes in the corresponding modeling files:\n'
for name, attributes in configs_with_unused_attributes.items():
error += f"""{name}: {attributes}\n"""
raise ValueError(_UpperCAmelCase )
if __name__ == "__main__":
check_config_attributes()
| 562
| 0
|
"""simple docstring"""
import inspect
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel, VQModel
from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class _snake_case ( __snake_case ):
"""simple docstring"""
def __init__( self : Any , _A : VQModel , _A : UNetaDModel , _A : DDIMScheduler):
"""simple docstring"""
super().__init__()
self.register_modules(vqvae=_A , unet=_A , scheduler=_A)
@torch.no_grad()
def __call__( self : List[str] , _A : int = 1 , _A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _A : float = 0.0 , _A : int = 5_0 , _A : Optional[str] = "pil" , _A : bool = True , **_A : List[str] , ):
"""simple docstring"""
_SCREAMING_SNAKE_CASE : str = randn_tensor(
(batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=_A , )
_SCREAMING_SNAKE_CASE : int = latents.to(self.device)
# scale the initial noise by the standard deviation required by the scheduler
_SCREAMING_SNAKE_CASE : Optional[int] = latents * self.scheduler.init_noise_sigma
self.scheduler.set_timesteps(_A)
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
_SCREAMING_SNAKE_CASE : Dict = """eta""" in set(inspect.signature(self.scheduler.step).parameters.keys())
_SCREAMING_SNAKE_CASE : Optional[Any] = {}
if accepts_eta:
_SCREAMING_SNAKE_CASE : Union[str, Any] = eta
for t in self.progress_bar(self.scheduler.timesteps):
_SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler.scale_model_input(_A , _A)
# predict the noise residual
_SCREAMING_SNAKE_CASE : Optional[Any] = self.unet(_A , _A).sample
# compute the previous noisy sample x_t -> x_t-1
_SCREAMING_SNAKE_CASE : str = self.scheduler.step(_A , _A , _A , **_A).prev_sample
# decode the image latents with the VAE
_SCREAMING_SNAKE_CASE : Any = self.vqvae.decode(_A).sample
_SCREAMING_SNAKE_CASE : str = (image / 2 + 0.5).clamp(0 , 1)
_SCREAMING_SNAKE_CASE : List[Any] = image.cpu().permute(0 , 2 , 3 , 1).numpy()
if output_type == "pil":
_SCREAMING_SNAKE_CASE : str = self.numpy_to_pil(_A)
if not return_dict:
return (image,)
return ImagePipelineOutput(images=_A)
| 635
|
"""simple docstring"""
import argparse
import random
import joblib
import numpy as np
import torch
from igf.igf import (
SecondaryLearner,
collect_objective_set,
compute_perplexity,
generate_datasets,
load_gpta,
recopy_gpta,
set_seed,
train_secondary_learner,
)
from torch.utils.data import DataLoader, RandomSampler
from transformers import GPTaLMHeadModel
def lowerCamelCase_(__SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE=1_026 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="data/tokenized_stories_train_wikitext103.jbl" , __SCREAMING_SNAKE_CASE="igf_context_pairs.jbl" , )-> Union[str, Any]:
set_seed(3 )
# generate train_data and objective_set
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = generate_datasets(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , number=__SCREAMING_SNAKE_CASE , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE )
# keeps model same across runs
set_seed(4 )
# model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights
# can we train on GPU?
_SCREAMING_SNAKE_CASE : Dict = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" )
# load pretrained model
_SCREAMING_SNAKE_CASE : Any = load_gpta("""gpt2""" ).to(__SCREAMING_SNAKE_CASE )
print("""computing perplexity on objective set""" )
_SCREAMING_SNAKE_CASE : Union[str, Any] = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).item()
print("""perplexity on objective set:""" , __SCREAMING_SNAKE_CASE )
# collect igf pairs and save to file demo.jbl
collect_objective_set(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
# clean up, delete model and data we don't need anymore
del model, train_data, objective_set
torch.cuda.empty_cache()
def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=15 , __SCREAMING_SNAKE_CASE=128 , __SCREAMING_SNAKE_CASE=100 , __SCREAMING_SNAKE_CASE="igf_model.pt" , )-> Optional[int]:
set_seed(42 )
# Load pre-trained model
_SCREAMING_SNAKE_CASE : Any = GPTaLMHeadModel.from_pretrained("""gpt2""" )
# Initialize secondary learner to use embedding weights of model
_SCREAMING_SNAKE_CASE : Union[str, Any] = SecondaryLearner(__SCREAMING_SNAKE_CASE )
# Train secondary learner
_SCREAMING_SNAKE_CASE : Any = train_secondary_learner(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , max_epochs=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , eval_freq=100 , igf_model_path=__SCREAMING_SNAKE_CASE , )
del model, secondary_learner_train_data
torch.cuda.empty_cache()
return secondary_learner
def lowerCamelCase_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=1_000 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=1.0 , __SCREAMING_SNAKE_CASE=recopy_gpta , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=10 , __SCREAMING_SNAKE_CASE="gpt2_finetuned.pt" , )-> Union[str, Any]:
_SCREAMING_SNAKE_CASE : Tuple = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" )
_SCREAMING_SNAKE_CASE : Union[str, Any] = RandomSampler(__SCREAMING_SNAKE_CASE )
_SCREAMING_SNAKE_CASE : Tuple = DataLoader(__SCREAMING_SNAKE_CASE , sampler=__SCREAMING_SNAKE_CASE )
_SCREAMING_SNAKE_CASE : Tuple = max_steps // (len(__SCREAMING_SNAKE_CASE )) + 1
_SCREAMING_SNAKE_CASE : List[Any] = 0
_SCREAMING_SNAKE_CASE : Any = torch.zeros((1, context_len) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE )
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = recopy_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
model.train()
if secondary_learner is not None:
secondary_learner.to(__SCREAMING_SNAKE_CASE )
secondary_learner.eval()
_SCREAMING_SNAKE_CASE : Dict = []
_SCREAMING_SNAKE_CASE : Optional[int] = 0
_SCREAMING_SNAKE_CASE : Optional[Any] = []
_SCREAMING_SNAKE_CASE : int = []
# Compute the performance of the transformer model at the beginning
_SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
test_perps.append(__SCREAMING_SNAKE_CASE )
print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE )
for epoch in range(int(__SCREAMING_SNAKE_CASE ) ):
for step, example in enumerate(__SCREAMING_SNAKE_CASE ):
torch.cuda.empty_cache()
_SCREAMING_SNAKE_CASE : Any = random.randint(0 , example.size(2 ) - context_len - 1 )
_SCREAMING_SNAKE_CASE : int = example[0, 0, start : start + context_len]
lm_optimizer.zero_grad()
_SCREAMING_SNAKE_CASE : Union[str, Any] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE )
_SCREAMING_SNAKE_CASE : List[str] = True
if secondary_learner is not None:
_SCREAMING_SNAKE_CASE : List[Any] = secondary_learner.forward(
torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) )[0].item()
observed_qs.append(float(__SCREAMING_SNAKE_CASE ) )
# Here we implement the simple non-constant threshold for the predicted IG(X) value
# We will decay the selectivity of our secondary learner filter from
# 1 standard deviation above average to 1 below average after 10 batches.
if global_step == 10:
_SCREAMING_SNAKE_CASE : Dict = -1
if predicted_q < threshold:
_SCREAMING_SNAKE_CASE : List[str] = False
# If we passed the filter, add the context to the batch!
if do_backprop:
contexts.append(np.array(context.cpu() ) )
_SCREAMING_SNAKE_CASE : Union[str, Any] = outputs[0]
lm_loss.backward()
examples += 1
del outputs
# Once the batch is filled with enough contexts, backprop on the batch.
if examples == batch_size:
torch.cuda.empty_cache()
_SCREAMING_SNAKE_CASE : Any = 0
# Do LM backprop
torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 )
lm_optimizer.step()
lm_scheduler.step() # Update learning rate schedule
global_step += 1
# Compute the performance of the transformer model at this batch
if global_step % eval_interval == 0:
_SCREAMING_SNAKE_CASE : Tuple = compute_perplexity(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
test_perps.append(__SCREAMING_SNAKE_CASE )
print("""Test perplexity, step""" , __SCREAMING_SNAKE_CASE , """:""" , __SCREAMING_SNAKE_CASE )
# Break out of the loop after 60 batches
if max_steps > 0 and global_step > 60:
break
if max_steps > 0 and global_step > 60:
break
# save finetuned transformer model
torch.save(model.state_dict() , __SCREAMING_SNAKE_CASE )
torch.cuda.empty_cache()
# Do some cleaning up so we can reinitialize for the next run of this function
del lm_optimizer
del lm_scheduler
return model
def lowerCamelCase_()-> Tuple:
_SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser(description="""Fine-tune a transformer model with IGF on a language modeling task""" )
# Required parameters
parser.add_argument(
"""--data_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The input data dir. Should contain data files for WikiText.""" , )
parser.add_argument(
"""--model_name_or_path""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""Path to pretrained model or model identifier from huggingface.co/models""" , )
parser.add_argument(
"""--data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help=(
"""A jbl file containing tokenized data which can be split as objective dataset, """
"""train_dataset and test_dataset."""
) , )
parser.add_argument(
"""--igf_data_file""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A jbl file containing the context and information gain pairs to train secondary learner.""" , )
parser.add_argument(
"""--output_dir""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , required=__SCREAMING_SNAKE_CASE , help="""The output directory where the final fine-tuned model is stored.""" , )
parser.add_argument(
"""--tokenizer_name""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Pretrained tokenizer name or path if not the same as model_name""" , )
parser.add_argument("""--seed""" , type=__SCREAMING_SNAKE_CASE , default=__SCREAMING_SNAKE_CASE , help="""A seed for reproducible training.""" )
parser.add_argument(
"""--context_len""" , default=32 , type=__SCREAMING_SNAKE_CASE , help=(
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
) , )
parser.add_argument(
"""--size_objective_set""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""number of articles that are long enough to be used as our objective set""" , )
parser.add_argument(
"""--eval_freq""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""secondary model evaluation is triggered at eval_freq""" )
parser.add_argument("""--max_steps""" , default=1_000 , type=__SCREAMING_SNAKE_CASE , help="""To calculate training epochs""" )
parser.add_argument(
"""--secondary_learner_batch_size""" , default=128 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data for secondary learner""" , )
parser.add_argument(
"""--batch_size""" , default=16 , type=__SCREAMING_SNAKE_CASE , help="""batch size of training data of language model(gpt2) """ )
parser.add_argument(
"""--eval_interval""" , default=10 , type=__SCREAMING_SNAKE_CASE , help=(
"""decay the selectivity of our secondary learner filter from"""
"""1 standard deviation above average to 1 below average after 10 batches"""
) , )
parser.add_argument(
"""--number""" , default=100 , type=__SCREAMING_SNAKE_CASE , help="""The number of examples split to be used as objective_set/test_data""" )
parser.add_argument(
"""--min_len""" , default=1_026 , type=__SCREAMING_SNAKE_CASE , help="""The minimum length of the article to be used as objective set""" )
parser.add_argument(
"""--secondary_learner_max_epochs""" , default=15 , type=__SCREAMING_SNAKE_CASE , help="""number of epochs to train secondary learner""" )
parser.add_argument("""--trim""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""truncate the example if it exceeds context length""" )
parser.add_argument(
"""--threshold""" , default=1.0 , type=__SCREAMING_SNAKE_CASE , help=(
"""The threshold value used by secondary learner to filter the train_data and allow only"""
""" informative data as input to the model"""
) , )
parser.add_argument("""--finetuned_model_name""" , default="""gpt2_finetuned.pt""" , type=__SCREAMING_SNAKE_CASE , help="""finetuned_model_name""" )
parser.add_argument(
"""--recopy_model""" , default=__SCREAMING_SNAKE_CASE , type=__SCREAMING_SNAKE_CASE , help="""Reset the model to the original pretrained GPT-2 weights after each iteration""" , )
# function calls
# Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner
generate_n_pairs(
context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE , data_file="""data/tokenized_stories_train_wikitext103.jbl""" , igf_data_file="""igf_context_pairs.jbl""" , )
# Load train data for secondary learner
_SCREAMING_SNAKE_CASE : Optional[int] = joblib.load("""data/IGF_values.jbl""" )
# Train secondary learner
_SCREAMING_SNAKE_CASE : int = training_secondary_learner(
__SCREAMING_SNAKE_CASE , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="""igf_model.pt""" , )
# load pretrained gpt2 model
_SCREAMING_SNAKE_CASE : List[Any] = GPTaLMHeadModel.from_pretrained("""gpt2""" )
set_seed(42 )
# Generate train and test data to train and evaluate gpt2 model
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[Any] = generate_datasets(
context_len=32 , file="""data/tokenized_stories_train_wikitext103.jbl""" , number=100 , min_len=1_026 , trim=__SCREAMING_SNAKE_CASE )
# fine-tuning of the gpt2 model using igf (Information Gain Filtration)
finetune(
__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , context_len=32 , max_steps=1_000 , batch_size=16 , threshold=1.0 , recopy_model=__SCREAMING_SNAKE_CASE , secondary_learner=__SCREAMING_SNAKE_CASE , eval_interval=10 , finetuned_model_name="""gpt2_finetuned.pt""" , )
if __name__ == "__main__":
main()
| 635
| 1
|
import argparse
from pathlib import Path
from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = None , lowerCamelCase_ = None , ) -> int:
if config_name_or_path is None:
_lowercase : int = 'facebook/rag-token-base' if model_type == 'rag_token' else 'facebook/rag-sequence-base'
if generator_tokenizer_name_or_path is None:
_lowercase : int = generator_name_or_path
if question_encoder_tokenizer_name_or_path is None:
_lowercase : str = question_encoder_name_or_path
_lowercase : Dict = RagTokenForGeneration if model_type == 'rag_token' else RagSequenceForGeneration
# Save model.
_lowercase : Dict = RagConfig.from_pretrained(lowerCamelCase_ )
_lowercase : Dict = AutoConfig.from_pretrained(lowerCamelCase_ )
_lowercase : Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase_ )
_lowercase : Any = gen_config
_lowercase : Dict = question_encoder_config
_lowercase : List[Any] = model_class.from_pretrained_question_encoder_generator(
lowerCamelCase_ , lowerCamelCase_ , config=lowerCamelCase_ )
rag_model.save_pretrained(lowerCamelCase_ )
# Sanity check.
model_class.from_pretrained(lowerCamelCase_ )
# Save tokenizers.
_lowercase : int = AutoTokenizer.from_pretrained(lowerCamelCase_ )
gen_tokenizer.save_pretrained(dest_dir / 'generator_tokenizer/' )
_lowercase : Optional[Any] = AutoTokenizer.from_pretrained(lowerCamelCase_ )
question_encoder_tokenizer.save_pretrained(dest_dir / 'question_encoder_tokenizer/' )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : List[Any] = argparse.ArgumentParser()
parser.add_argument(
"--model_type",
choices=["rag_sequence", "rag_token"],
required=True,
type=str,
help="RAG model type: rag_sequence, rag_token",
)
parser.add_argument("--dest", type=str, required=True, help="Path to the output checkpoint directory.")
parser.add_argument("--generator_name_or_path", type=str, required=True, help="Generator model identifier")
parser.add_argument(
"--question_encoder_name_or_path", type=str, required=True, help="Question encoder model identifier"
)
parser.add_argument(
"--generator_tokenizer_name_or_path",
type=str,
help="Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``",
)
parser.add_argument(
"--question_encoder_tokenizer_name_or_path",
type=str,
help="Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``",
)
parser.add_argument(
"--config_name_or_path",
type=str,
help=(
"Identifier of the model config to use, if not provided, resolves to a base config for a given"
" ``model_type``"
),
)
SCREAMING_SNAKE_CASE : Dict = parser.parse_args()
SCREAMING_SNAKE_CASE : Dict = Path(args.dest)
dest_dir.mkdir(exist_ok=True)
consolidate(
args.model_type,
args.generator_name_or_path,
args.question_encoder_name_or_path,
dest_dir,
args.config_name_or_path,
args.generator_tokenizer_name_or_path,
args.question_encoder_tokenizer_name_or_path,
)
| 89
|
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 lowerCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , snake_case_ , snake_case_=7 , snake_case_=3 , snake_case_=1_8 , snake_case_=3_0 , snake_case_=4_0_0 , snake_case_=True , snake_case_=None , snake_case_=True , snake_case_=False , snake_case_=True , snake_case_=True , snake_case_=[0.5, 0.5, 0.5] , snake_case_=[0.5, 0.5, 0.5] , ) -> Optional[Any]:
'''simple docstring'''
__lowercase = parent
__lowercase = batch_size
__lowercase = num_channels
__lowercase = image_size
__lowercase = min_resolution
__lowercase = max_resolution
__lowercase = do_resize
__lowercase = size if size is not None else {'''height''': 1_8, '''width''': 2_0}
__lowercase = do_thumbnail
__lowercase = do_align_axis
__lowercase = do_pad
__lowercase = do_normalize
__lowercase = image_mean
__lowercase = image_std
def A ( self ) -> Dict:
'''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 lowerCamelCase_ ( lowerCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
__UpperCAmelCase = DonutImageProcessor if is_vision_available() else None
def A ( self ) -> Optional[Any]:
'''simple docstring'''
__lowercase = DonutImageProcessingTester(self )
@property
def A ( self ) -> str:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def A ( self ) -> Optional[int]:
'''simple docstring'''
__lowercase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(snake_case_ , '''do_resize''' ) )
self.assertTrue(hasattr(snake_case_ , '''size''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_thumbnail''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_align_long_axis''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_pad''' ) )
self.assertTrue(hasattr(snake_case_ , '''do_normalize''' ) )
self.assertTrue(hasattr(snake_case_ , '''image_mean''' ) )
self.assertTrue(hasattr(snake_case_ , '''image_std''' ) )
def A ( self ) -> List[str]:
'''simple docstring'''
__lowercase = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''height''': 1_8, '''width''': 2_0} )
__lowercase = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 )
self.assertEqual(image_processor.size , {'''height''': 4_2, '''width''': 4_2} )
# Previous config had dimensions in (width, height) order
__lowercase = self.image_processing_class.from_dict(self.image_processor_dict , size=(4_2, 8_4) )
self.assertEqual(image_processor.size , {'''height''': 8_4, '''width''': 4_2} )
def A ( self ) -> Optional[Any]:
'''simple docstring'''
pass
@is_flaky()
def A ( self ) -> Optional[Any]:
'''simple docstring'''
__lowercase = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__lowercase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ )
for image in image_inputs:
self.assertIsInstance(snake_case_ , Image.Image )
# Test not batched input
__lowercase = 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
__lowercase = image_processing(snake_case_ , 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 A ( self ) -> Dict:
'''simple docstring'''
__lowercase = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__lowercase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , numpify=snake_case_ )
for image in image_inputs:
self.assertIsInstance(snake_case_ , np.ndarray )
# Test not batched input
__lowercase = 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
__lowercase = image_processing(snake_case_ , 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 A ( self ) -> Dict:
'''simple docstring'''
__lowercase = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__lowercase = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case_ , torchify=snake_case_ )
for image in image_inputs:
self.assertIsInstance(snake_case_ , torch.Tensor )
# Test not batched input
__lowercase = 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
__lowercase = image_processing(snake_case_ , 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'''],
) , )
| 639
| 0
|
import copy
import inspect
import unittest
from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
if is_torch_available():
import torch
from transformers import TimmBackbone, TimmBackboneConfig
from ...test_pipeline_mixin import PipelineTesterMixin
class snake_case_ :
def __init__( self , __lowercase , __lowercase=None , __lowercase=None , __lowercase=None , __lowercase="resnet50" , __lowercase=3 , __lowercase=3_2 , __lowercase=3 , __lowercase=True , __lowercase=True , ) -> Dict:
lowerCamelCase : int =parent
lowerCamelCase : Union[str, Any] =out_indices if out_indices is not None else [4]
lowerCamelCase : Any =stage_names
lowerCamelCase : Any =out_features
lowerCamelCase : Dict =backbone
lowerCamelCase : Union[str, Any] =batch_size
lowerCamelCase : List[Any] =image_size
lowerCamelCase : Dict =num_channels
lowerCamelCase : Tuple =use_pretrained_backbone
lowerCamelCase : Dict =is_training
def __lowercase ( self ) -> Union[str, Any]:
lowerCamelCase : List[Any] =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowerCamelCase : int =self.get_config()
return config, pixel_values
def __lowercase ( self ) -> str:
return TimmBackboneConfig(
image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , )
def __lowercase ( self , __lowercase , __lowercase ) -> List[Any]:
lowerCamelCase : List[str] =TimmBackbone(config=__lowercase )
model.to(__lowercase )
model.eval()
with torch.no_grad():
lowerCamelCase : List[str] =model(__lowercase )
self.parent.assertEqual(
result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , )
def __lowercase ( self ) -> List[Any]:
lowerCamelCase : str =self.prepare_config_and_inputs()
lowerCamelCase , lowerCamelCase : Any =config_and_inputs
lowerCamelCase : str ={'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
@require_timm
class snake_case_ ( _A , _A , _A , unittest.TestCase):
lowerCamelCase :List[Any] = (TimmBackbone,) if is_torch_available() else ()
lowerCamelCase :Optional[int] = {"feature-extraction": TimmBackbone} if is_torch_available() else {}
lowerCamelCase :Tuple = False
lowerCamelCase :List[Any] = False
lowerCamelCase :int = False
lowerCamelCase :str = False
def __lowercase ( self ) -> List[Any]:
lowerCamelCase : Union[str, Any] =TimmBackboneModelTester(self )
lowerCamelCase : List[Any] =ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase )
def __lowercase ( self ) -> Union[str, Any]:
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def __lowercase ( self ) -> List[Any]:
lowerCamelCase : Dict ='''resnet18'''
lowerCamelCase : Tuple ='''microsoft/resnet-18'''
lowerCamelCase : Any =AutoBackbone.from_pretrained(__lowercase , use_timm_backbone=__lowercase )
lowerCamelCase : Tuple =AutoBackbone.from_pretrained(__lowercase )
self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) )
self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) )
self.assertEqual(timm_model.channels , transformers_model.channels )
# Out indices are set to the last layer by default. For timm models, we don't know
# the number of layers in advance, so we set it to (-1,), whereas for transformers
# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
self.assertEqual(timm_model.out_indices , (-1,) )
self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] )
lowerCamelCase : List[Any] =AutoBackbone.from_pretrained(__lowercase , use_timm_backbone=__lowercase , out_indices=[1, 2, 3] )
lowerCamelCase : List[Any] =AutoBackbone.from_pretrained(__lowercase , out_indices=[1, 2, 3] )
self.assertEqual(timm_model.out_indices , transformers_model.out_indices )
self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) )
self.assertEqual(timm_model.channels , transformers_model.channels )
@unittest.skip('''TimmBackbone doesn\'t support feed forward chunking''' )
def __lowercase ( self ) -> Union[str, Any]:
pass
@unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute''' )
def __lowercase ( self ) -> List[str]:
pass
@unittest.skip('''TimmBackbone initialization is managed on the timm side''' )
def __lowercase ( self ) -> Optional[Any]:
pass
@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''' )
def __lowercase ( self ) -> str:
pass
@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''' )
def __lowercase ( self ) -> Dict:
pass
@unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint''' )
def __lowercase ( self ) -> Optional[int]:
pass
@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' )
def __lowercase ( self ) -> Any:
pass
@unittest.skip('''model weights aren\'t tied in TimmBackbone.''' )
def __lowercase ( self ) -> Optional[int]:
pass
@unittest.skip('''model weights aren\'t tied in TimmBackbone.''' )
def __lowercase ( self ) -> List[Any]:
pass
@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' )
def __lowercase ( self ) -> Optional[int]:
pass
@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''' )
def __lowercase ( self ) -> Optional[int]:
pass
@unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.''' )
def __lowercase ( self ) -> Dict:
pass
@unittest.skip('''TimmBackbone doesn\'t support output_attentions.''' )
def __lowercase ( self ) -> int:
pass
@unittest.skip('''Safetensors is not supported by timm.''' )
def __lowercase ( self ) -> int:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __lowercase ( self ) -> Union[str, Any]:
pass
def __lowercase ( self ) -> Optional[int]:
lowerCamelCase , lowerCamelCase : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase : Union[str, Any] =model_class(__lowercase )
lowerCamelCase : str =inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowerCamelCase : Tuple =[*signature.parameters.keys()]
lowerCamelCase : Optional[int] =['''pixel_values''']
self.assertListEqual(arg_names[:1] , __lowercase )
def __lowercase ( self ) -> Tuple:
lowerCamelCase , lowerCamelCase : int =self.model_tester.prepare_config_and_inputs_for_common()
lowerCamelCase : List[str] =True
lowerCamelCase : Optional[Any] =self.has_attentions
# no need to test all models as different heads yield the same functionality
lowerCamelCase : List[Any] =self.all_model_classes[0]
lowerCamelCase : Tuple =model_class(__lowercase )
model.to(__lowercase )
lowerCamelCase : List[Any] =self._prepare_for_class(__lowercase , __lowercase )
lowerCamelCase : Tuple =model(**__lowercase )
lowerCamelCase : List[Any] =outputs[0][-1]
# Encoder-/Decoder-only models
lowerCamelCase : List[str] =outputs.hidden_states[0]
hidden_states.retain_grad()
if self.has_attentions:
lowerCamelCase : str =outputs.attentions[0]
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=__lowercase )
self.assertIsNotNone(hidden_states.grad )
if self.has_attentions:
self.assertIsNotNone(attentions.grad )
def __lowercase ( self ) -> Union[str, Any]:
lowerCamelCase , lowerCamelCase : Any =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowerCamelCase : List[str] =model_class(__lowercase )
model.to(__lowercase )
model.eval()
lowerCamelCase : List[str] =model(**__lowercase )
self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) )
self.assertEqual(len(model.channels ) , len(config.out_indices ) )
# Check output of last stage is taken if out_features=None, out_indices=None
lowerCamelCase : Union[str, Any] =copy.deepcopy(__lowercase )
lowerCamelCase : int =None
lowerCamelCase : int =model_class(__lowercase )
model.to(__lowercase )
model.eval()
lowerCamelCase : Any =model(**__lowercase )
self.assertEqual(len(result.feature_maps ) , 1 )
self.assertEqual(len(model.channels ) , 1 )
# Check backbone can be initialized with fresh weights
lowerCamelCase : str =copy.deepcopy(__lowercase )
lowerCamelCase : Union[str, Any] =False
lowerCamelCase : List[str] =model_class(__lowercase )
model.to(__lowercase )
model.eval()
lowerCamelCase : Optional[Any] =model(**__lowercase )
| 262
|
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
def A__ ( SCREAMING_SNAKE_CASE_ ) -> tuple:
return (data["data"], data["target"])
def A__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> np.ndarray:
lowerCamelCase : Dict =XGBRegressor(verbosity=0 , random_state=4_2 )
xgb.fit(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Predict target for test data
lowerCamelCase : List[str] =xgb.predict(SCREAMING_SNAKE_CASE_ )
lowerCamelCase : List[Any] =predictions.reshape(len(SCREAMING_SNAKE_CASE_ ) , 1 )
return predictions
def A__ ( ) -> None:
lowerCamelCase : Union[str, Any] =fetch_california_housing()
lowerCamelCase , lowerCamelCase : Optional[Any] =data_handling(SCREAMING_SNAKE_CASE_ )
lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase : str =train_test_split(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , test_size=0.2_5 , random_state=1 )
lowerCamelCase : str =xgboost(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Error printing
print(F"Mean Absolute Error : {mean_absolute_error(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}" )
print(F"Mean Square Error : {mean_squared_error(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}" )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
main()
| 262
| 1
|
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class lowerCamelCase ( unittest.TestCase ):
UpperCamelCase_ : Optional[Any] = inspect.getfile(accelerate.test_utils )
UpperCamelCase_ : Tuple = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
UpperCamelCase_ : List[str] = ['accelerate', 'launch']
UpperCamelCase_ : Optional[Any] = Path.home() / '.cache/huggingface/accelerate'
UpperCamelCase_ : int = 'default_config.yaml'
UpperCamelCase_ : Any = config_folder / config_file
UpperCamelCase_ : str = config_folder / '_default_config.yaml'
UpperCamelCase_ : Tuple = Path('tests/test_configs' )
@classmethod
def snake_case__ ( cls :Optional[Any] ) -> List[Any]:
"""simple docstring"""
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path )
@classmethod
def snake_case__ ( cls :Optional[int] ) -> int:
"""simple docstring"""
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path )
def snake_case__ ( self :Optional[Any] ) -> Tuple:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() )
def snake_case__ ( self :Dict ) -> Dict:
"""simple docstring"""
for config in sorted(self.test_config_path.glob('''**/*.yaml''' ) ):
with self.subTest(config_file=lowercase ):
execute_subprocess_async(
self.base_cmd + ['''--config_file''', str(lowercase ), self.test_file_path] , env=os.environ.copy() )
def snake_case__ ( self :Any ) -> Tuple:
"""simple docstring"""
execute_subprocess_async(['''accelerate''', '''test'''] , env=os.environ.copy() )
class lowerCamelCase ( unittest.TestCase ):
UpperCamelCase_ : Optional[Any] = 'test-tpu'
UpperCamelCase_ : List[str] = 'us-central1-a'
UpperCamelCase_ : List[str] = 'ls'
UpperCamelCase_ : Optional[Any] = ['accelerate', 'tpu-config']
UpperCamelCase_ : Optional[Any] = 'cd /usr/share'
UpperCamelCase_ : Tuple = 'tests/test_samples/test_command_file.sh'
UpperCamelCase_ : Optional[int] = 'Running gcloud compute tpus tpu-vm ssh'
def snake_case__ ( self :str ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd
+ ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug'''] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , lowercase , )
def snake_case__ ( self :Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/0_12_0.yaml''',
'''--command''',
self.command,
'''--tpu_zone''',
self.tpu_zone,
'''--tpu_name''',
self.tpu_name,
'''--debug''',
] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , lowercase , )
def snake_case__ ( self :Tuple ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug'''] , return_stdout=lowercase )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , lowercase , )
def snake_case__ ( self :Tuple ) -> Optional[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug'''] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , lowercase , )
def snake_case__ ( self :Any ) -> Dict:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/latest.yaml''',
'''--command''',
self.command,
'''--command''',
'''echo "Hello World"''',
'''--debug''',
] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , lowercase , )
def snake_case__ ( self :Tuple ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd
+ ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug'''] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , lowercase , )
def snake_case__ ( self :List[str] ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/0_12_0.yaml''',
'''--command_file''',
self.command_file,
'''--tpu_zone''',
self.tpu_zone,
'''--tpu_name''',
self.tpu_name,
'''--debug''',
] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , lowercase , )
def snake_case__ ( self :Optional[int] ) -> Dict:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug'''] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , lowercase , )
def snake_case__ ( self :Optional[int] ) -> List[Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = run_command(
self.cmd
+ [
'''--config_file''',
'''tests/test_configs/latest.yaml''',
'''--install_accelerate''',
'''--accelerate_version''',
'''12.0.0''',
'''--debug''',
] , return_stdout=lowercase , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , lowercase , )
| 201
|
import unittest
from transformers import SqueezeBertConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
SqueezeBertForMaskedLM,
SqueezeBertForMultipleChoice,
SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification,
SqueezeBertForTokenClassification,
SqueezeBertModel,
)
class lowerCamelCase ( __lowerCamelCase ):
def __init__( self :int , lowercase :Optional[Any] , lowercase :Optional[int]=1_3 , lowercase :Any=7 , lowercase :Tuple=True , lowercase :Optional[int]=True , lowercase :Any=False , lowercase :Any=True , lowercase :Dict=9_9 , lowercase :Dict=3_2 , lowercase :Any=5 , lowercase :Optional[Any]=4 , lowercase :List[str]=6_4 , lowercase :Optional[int]="gelu" , lowercase :int=0.1 , lowercase :str=0.1 , lowercase :List[str]=5_1_2 , lowercase :int=1_6 , lowercase :Any=2 , lowercase :Union[str, Any]=0.02 , lowercase :Optional[int]=3 , lowercase :Optional[Any]=4 , lowercase :Tuple=None , lowercase :int=2 , lowercase :Tuple=2 , lowercase :List[Any]=2 , lowercase :Optional[int]=2 , lowercase :Tuple=4 , lowercase :int=1 , ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = batch_size
SCREAMING_SNAKE_CASE = seq_length
SCREAMING_SNAKE_CASE = is_training
SCREAMING_SNAKE_CASE = use_input_mask
SCREAMING_SNAKE_CASE = use_token_type_ids
SCREAMING_SNAKE_CASE = use_labels
SCREAMING_SNAKE_CASE = 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 = type_sequence_label_size
SCREAMING_SNAKE_CASE = initializer_range
SCREAMING_SNAKE_CASE = num_labels
SCREAMING_SNAKE_CASE = num_choices
SCREAMING_SNAKE_CASE = scope
SCREAMING_SNAKE_CASE = q_groups
SCREAMING_SNAKE_CASE = k_groups
SCREAMING_SNAKE_CASE = v_groups
SCREAMING_SNAKE_CASE = post_attention_groups
SCREAMING_SNAKE_CASE = intermediate_groups
SCREAMING_SNAKE_CASE = output_groups
def snake_case__ ( self :str ) -> Dict:
"""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
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 = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def snake_case__ ( self :str ) -> Dict:
"""simple docstring"""
return SqueezeBertConfig(
embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , )
def snake_case__ ( self :Optional[Any] , lowercase :Optional[Any] , lowercase :int , lowercase :Any , lowercase :List[str] , lowercase :Optional[Any] , lowercase :List[str] ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE = SqueezeBertModel(config=lowercase )
model.to(lowercase )
model.eval()
SCREAMING_SNAKE_CASE = model(lowercase , lowercase )
SCREAMING_SNAKE_CASE = model(lowercase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def snake_case__ ( self :Dict , lowercase :Dict , lowercase :List[Any] , lowercase :str , lowercase :Union[str, Any] , lowercase :Dict , lowercase :List[Any] ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE = SqueezeBertForMaskedLM(config=lowercase )
model.to(lowercase )
model.eval()
SCREAMING_SNAKE_CASE = model(lowercase , attention_mask=lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def snake_case__ ( self :List[str] , lowercase :Optional[Any] , lowercase :Optional[int] , lowercase :str , lowercase :int , lowercase :Optional[Any] , lowercase :int ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = SqueezeBertForQuestionAnswering(config=lowercase )
model.to(lowercase )
model.eval()
SCREAMING_SNAKE_CASE = model(
lowercase , attention_mask=lowercase , start_positions=lowercase , end_positions=lowercase )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def snake_case__ ( self :Any , lowercase :Optional[Any] , lowercase :List[str] , lowercase :int , lowercase :Any , lowercase :Optional[int] , lowercase :List[str] ) -> Any:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.num_labels
SCREAMING_SNAKE_CASE = SqueezeBertForSequenceClassification(lowercase )
model.to(lowercase )
model.eval()
SCREAMING_SNAKE_CASE = model(lowercase , attention_mask=lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def snake_case__ ( self :str , lowercase :List[Any] , lowercase :List[str] , lowercase :Optional[int] , lowercase :Tuple , lowercase :Tuple , lowercase :str ) -> str:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.num_labels
SCREAMING_SNAKE_CASE = SqueezeBertForTokenClassification(config=lowercase )
model.to(lowercase )
model.eval()
SCREAMING_SNAKE_CASE = model(lowercase , attention_mask=lowercase , labels=lowercase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def snake_case__ ( self :int , lowercase :List[str] , lowercase :List[Any] , lowercase :Tuple , lowercase :str , lowercase :Optional[Any] , lowercase :Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.num_choices
SCREAMING_SNAKE_CASE = SqueezeBertForMultipleChoice(config=lowercase )
model.to(lowercase )
model.eval()
SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
SCREAMING_SNAKE_CASE = model(
lowercase , attention_mask=lowercase , labels=lowercase , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def snake_case__ ( self :List[str] ) -> Union[str, 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)) = config_and_inputs
SCREAMING_SNAKE_CASE = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ):
UpperCamelCase_ : int = (
(
SqueezeBertModel,
SqueezeBertForMaskedLM,
SqueezeBertForMultipleChoice,
SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification,
SqueezeBertForTokenClassification,
)
if is_torch_available()
else None
)
UpperCamelCase_ : int = (
{
'feature-extraction': SqueezeBertModel,
'fill-mask': SqueezeBertForMaskedLM,
'question-answering': SqueezeBertForQuestionAnswering,
'text-classification': SqueezeBertForSequenceClassification,
'token-classification': SqueezeBertForTokenClassification,
'zero-shot': SqueezeBertForSequenceClassification,
}
if is_torch_available()
else {}
)
UpperCamelCase_ : Tuple = False
UpperCamelCase_ : int = True
UpperCamelCase_ : List[Any] = False
def snake_case__ ( self :Tuple ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE = SqueezeBertModelTester(self )
SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowercase , dim=3_7 )
def snake_case__ ( self :Optional[Any] ) -> Optional[int]:
"""simple docstring"""
self.config_tester.run_common_tests()
def snake_case__ ( self :Union[str, Any] ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_model(*lowercase )
def snake_case__ ( self :Any ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_masked_lm(*lowercase )
def snake_case__ ( self :List[str] ) -> List[str]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_question_answering(*lowercase )
def snake_case__ ( self :Any ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_sequence_classification(*lowercase )
def snake_case__ ( self :Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_token_classification(*lowercase )
def snake_case__ ( self :Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_squeezebert_for_multiple_choice(*lowercase )
@slow
def snake_case__ ( self :Dict ) -> str:
"""simple docstring"""
for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE = SqueezeBertModel.from_pretrained(lowercase )
self.assertIsNotNone(lowercase )
@require_sentencepiece
@require_tokenizers
@require_torch
class lowerCamelCase ( unittest.TestCase ):
@slow
def snake_case__ ( self :Any ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE = SqueezeBertForSequenceClassification.from_pretrained('''squeezebert/squeezebert-mnli''' )
SCREAMING_SNAKE_CASE = torch.tensor([[1, 2_9_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 1_3, 1_5_8_8, 2]] )
SCREAMING_SNAKE_CASE = model(lowercase )[0]
SCREAMING_SNAKE_CASE = torch.Size((1, 3) )
self.assertEqual(output.shape , lowercase )
SCREAMING_SNAKE_CASE = torch.tensor([[0.64_01, -0.03_49, -0.60_41]] )
self.assertTrue(torch.allclose(lowercase , lowercase , atol=1e-4 ) )
| 201
| 1
|
'''simple docstring'''
from math import sqrt
import numpy as np
from sympy import symbols
# Coefficient
# Speed of light (m/s)
lowercase__ = 299_792_458
# Symbols
lowercase__ , lowercase__ , lowercase__ , lowercase__ = symbols("ct x y z")
def __UpperCamelCase ( __lowerCamelCase : float ) -> float:
'''simple docstring'''
if velocity > c:
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!" )
elif velocity < 1:
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError("Speed must be greater than or equal to 1!" )
return velocity / c
def __UpperCamelCase ( __lowerCamelCase : float ) -> float:
'''simple docstring'''
return 1 / sqrt(1 - beta(__lowerCamelCase ) ** 2 )
def __UpperCamelCase ( __lowerCamelCase : float ) -> np.ndarray:
'''simple docstring'''
return np.array(
[
[gamma(__lowerCamelCase ), -gamma(__lowerCamelCase ) * beta(__lowerCamelCase ), 0, 0],
[-gamma(__lowerCamelCase ) * beta(__lowerCamelCase ), gamma(__lowerCamelCase ), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
] )
def __UpperCamelCase ( __lowerCamelCase : float , __lowerCamelCase : np.ndarray | None = None ) -> np.ndarray:
'''simple docstring'''
if event is None:
_a = np.array([ct, x, y, z] ) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)
return transformation_matrix(__lowerCamelCase ) @ event
if __name__ == "__main__":
import doctest
doctest.testmod()
# Example of symbolic vector:
lowercase__ = transform(29_979_245)
print("Example of four vector: ")
print(f'''ct\' = {four_vector[0]}''')
print(f'''x\' = {four_vector[1]}''')
print(f'''y\' = {four_vector[2]}''')
print(f'''z\' = {four_vector[3]}''')
# Substitute symbols with numerical values
lowercase__ = {ct: c, x: 1, y: 1, z: 1}
lowercase__ = [four_vector[i].subs(sub_dict) for i in range(4)]
print(f'''\n{numerical_vector}''')
| 276
|
'''simple docstring'''
import argparse
import os
import pickle
import sys
import torch
from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
lowercase__ = data_utils.TransfoXLTokenizer
lowercase__ = data_utils.TransfoXLCorpus
lowercase__ = data_utils
lowercase__ = data_utils
def __UpperCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple ) -> Dict:
'''simple docstring'''
if transfo_xl_dataset_file:
# Convert a pre-processed corpus (see original TensorFlow repo)
with open(__lowerCamelCase , "rb" ) as fp:
_a = pickle.load(__lowerCamelCase , encoding="latin1" )
# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
_a = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"]
print(F"Save vocabulary to {pytorch_vocab_dump_path}" )
_a = corpus.vocab.__dict__
torch.save(__lowerCamelCase , __lowerCamelCase )
_a = corpus.__dict__
corpus_dict_no_vocab.pop("vocab" , __lowerCamelCase )
_a = pytorch_dump_folder_path + "/" + CORPUS_NAME
print(F"Save dataset to {pytorch_dataset_dump_path}" )
torch.save(__lowerCamelCase , __lowerCamelCase )
if tf_checkpoint_path:
# Convert a pre-trained TensorFlow model
_a = os.path.abspath(__lowerCamelCase )
_a = os.path.abspath(__lowerCamelCase )
print(F"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}." )
# Initialise PyTorch model
if transfo_xl_config_file == "":
_a = TransfoXLConfig()
else:
_a = TransfoXLConfig.from_json_file(__lowerCamelCase )
print(F"Building PyTorch model from configuration: {config}" )
_a = TransfoXLLMHeadModel(__lowerCamelCase )
_a = load_tf_weights_in_transfo_xl(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
# Save pytorch-model
_a = os.path.join(__lowerCamelCase , __lowerCamelCase )
_a = os.path.join(__lowerCamelCase , __lowerCamelCase )
print(F"Save PyTorch model to {os.path.abspath(__lowerCamelCase )}" )
torch.save(model.state_dict() , __lowerCamelCase )
print(F"Save configuration file to {os.path.abspath(__lowerCamelCase )}" )
with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
lowercase__ = argparse.ArgumentParser()
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=True,
help="Path to the folder to store the PyTorch model or dataset/vocab.",
)
parser.add_argument(
"--tf_checkpoint_path",
default="",
type=str,
help="An optional path to a TensorFlow checkpoint path to be converted.",
)
parser.add_argument(
"--transfo_xl_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained BERT model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--transfo_xl_dataset_file",
default="",
type=str,
help="An optional dataset file to be converted in a vocabulary.",
)
lowercase__ = parser.parse_args()
convert_transfo_xl_checkpoint_to_pytorch(
args.tf_checkpoint_path,
args.transfo_xl_config_file,
args.pytorch_dump_folder_path,
args.transfo_xl_dataset_file,
)
| 276
| 1
|
import io
import json
import fsspec
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase ):
assert isinstance(__UpperCamelCase , __UpperCamelCase )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('''keep_in_memory''' , [False, True] )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
A_ = JsonDatasetReader(__UpperCamelCase , cache_dir=__UpperCamelCase , keep_in_memory=__UpperCamelCase ).read()
_check_json_dataset(__UpperCamelCase , __UpperCamelCase )
@pytest.mark.parametrize(
'''features''' , [
None,
{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
{'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
{'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
{'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
] , )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
A_ = features.copy() if features else default_expected_features
A_ = (
Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None
)
A_ = JsonDatasetReader(__UpperCamelCase , features=__UpperCamelCase , cache_dir=__UpperCamelCase ).read()
_check_json_dataset(__UpperCamelCase , __UpperCamelCase )
@pytest.mark.parametrize(
'''features''' , [
None,
{'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''},
] , )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = tmp_path / '''cache'''
A_ = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}
A_ = features.copy() if features else default_expected_features
A_ = (
Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None
)
A_ = JsonDatasetReader(__UpperCamelCase , features=__UpperCamelCase , cache_dir=__UpperCamelCase ).read()
assert isinstance(__UpperCamelCase , __UpperCamelCase )
assert dataset.num_rows == 2
assert dataset.num_columns == 3
assert dataset.column_names == ["col_3", "col_1", "col_2"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase ):
# jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"}
A_ = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''}
A_ = features.copy()
A_ = (
Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None
)
A_ = tmp_path / '''cache'''
A_ = JsonDatasetReader(__UpperCamelCase , features=__UpperCamelCase , cache_dir=__UpperCamelCase ).read()
assert isinstance(__UpperCamelCase , __UpperCamelCase )
assert dataset.num_rows == 2
assert dataset.num_columns == 3
assert dataset.column_names == ["col_2", "col_3", "col_1"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
A_ = JsonDatasetReader(__UpperCamelCase , cache_dir=__UpperCamelCase , split=__UpperCamelCase ).read()
_check_json_dataset(__UpperCamelCase , __UpperCamelCase )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize('''path_type''' , [str, list] )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
if issubclass(__UpperCamelCase , __UpperCamelCase ):
A_ = jsonl_path
elif issubclass(__UpperCamelCase , __UpperCamelCase ):
A_ = [jsonl_path]
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
A_ = JsonDatasetReader(__UpperCamelCase , cache_dir=__UpperCamelCase ).read()
_check_json_dataset(__UpperCamelCase , __UpperCamelCase )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=("train",) ):
assert isinstance(__UpperCamelCase , __UpperCamelCase )
for split in splits:
A_ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize('''keep_in_memory''' , [False, True] )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
A_ = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=__UpperCamelCase , keep_in_memory=__UpperCamelCase ).read()
_check_json_datasetdict(__UpperCamelCase , __UpperCamelCase )
@pytest.mark.parametrize(
'''features''' , [
None,
{'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
{'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
{'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
{'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
] , )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
A_ = features.copy() if features else default_expected_features
A_ = (
Features({feature: Value(__UpperCamelCase ) for feature, dtype in features.items()} ) if features is not None else None
)
A_ = JsonDatasetReader({'''train''': jsonl_path} , features=__UpperCamelCase , cache_dir=__UpperCamelCase ).read()
_check_json_datasetdict(__UpperCamelCase , __UpperCamelCase )
@pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] )
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
if split:
A_ = {split: jsonl_path}
else:
A_ = '''train'''
A_ = {'''train''': jsonl_path, '''test''': jsonl_path}
A_ = tmp_path / '''cache'''
A_ = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
A_ = JsonDatasetReader(__UpperCamelCase , cache_dir=__UpperCamelCase ).read()
_check_json_datasetdict(__UpperCamelCase , __UpperCamelCase , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def lowerCamelCase_ ( __UpperCamelCase ):
return json.load(__UpperCamelCase )
def lowerCamelCase_ ( __UpperCamelCase ):
return [json.loads(__UpperCamelCase ) for line in buffer]
class __lowercase :
@pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] )
def lowerCAmelCase_ ( self , a__ , a__ , a__ ) -> int:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(a__ , a__ , lines=a__ ).write()
buffer.seek(0 )
A_ = load_json_function(a__ )
assert isinstance(a__ , a__ )
assert isinstance(exported_content[0] , a__ )
assert len(a__ ) == 1_0
@pytest.mark.parametrize(
'''orient, container, keys, len_at''' , [
('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
('''split''', dict, {'''columns''', '''data'''}, '''data'''),
('''index''', dict, set('''0123456789''' ), None),
('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
('''values''', list, None, None),
('''table''', dict, {'''schema''', '''data'''}, '''data'''),
] , )
def lowerCAmelCase_ ( self , a__ , a__ , a__ , a__ , a__ ) -> Optional[int]:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(a__ , a__ , lines=a__ , orient=a__ ).write()
buffer.seek(0 )
A_ = load_json(a__ )
assert isinstance(a__ , a__ )
if keys:
if container is dict:
assert exported_content.keys() == keys
else:
assert exported_content[0].keys() == keys
else:
assert not hasattr(a__ , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' )
if len_at:
assert len(exported_content[len_at] ) == 1_0
else:
assert len(a__ ) == 1_0
@pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] )
def lowerCAmelCase_ ( self , a__ , a__ , a__ ) -> Optional[int]:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(a__ , a__ , lines=a__ , num_proc=2 ).write()
buffer.seek(0 )
A_ = load_json_function(a__ )
assert isinstance(a__ , a__ )
assert isinstance(exported_content[0] , a__ )
assert len(a__ ) == 1_0
@pytest.mark.parametrize(
'''orient, container, keys, len_at''' , [
('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
('''split''', dict, {'''columns''', '''data'''}, '''data'''),
('''index''', dict, set('''0123456789''' ), None),
('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
('''values''', list, None, None),
('''table''', dict, {'''schema''', '''data'''}, '''data'''),
] , )
def lowerCAmelCase_ ( self , a__ , a__ , a__ , a__ , a__ ) -> Tuple:
'''simple docstring'''
with io.BytesIO() as buffer:
JsonDatasetWriter(a__ , a__ , lines=a__ , orient=a__ , num_proc=2 ).write()
buffer.seek(0 )
A_ = load_json(a__ )
assert isinstance(a__ , a__ )
if keys:
if container is dict:
assert exported_content.keys() == keys
else:
assert exported_content[0].keys() == keys
else:
assert not hasattr(a__ , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' )
if len_at:
assert len(exported_content[len_at] ) == 1_0
else:
assert len(a__ ) == 1_0
def lowerCAmelCase_ ( self , a__ ) -> Dict:
'''simple docstring'''
with pytest.raises(a__ ):
with io.BytesIO() as buffer:
JsonDatasetWriter(a__ , a__ , num_proc=0 )
@pytest.mark.parametrize('''compression, extension''' , [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] )
def lowerCAmelCase_ ( self , a__ , a__ , a__ , a__ , a__ ) -> List[Any]:
'''simple docstring'''
A_ = tmp_path_factory.mktemp('''data''' ) / F"test.json.{extension}"
A_ = str(shared_datadir / F"test_file.json.{extension}" )
JsonDatasetWriter(a__ , a__ , compression=a__ ).write()
with fsspec.open(a__ , '''rb''' , compression='''infer''' ) as f:
A_ = f.read()
with fsspec.open(a__ , '''rb''' , compression='''infer''' ) as f:
A_ = f.read()
assert exported_content == original_content
| 141
|
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
if n == 0:
return 1
elif n % 2 == 1:
return (binary_exponentiation(__UpperCamelCase , n - 1 , __UpperCamelCase ) * a) % mod
else:
A_ = binary_exponentiation(__UpperCamelCase , n / 2 , __UpperCamelCase )
return (b * b) % mod
# a prime number
SCREAMING_SNAKE_CASE : str = 701
SCREAMING_SNAKE_CASE : int = 10_0000_0000
SCREAMING_SNAKE_CASE : Optional[Any] = 10
# using binary exponentiation function, O(log(p)):
print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p)
print((a / b) % p == (a * b ** (p - 2)) % p)
| 141
| 1
|
'''simple docstring'''
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
lowerCamelCase :str = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''')
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase ( __UpperCAmelCase , unittest.TestCase ):
__SCREAMING_SNAKE_CASE : str = GPTSwaTokenizer
__SCREAMING_SNAKE_CASE : Tuple = False
__SCREAMING_SNAKE_CASE : List[Any] = True
__SCREAMING_SNAKE_CASE : List[Any] = False
def _a (self ):
super().setUp()
# We have a SentencePiece fixture for testing
A_ : Union[str, Any] = GPTSwaTokenizer(lowercase , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""" )
tokenizer.save_pretrained(self.tmpdirname )
def _a (self , lowercase ):
A_ : List[str] = """This is a test"""
A_ : List[str] = """This is a test"""
return input_text, output_text
def _a (self ):
A_ : str = """<s>"""
A_ : Dict = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase )
def _a (self ):
A_ : Any = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , """<unk>""" )
self.assertEqual(vocab_keys[1] , """<s>""" )
self.assertEqual(vocab_keys[-1] , """j""" )
self.assertEqual(len(lowercase ) , 2000 )
def _a (self ):
self.assertEqual(self.get_tokenizer().vocab_size , 2000 )
def _a (self ):
A_ : int = GPTSwaTokenizer(lowercase )
A_ : Dict = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(lowercase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase ) , [465, 287, 265, 631, 842] )
A_ : Dict = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
# fmt: off
self.assertListEqual(
lowercase , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , )
# fmt: on
A_ : List[Any] = tokenizer.convert_tokens_to_ids(lowercase )
self.assertListEqual(
lowercase , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
A_ : Optional[int] = tokenizer.convert_ids_to_tokens(lowercase )
# fmt: off
self.assertListEqual(
lowercase , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] )
# fmt: on
def _a (self ):
A_ : List[Any] = GPTSwaTokenizer(lowercase )
A_ : Optional[int] = ["""This is a test""", """I was born in 92000, and this is falsé."""]
A_ : Union[str, Any] = [
[465, 287, 265, 631, 842],
[262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(lowercase , lowercase ):
self.assertListEqual(tokenizer.encode_fast(lowercase ) , lowercase )
# Test that decode_fast returns the input text
for text, token_ids in zip(lowercase , lowercase ):
self.assertEqual(tokenizer.decode_fast(lowercase ) , lowercase )
@slow
def _a (self ):
A_ : Union[str, Any] = [
"""<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""",
"""Hey there, how are you doing this fine day?""",
"""This is a text with a trailing spaces followed by a dot .""",
"""Häj sväjs lillebrör! =)""",
"""Det är inget fel på Mr. Cool""",
]
# fmt: off
A_ : Dict = {"""input_ids""": [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowercase , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=lowercase , )
| 711
|
'''simple docstring'''
import argparse
import torch
from transformers import (
EncodecConfig,
EncodecFeatureExtractor,
EncodecModel,
logging,
)
# checkpoints downloaded from:
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th
# https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin
# https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th
logging.set_verbosity_info()
lowerCamelCase :int = logging.get_logger('''transformers.models.encodec''')
lowerCamelCase :int = {
'''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''',
'''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''',
'''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''',
'''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''',
}
lowerCamelCase :List[str] = {
'''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''',
'''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''',
'''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''',
'''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''',
'''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''',
'''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''',
'''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''',
'''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''',
'''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''',
'''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''',
'''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''',
'''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''',
'''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''',
'''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''',
'''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''',
'''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''',
'''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''',
'''encoder.model.13.lstm''': '''encoder.layers.13.lstm''',
'''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''',
}
lowerCamelCase :Union[str, Any] = {
'''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''',
'''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''',
'''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''',
'''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''',
'''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''',
'''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''',
'''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''',
'''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''',
'''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''',
'''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''',
'''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''',
'''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''',
'''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''',
'''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''',
'''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''',
'''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''',
'''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''',
'''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''',
}
lowerCamelCase :Dict = {
'''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''',
'''decoder.model.1.lstm''': '''decoder.layers.1.lstm''',
'''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''',
'''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''',
'''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''',
'''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''',
'''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''',
'''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''',
'''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''',
'''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''',
'''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''',
'''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''',
'''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''',
'''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''',
'''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''',
'''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''',
'''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''',
'''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''',
'''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''',
}
lowerCamelCase :int = {
'''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''',
'''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''',
'''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''',
'''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''',
'''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''',
'''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''',
'''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''',
'''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''',
'''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''',
'''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''',
'''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''',
'''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''',
'''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''',
'''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''',
'''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''',
'''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''',
'''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''',
'''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''',
}
lowerCamelCase :str = {
**MAPPING_QUANTIZER,
**MAPPING_ENCODER,
**MAPPING_DECODER,
}
lowerCamelCase :List[Any] = {
**MAPPING_QUANTIZER,
**MAPPING_ENCODER,
**MAPPING_ENCODER_48K,
**MAPPING_DECODER,
**MAPPING_DECODER_48K,
}
lowerCamelCase :Tuple = []
lowerCamelCase :Dict = []
def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
for attribute in key.split(""".""" ):
A_ : Optional[Any] = getattr(lowerCamelCase__ , lowerCamelCase__ )
if weight_type is not None:
A_ : Optional[int] = getattr(lowerCamelCase__ , lowerCamelCase__ ).shape
else:
A_ : Any = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'
f' {value.shape} for {full_name}' )
if weight_type == "weight":
A_ : Optional[int] = value
elif weight_type == "weight_g":
A_ : Optional[int] = value
elif weight_type == "weight_v":
A_ : Dict = value
elif weight_type == "bias":
A_ : Dict = value
elif weight_type == "running_mean":
A_ : Optional[Any] = value
elif weight_type == "running_var":
A_ : int = value
elif weight_type == "num_batches_tracked":
A_ : Optional[Any] = value
elif weight_type == "weight_ih_l0":
A_ : Optional[int] = value
elif weight_type == "weight_hh_l0":
A_ : Union[str, Any] = value
elif weight_type == "bias_ih_l0":
A_ : Optional[int] = value
elif weight_type == "bias_hh_l0":
A_ : Tuple = value
elif weight_type == "weight_ih_l1":
A_ : Optional[int] = value
elif weight_type == "weight_hh_l1":
A_ : Dict = value
elif weight_type == "bias_ih_l1":
A_ : Optional[int] = value
elif weight_type == "bias_hh_l1":
A_ : Tuple = value
else:
A_ : Any = value
logger.info(f'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' )
def a ( lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
for key in ignore_keys:
if key.endswith(""".*""" ):
if name.startswith(key[:-1] ):
return True
elif ".*." in key:
A_, A_ : List[str] = key.split(""".*.""" )
if prefix in name and suffix in name:
return True
elif key in name:
return True
return False
def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
A_ : List[Any] = []
if model_name == "encodec_24khz" or "encodec_32khz":
A_ : List[str] = MAPPING_24K
elif model_name == "encodec_48khz":
A_ : str = MAPPING_48K
else:
raise ValueError(f'Unsupported model: {model_name}' )
for name, value in orig_dict.items():
if should_ignore(lowerCamelCase__ , lowerCamelCase__ ):
logger.info(f'{name} was ignored' )
continue
A_ : str = False
for key, mapped_key in MAPPING.items():
if "*" in key:
A_, A_ : List[Any] = key.split(""".*.""" )
if prefix in name and suffix in name:
A_ : Optional[Any] = suffix
if key in name:
# HACK otherwise .embed gets initialized with .embed_avg too
if key.endswith("""embed""" ) and name.endswith("""embed_avg""" ):
continue
A_ : Union[str, Any] = True
if "*" in mapped_key:
A_ : int = name.split(lowerCamelCase__ )[0].split(""".""" )[-2]
A_ : Optional[Any] = mapped_key.replace("""*""" , lowerCamelCase__ )
if "weight_g" in name:
A_ : Any = """weight_g"""
elif "weight_v" in name:
A_ : Tuple = """weight_v"""
elif "weight_ih_l0" in name:
A_ : Union[str, Any] = """weight_ih_l0"""
elif "weight_hh_l0" in name:
A_ : Tuple = """weight_hh_l0"""
elif "bias_ih_l0" in name:
A_ : str = """bias_ih_l0"""
elif "bias_hh_l0" in name:
A_ : List[Any] = """bias_hh_l0"""
elif "weight_ih_l1" in name:
A_ : Dict = """weight_ih_l1"""
elif "weight_hh_l1" in name:
A_ : Any = """weight_hh_l1"""
elif "bias_ih_l1" in name:
A_ : Optional[int] = """bias_ih_l1"""
elif "bias_hh_l1" in name:
A_ : List[Any] = """bias_hh_l1"""
elif "bias" in name:
A_ : List[str] = """bias"""
elif "weight" in name:
A_ : Optional[int] = """weight"""
elif "running_mean" in name:
A_ : Union[str, Any] = """running_mean"""
elif "running_var" in name:
A_ : Optional[int] = """running_var"""
elif "num_batches_tracked" in name:
A_ : List[Any] = """num_batches_tracked"""
else:
A_ : str = None
set_recursively(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
continue
if not is_used:
unused_weights.append(lowerCamelCase__ )
logger.warning(f'Unused weights: {unused_weights}' )
@torch.no_grad()
def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , ):
'''simple docstring'''
if config_path is not None:
A_ : Any = EncodecConfig.from_pretrained(lowerCamelCase__ )
else:
A_ : Optional[int] = EncodecConfig()
if model_name == "encodec_24khz":
pass # config is already correct
elif model_name == "encodec_32khz":
A_ : Dict = [8, 5, 4, 4]
A_ : Optional[Any] = [2.2]
A_ : Tuple = 64
A_ : Tuple = 3_20_00
A_ : List[Any] = 20_48
A_ : Optional[Any] = False
A_ : str = False
A_ : Optional[int] = False
elif model_name == "encodec_48khz":
A_ : Dict = [8, 5, 4, 2]
A_ : Tuple = [3.0, 6.0, 12.0, 24.0]
A_ : List[Any] = 4_80_00
A_ : Dict = 2
A_ : Dict = False
A_ : Dict = """time_group_norm"""
A_ : Optional[Any] = True
A_ : str = 1.0
A_ : Any = 0.01
else:
raise ValueError(f'Unknown model name: {model_name}' )
A_ : Dict = EncodecModel(lowerCamelCase__ )
A_ : Any = EncodecFeatureExtractor(
feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , )
feature_extractor.save_pretrained(lowerCamelCase__ )
A_ : int = torch.load(lowerCamelCase__ )
if "best_state" in original_checkpoint:
# we might have a training state saved, in which case discard the yaml results and just retain the weights
A_ : Tuple = original_checkpoint["""best_state"""]
recursively_load_weights(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
model.save_pretrained(lowerCamelCase__ )
if repo_id:
print("""Pushing to the hub...""" )
feature_extractor.push_to_hub(lowerCamelCase__ )
model.push_to_hub(lowerCamelCase__ )
if __name__ == "__main__":
lowerCamelCase :Any = argparse.ArgumentParser()
parser.add_argument(
'''--model''',
default='''encodec_24khz''',
type=str,
help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''',
)
parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''')
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
parser.add_argument(
'''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.'''
)
parser.add_argument(
'''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.'''
)
lowerCamelCase :Dict = parser.parse_args()
convert_checkpoint(
args.model,
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.config_path,
args.push_to_hub,
)
| 686
| 0
|
import qiskit
def lowerCamelCase_ ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ):
lowercase : Tuple = qiskit.Aer.get_backend('''aer_simulator''' )
# Create a Quantum Circuit acting on the q register
lowercase : Optional[int] = qiskit.QuantumCircuit(UpperCAmelCase_ , UpperCAmelCase_ )
# Map the quantum measurement to the classical bits
circuit.measure([0] , [0] )
# Execute the circuit on the simulator
lowercase : Union[str, Any] = qiskit.execute(UpperCAmelCase_ , UpperCAmelCase_ , shots=10_00 )
# Return the histogram data of the results of the experiment.
return job.result().get_counts(UpperCAmelCase_ )
if __name__ == "__main__":
print(F'Total count for various states are: {single_qubit_measure(1, 1)}')
| 583
|
import json
import os
import tempfile
from unittest.mock import patch
import torch
from torch.utils.data import DataLoader, TensorDataset
from accelerate import DistributedType, infer_auto_device_map, init_empty_weights
from accelerate.accelerator import Accelerator
from accelerate.state import GradientState, PartialState
from accelerate.test_utils import require_bnb, require_multi_gpu, slow
from accelerate.test_utils.testing import AccelerateTestCase, require_cuda
from accelerate.utils import patch_environment
def lowerCamelCase_ ( ):
lowercase : Any = torch.nn.Linear(2 , 4 )
lowercase : int = torch.optim.AdamW(model.parameters() , lr=1.0 )
lowercase : Optional[Any] = torch.optim.lr_scheduler.OneCycleLR(UpperCAmelCase_ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 )
lowercase : List[Any] = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) )
lowercase : Optional[int] = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) )
return model, optimizer, scheduler, train_dl, valid_dl
def lowerCamelCase_ ( UpperCAmelCase_ : Any ):
return (model.weight.abs().sum() + model.bias.abs().sum()).item()
def lowerCamelCase_ ( UpperCAmelCase_ : Dict ):
lowercase : List[str] = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict()
model.load_state_dict(UpperCAmelCase_ )
class UpperCAmelCase ( __lowerCamelCase ):
@require_cuda
def _lowerCAmelCase ( self : Optional[Any] ):
lowercase : List[Any] = Accelerator()
assert PartialState._shared_state["_cpu"] is False
assert PartialState._shared_state["device"].type == "cuda"
with self.assertRaises(lowerCAmelCase ):
lowercase : Optional[Any] = Accelerator(cpu=lowerCAmelCase )
def _lowerCAmelCase ( self : Union[str, Any] ):
lowercase : int = Accelerator()
lowercase : Union[str, Any] = GradientState()
assert state.num_steps == 1
lowercase : Tuple = 4
assert state.num_steps == 4
assert state.sync_gradients is True
lowercase : Tuple = False
assert state.sync_gradients is False
GradientState._reset_state()
def _lowerCAmelCase ( self : Union[str, Any] ):
lowercase : List[str] = Accelerator()
lowercase , lowercase , lowercase , lowercase , lowercase : Optional[int] = create_components()
(
(
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) , (
lowercase
) ,
) : Union[str, Any] = accelerator.prepare(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
self.assertTrue(prepared_model in accelerator._models )
self.assertTrue(prepared_optimizer in accelerator._optimizers )
self.assertTrue(prepared_scheduler in accelerator._schedulers )
self.assertTrue(prepared_train_dl in accelerator._dataloaders )
self.assertTrue(prepared_valid_dl in accelerator._dataloaders )
def _lowerCAmelCase ( self : int ):
lowercase : Optional[Any] = Accelerator()
lowercase , lowercase , lowercase , lowercase , lowercase : Optional[Any] = create_components()
accelerator.prepare(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
accelerator.free_memory()
self.assertTrue(len(accelerator._models ) == 0 )
self.assertTrue(len(accelerator._optimizers ) == 0 )
self.assertTrue(len(accelerator._schedulers ) == 0 )
self.assertTrue(len(accelerator._dataloaders ) == 0 )
def _lowerCAmelCase ( self : Dict ):
PartialState._reset_state()
# Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
def noop(*lowerCAmelCase : Any , **lowerCAmelCase : Optional[int] ):
pass
with patch('''torch.cuda.set_device''' , lowerCAmelCase ), patch_environment(ACCELERATE_TORCH_DEVICE='''cuda:64''' ):
lowercase : Optional[Any] = Accelerator()
self.assertEqual(str(accelerator.state.device ) , '''cuda:64''' )
def _lowerCAmelCase ( self : Union[str, Any] ):
lowercase : Tuple = Accelerator()
lowercase , lowercase , lowercase , lowercase , lowercase : int = create_components()
accelerator.prepare(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
lowercase : List[Any] = get_signature(lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
accelerator.save_state(lowerCAmelCase )
# make sure random weights don't match
load_random_weights(lowerCAmelCase )
self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase ) ) > 1E-3 )
# make sure loaded weights match
accelerator.load_state(lowerCAmelCase )
self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase ) ) < 1E-3 )
def _lowerCAmelCase ( self : Optional[Any] ):
lowercase : int = Accelerator()
lowercase , lowercase , lowercase , lowercase , lowercase : List[str] = create_components()
accelerator.prepare(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
lowercase : Tuple = get_signature(lowerCAmelCase )
# saving hook
def save_config(lowerCAmelCase : Dict , lowerCAmelCase : List[Any] , lowerCAmelCase : int ):
lowercase : Optional[int] = {'''class_name''': models[0].__class__.__name__}
with open(os.path.join(lowerCAmelCase , '''data.json''' ) , '''w''' ) as f:
json.dump(lowerCAmelCase , lowerCAmelCase )
# loading hook
def load_config(lowerCAmelCase : Dict , lowerCAmelCase : Dict ):
with open(os.path.join(lowerCAmelCase , '''data.json''' ) , '''r''' ) as f:
lowercase : Dict = json.load(lowerCAmelCase )
lowercase : Union[str, Any] = config['''class_name''']
lowercase : str = accelerator.register_save_state_pre_hook(lowerCAmelCase )
lowercase : Tuple = accelerator.register_load_state_pre_hook(lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmpdirname:
accelerator.save_state(lowerCAmelCase )
# make sure random weights don't match with hooks
load_random_weights(lowerCAmelCase )
self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase ) ) > 1E-3 )
# random class name to verify correct one is loaded
lowercase : List[Any] = '''random'''
# make sure loaded weights match with hooks
accelerator.load_state(lowerCAmelCase )
self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase ) ) < 1E-3 )
# mode.class_name is loaded from config
self.assertTrue(model.class_name == model.__class__.__name__ )
# remove hooks
save_hook.remove()
load_hook.remove()
with tempfile.TemporaryDirectory() as tmpdirname:
accelerator.save_state(lowerCAmelCase )
# make sure random weights don't match with hooks removed
load_random_weights(lowerCAmelCase )
self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase ) ) > 1E-3 )
# random class name to verify correct one is loaded
lowercase : Any = '''random'''
# make sure loaded weights match with hooks removed
accelerator.load_state(lowerCAmelCase )
self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase ) ) < 1E-3 )
# mode.class_name is NOT loaded from config
self.assertTrue(model.class_name != model.__class__.__name__ )
def _lowerCAmelCase ( self : Union[str, Any] ):
lowercase : List[Any] = Accelerator()
lowercase , lowercase , lowercase , lowercase , lowercase : Optional[int] = create_components()
lowercase : int = None
# This should work
lowercase , lowercase , lowercase , lowercase , lowercase , lowercase : int = accelerator.prepare(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
self.assertTrue(dummy_obj is None )
def _lowerCAmelCase ( self : Dict ):
lowercase : str = Accelerator()
lowercase , lowercase , lowercase , lowercase , lowercase : List[str] = create_components()
lowercase : List[str] = [1, 2, 3]
# This should work
lowercase , lowercase , lowercase , lowercase , lowercase , lowercase : Union[str, Any] = accelerator.prepare(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
self.assertEqual(
getattr(lowerCAmelCase , '''_is_accelerate_prepared''' , lowerCAmelCase ) , lowerCAmelCase , '''Dummy object should have `_is_accelerate_prepared` set to `True`''' , )
self.assertEqual(
getattr(lowerCAmelCase , '''_is_accelerate_prepared''' , lowerCAmelCase ) , lowerCAmelCase , '''Model is missing `_is_accelerator_prepared` or is set to `False`''' , )
self.assertEqual(
getattr(lowerCAmelCase , '''_is_accelerate_prepared''' , lowerCAmelCase ) , lowerCAmelCase , '''Optimizer is missing `_is_accelerator_prepared` or is set to `False`''' , )
self.assertEqual(
getattr(lowerCAmelCase , '''_is_accelerate_prepared''' , lowerCAmelCase ) , lowerCAmelCase , '''Scheduler is missing `_is_accelerator_prepared` or is set to `False`''' , )
self.assertEqual(
getattr(lowerCAmelCase , '''_is_accelerate_prepared''' , lowerCAmelCase ) , lowerCAmelCase , '''Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`''' , )
self.assertEqual(
getattr(lowerCAmelCase , '''_is_accelerate_prepared''' , lowerCAmelCase ) , lowerCAmelCase , '''Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`''' , )
@slow
@require_bnb
def _lowerCAmelCase ( self : Optional[int] ):
from transformers import AutoModelForCausalLM
lowercase : Optional[int] = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , load_in_abit=lowerCAmelCase , device_map={'''''': 0} , )
lowercase : List[str] = Accelerator()
# This should work
lowercase : Any = accelerator.prepare(lowerCAmelCase )
@slow
@require_bnb
def _lowerCAmelCase ( self : Optional[Any] ):
from transformers import AutoModelForCausalLM
lowercase : Optional[int] = Accelerator()
with init_empty_weights():
lowercase : str = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , )
model.tie_weights()
lowercase : Optional[Any] = infer_auto_device_map(lowerCAmelCase )
lowercase : str = '''cpu'''
lowercase : Optional[Any] = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , device_map=lowerCAmelCase , load_in_abit=lowerCAmelCase , llm_inta_enable_fpaa_cpu_offload=lowerCAmelCase )
# This should not work and get value error
with self.assertRaises(lowerCAmelCase ):
lowercase : Optional[Any] = accelerator.prepare(lowerCAmelCase )
@slow
@require_bnb
@require_multi_gpu
def _lowerCAmelCase ( self : Union[str, Any] ):
from transformers import AutoModelForCausalLM
lowercase : Tuple = {'''distributed_type''': DistributedType.MULTI_GPU}
with init_empty_weights():
lowercase : Union[str, Any] = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , )
model.tie_weights()
lowercase : int = infer_auto_device_map(lowerCAmelCase )
lowercase : Tuple = 1
lowercase : Tuple = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , load_in_abit=lowerCAmelCase , device_map=lowerCAmelCase , )
lowercase : Any = Accelerator()
# This should not work and get value error
with self.assertRaises(lowerCAmelCase ):
lowercase : str = accelerator.prepare(lowerCAmelCase )
PartialState._reset_state()
@slow
@require_bnb
@require_multi_gpu
def _lowerCAmelCase ( self : str ):
from transformers import AutoModelForCausalLM
with init_empty_weights():
lowercase : Optional[int] = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , )
lowercase : Any = infer_auto_device_map(lowerCAmelCase )
lowercase : Any = 1
lowercase : int = AutoModelForCausalLM.from_pretrained(
'''EleutherAI/gpt-neo-125m''' , load_in_abit=lowerCAmelCase , device_map=lowerCAmelCase , )
lowercase : List[str] = Accelerator()
# This should work
lowercase : List[Any] = accelerator.prepare(lowerCAmelCase )
@require_cuda
def _lowerCAmelCase ( self : str ):
lowercase : int = torch.nn.Linear(10 , 10 )
lowercase : Optional[Any] = torch.optim.SGD(model.parameters() , lr=0.01 )
lowercase : Union[str, Any] = Accelerator(cpu=lowerCAmelCase )
lowercase : Union[str, Any] = accelerator.prepare(lowerCAmelCase )
| 583
| 1
|
"""simple docstring"""
import random
class __magic_name__ :
@staticmethod
def lowercase_ ( A_ ) -> tuple[list[int], list[int]]:
"""simple docstring"""
_lowercase: Optional[int] = [ord(__UpperCamelCase ) for i in text]
_lowercase: Optional[int] = []
_lowercase: Dict = []
for i in plain:
_lowercase: Any = random.randint(1 , 300 )
_lowercase: Union[str, Any] = (i + k) * k
cipher.append(__UpperCamelCase )
key.append(__UpperCamelCase )
return cipher, key
@staticmethod
def lowercase_ ( A_ , A_ ) -> str:
"""simple docstring"""
_lowercase: int = []
for i in range(len(__UpperCamelCase ) ):
_lowercase: List[str] = int((cipher[i] - (key[i]) ** 2) / key[i] )
plain.append(chr(__UpperCamelCase ) )
return "".join(__UpperCamelCase )
if __name__ == "__main__":
A__ : Union[str, Any] = Onepad().encrypt('Hello')
print(c, k)
print(Onepad().decrypt(c, k))
| 719
|
"""simple docstring"""
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
A__ : Tuple = pd.read_csv(
'https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/'
'position_salaries.csv'
)
A__ : Optional[int] = dataset.iloc[:, 1:2].values
A__ : Union[str, Any] = dataset.iloc[:, 2].values
A__ , A__ , A__ , A__ : Dict = train_test_split(X, y, test_size=0.2, random_state=0)
A__ : Union[str, Any] = PolynomialFeatures(degree=4)
A__ : List[Any] = poly_reg.fit_transform(X)
A__ : Dict = LinearRegression()
pol_reg.fit(X_poly, y)
def _lowerCAmelCase ( ):
"""simple docstring"""
plt.scatter(_UpperCamelCase , _UpperCamelCase , color='''red''' )
plt.plot(_UpperCamelCase , pol_reg.predict(poly_reg.fit_transform(_UpperCamelCase ) ) , color='''blue''' )
plt.title('''Truth or Bluff (Linear Regression)''' )
plt.xlabel('''Position level''' )
plt.ylabel('''Salary''' )
plt.show()
if __name__ == "__main__":
viz_polymonial()
# Predicting a new result with Polymonial Regression
pol_reg.predict(poly_reg.fit_transform([[5.5]]))
# output should be 132148.43750003
| 272
| 0
|
import unittest
import numpy as np
from transformers import is_flax_available
from transformers.testing_utils import require_flax
from ..test_modeling_flax_common import ids_tensor
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.generation import (
FlaxForcedBOSTokenLogitsProcessor,
FlaxForcedEOSTokenLogitsProcessor,
FlaxLogitsProcessorList,
FlaxMinLengthLogitsProcessor,
FlaxTemperatureLogitsWarper,
FlaxTopKLogitsWarper,
FlaxTopPLogitsWarper,
)
@require_flax
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def a ( self , _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
__snake_case = jnp.ones((batch_size, length) ) / length
return scores
def a ( self ) -> List[str]:
"""simple docstring"""
__snake_case = None
__snake_case = 20
__snake_case = self._get_uniform_logits(batch_size=2 , length=_UpperCamelCase )
# tweak scores to not be uniform anymore
__snake_case = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch
__snake_case = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch
# compute softmax
__snake_case = jax.nn.softmax(_UpperCamelCase , axis=-1 )
__snake_case = FlaxTemperatureLogitsWarper(temperature=0.5 )
__snake_case = FlaxTemperatureLogitsWarper(temperature=1.3 )
__snake_case = jax.nn.softmax(temp_dist_warper_sharper(_UpperCamelCase , scores.copy() , cur_len=_UpperCamelCase ) , axis=-1 )
__snake_case = jax.nn.softmax(temp_dist_warper_smoother(_UpperCamelCase , scores.copy() , cur_len=_UpperCamelCase ) , axis=-1 )
# uniform distribution stays uniform
self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1E-3 ) )
self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1E-3 ) )
# sharp peaks get higher, valleys get lower
self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() )
self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() )
# smooth peaks get lower, valleys get higher
self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() )
self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() )
def a ( self ) -> str:
"""simple docstring"""
__snake_case = None
__snake_case = 10
__snake_case = 2
# create ramp distribution
__snake_case = np.broadcast_to(np.arange(_UpperCamelCase )[None, :] , (batch_size, vocab_size) ).copy()
__snake_case = ramp_logits[1:, : vocab_size // 2] + vocab_size
__snake_case = FlaxTopKLogitsWarper(3 )
__snake_case = top_k_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
# check that correct tokens are filtered
self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] )
self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] )
# check special case
__snake_case = 5
__snake_case = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 )
__snake_case = np.broadcast_to(np.arange(_UpperCamelCase )[None, :] , (batch_size, length) ).copy()
__snake_case = top_k_warp_safety_check(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified
self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] )
def a ( self ) -> int:
"""simple docstring"""
__snake_case = None
__snake_case = 10
__snake_case = 2
# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)
__snake_case = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) )
__snake_case = FlaxTopPLogitsWarper(0.8 )
__snake_case = np.exp(top_p_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase ) )
# dist should be filtered to keep min num values so that sum is >= top_p
# exp (-inf) => 0
__snake_case = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] )
self.assertTrue(np.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 ) )
# check edge cases with negative and extreme logits
__snake_case = np.broadcast_to(np.arange(_UpperCamelCase )[None, :] , (batch_size, vocab_size) ).copy() - (
vocab_size // 2
)
# make ramp_logits more extreme
__snake_case = ramp_logits[1] * 100.0
# make sure at least 2 tokens are kept
__snake_case = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 )
__snake_case = top_p_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.
self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] )
def a ( self ) -> Union[str, Any]:
"""simple docstring"""
__snake_case = 20
__snake_case = 4
__snake_case = 0
__snake_case = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_UpperCamelCase )
# check that min length is applied at length 5
__snake_case = ids_tensor((batch_size, 20) , vocab_size=20 )
__snake_case = 5
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = min_dist_processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float("""inf""" )] )
# check that min length is not applied anymore at length 15
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = 15
__snake_case = min_dist_processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
self.assertFalse(jnp.isinf(_UpperCamelCase ).any() )
def a ( self ) -> Optional[Any]:
"""simple docstring"""
__snake_case = 20
__snake_case = 4
__snake_case = 0
__snake_case = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_UpperCamelCase )
# check that all scores are -inf except the bos_token_id score
__snake_case = ids_tensor((batch_size, 1) , vocab_size=20 )
__snake_case = 1
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = logits_processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() )
self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero
# check that bos_token_id is not forced if current length is greater than 1
__snake_case = 3
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = logits_processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
self.assertFalse(jnp.isinf(_UpperCamelCase ).any() )
def a ( self ) -> Tuple:
"""simple docstring"""
__snake_case = 20
__snake_case = 4
__snake_case = 0
__snake_case = 5
__snake_case = FlaxForcedEOSTokenLogitsProcessor(max_length=_UpperCamelCase , eos_token_id=_UpperCamelCase )
# check that all scores are -inf except the eos_token_id when max_length is reached
__snake_case = ids_tensor((batch_size, 4) , vocab_size=20 )
__snake_case = 4
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = logits_processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() )
self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero
# check that eos_token_id is not forced if max_length is not reached
__snake_case = 3
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = logits_processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
self.assertFalse(jnp.isinf(_UpperCamelCase ).any() )
def a ( self ) -> Optional[Any]:
"""simple docstring"""
__snake_case = 4
__snake_case = 10
__snake_case = 15
__snake_case = 2
__snake_case = 1
__snake_case = 15
# dummy input_ids and scores
__snake_case = ids_tensor((batch_size, sequence_length) , _UpperCamelCase )
__snake_case = input_ids.copy()
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = scores.copy()
# instantiate all dist processors
__snake_case = FlaxTemperatureLogitsWarper(temperature=0.5 )
__snake_case = FlaxTopKLogitsWarper(3 )
__snake_case = FlaxTopPLogitsWarper(0.8 )
# instantiate all logits processors
__snake_case = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_UpperCamelCase )
__snake_case = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_UpperCamelCase )
__snake_case = FlaxForcedEOSTokenLogitsProcessor(max_length=_UpperCamelCase , eos_token_id=_UpperCamelCase )
__snake_case = 10
# no processor list
__snake_case = temp_dist_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = top_k_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = top_p_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = min_dist_proc(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = bos_dist_proc(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = eos_dist_proc(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
# with processor list
__snake_case = FlaxLogitsProcessorList(
[temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] )
__snake_case = processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
# scores should be equal
self.assertTrue(jnp.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 ) )
# input_ids should never be changed
self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
def a ( self ) -> str:
"""simple docstring"""
__snake_case = 4
__snake_case = 10
__snake_case = 15
__snake_case = 2
__snake_case = 1
__snake_case = 15
# dummy input_ids and scores
__snake_case = ids_tensor((batch_size, sequence_length) , _UpperCamelCase )
__snake_case = input_ids.copy()
__snake_case = self._get_uniform_logits(_UpperCamelCase , _UpperCamelCase )
__snake_case = scores.copy()
# instantiate all dist processors
__snake_case = FlaxTemperatureLogitsWarper(temperature=0.5 )
__snake_case = FlaxTopKLogitsWarper(3 )
__snake_case = FlaxTopPLogitsWarper(0.8 )
# instantiate all logits processors
__snake_case = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_UpperCamelCase )
__snake_case = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_UpperCamelCase )
__snake_case = FlaxForcedEOSTokenLogitsProcessor(max_length=_UpperCamelCase , eos_token_id=_UpperCamelCase )
__snake_case = 10
# no processor list
def run_no_processor_list(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ):
__snake_case = temp_dist_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = top_k_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = top_p_warp(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = min_dist_proc(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = bos_dist_proc(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
__snake_case = eos_dist_proc(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
return scores
# with processor list
def run_processor_list(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ):
__snake_case = FlaxLogitsProcessorList(
[temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] )
__snake_case = processor(_UpperCamelCase , _UpperCamelCase , cur_len=_UpperCamelCase )
return scores
__snake_case = jax.jit(_UpperCamelCase )
__snake_case = jax.jit(_UpperCamelCase )
__snake_case = jitted_run_no_processor_list(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
__snake_case = jitted_run_processor_list(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
# scores should be equal
self.assertTrue(jnp.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 ) )
# input_ids should never be changed
self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
| 268
|
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import CLIPImageProcessor, CLIPProcessor
@require_vision
class __snake_case ( unittest.TestCase ):
"""simple docstring"""
def a ( self ) -> Optional[int]:
"""simple docstring"""
__snake_case = tempfile.mkdtemp()
# fmt: off
__snake_case = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""]
# fmt: on
__snake_case = dict(zip(_UpperCamelCase , range(len(_UpperCamelCase ) ) ) )
__snake_case = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""]
__snake_case = {"""unk_token""": """<unk>"""}
__snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
__snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] )
with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp:
fp.write(json.dumps(_UpperCamelCase ) + """\n""" )
with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp:
fp.write("""\n""".join(_UpperCamelCase ) )
__snake_case = {
"""do_resize""": True,
"""size""": 20,
"""do_center_crop""": True,
"""crop_size""": 18,
"""do_normalize""": True,
"""image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073],
"""image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711],
}
__snake_case = os.path.join(self.tmpdirname , _UpperCamelCase )
with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp:
json.dump(_UpperCamelCase , _UpperCamelCase )
def a ( self , **_UpperCamelCase ) -> Optional[int]:
"""simple docstring"""
return CLIPTokenizer.from_pretrained(self.tmpdirname , **_UpperCamelCase )
def a ( self , **_UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCamelCase )
def a ( self , **_UpperCamelCase ) -> List[str]:
"""simple docstring"""
return CLIPImageProcessor.from_pretrained(self.tmpdirname , **_UpperCamelCase )
def a ( self ) -> int:
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def a ( self ) -> Optional[Any]:
"""simple docstring"""
__snake_case = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
__snake_case = [Image.fromarray(np.moveaxis(_UpperCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def a ( self ) -> List[Any]:
"""simple docstring"""
__snake_case = self.get_tokenizer()
__snake_case = self.get_rust_tokenizer()
__snake_case = self.get_image_processor()
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
processor_slow.save_pretrained(self.tmpdirname )
__snake_case = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_UpperCamelCase )
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
processor_fast.save_pretrained(self.tmpdirname )
__snake_case = CLIPProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() )
self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() )
self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() )
self.assertIsInstance(processor_slow.tokenizer , _UpperCamelCase )
self.assertIsInstance(processor_fast.tokenizer , _UpperCamelCase )
self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor_slow.image_processor , _UpperCamelCase )
self.assertIsInstance(processor_fast.image_processor , _UpperCamelCase )
def a ( self ) -> List[str]:
"""simple docstring"""
__snake_case = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__snake_case = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" )
__snake_case = self.get_image_processor(do_normalize=_UpperCamelCase , padding_value=1.0 )
__snake_case = CLIPProcessor.from_pretrained(
self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_UpperCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , _UpperCamelCase )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _UpperCamelCase )
def a ( self ) -> Any:
"""simple docstring"""
__snake_case = self.get_image_processor()
__snake_case = self.get_tokenizer()
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
__snake_case = self.prepare_image_inputs()
__snake_case = image_processor(_UpperCamelCase , return_tensors="""np""" )
__snake_case = processor(images=_UpperCamelCase , return_tensors="""np""" )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 )
def a ( self ) -> str:
"""simple docstring"""
__snake_case = self.get_image_processor()
__snake_case = self.get_tokenizer()
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
__snake_case = """lower newer"""
__snake_case = processor(text=_UpperCamelCase )
__snake_case = tokenizer(_UpperCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def a ( self ) -> str:
"""simple docstring"""
__snake_case = self.get_image_processor()
__snake_case = self.get_tokenizer()
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
__snake_case = """lower newer"""
__snake_case = self.prepare_image_inputs()
__snake_case = processor(text=_UpperCamelCase , images=_UpperCamelCase )
self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] )
# test if it raises when no input is passed
with pytest.raises(_UpperCamelCase ):
processor()
def a ( self ) -> Any:
"""simple docstring"""
__snake_case = self.get_image_processor()
__snake_case = self.get_tokenizer()
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
__snake_case = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__snake_case = processor.batch_decode(_UpperCamelCase )
__snake_case = tokenizer.batch_decode(_UpperCamelCase )
self.assertListEqual(_UpperCamelCase , _UpperCamelCase )
def a ( self ) -> int:
"""simple docstring"""
__snake_case = self.get_image_processor()
__snake_case = self.get_tokenizer()
__snake_case = CLIPProcessor(tokenizer=_UpperCamelCase , image_processor=_UpperCamelCase )
__snake_case = """lower newer"""
__snake_case = self.prepare_image_inputs()
__snake_case = processor(text=_UpperCamelCase , images=_UpperCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 268
| 1
|
'''simple docstring'''
# This script creates a super tiny model that is useful inside tests, when we just want to test that
# the machinery works, without needing to the check the quality of the outcomes.
#
# This version creates a tiny model through reduction of a normal pre-trained model, but keeping the
# full vocab, merges file, and thus also resulting in a larger model due to a large vocab size.
# This gives ~3MB in total for all files.
#
# If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated
#
#
# It will be used then as "stas/tiny-wmt19-en-de"
# Build
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration
a__ : Optional[Any] = 'facebook/wmt19-en-de'
a__ : Any = FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
a__ : str = FSMTConfig.from_pretrained(mname)
config.update(
dict(
d_model=4,
encoder_layers=1,
decoder_layers=1,
encoder_ffn_dim=4,
decoder_ffn_dim=4,
encoder_attention_heads=1,
decoder_attention_heads=1,
)
)
a__ : Union[str, Any] = FSMTForConditionalGeneration(config)
print(F"""num of params {tiny_model.num_parameters()}""")
# Test
a__ : Dict = tokenizer(['Making tiny model'], return_tensors='pt')
a__ : Union[str, Any] = tiny_model(**batch)
print('test output:', len(outputs.logits[0]))
# Save
a__ : Tuple = 'tiny-wmt19-en-de'
tiny_model.half() # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)
print(F"""Generated {mname_tiny}""")
# Upload
# transformers-cli upload tiny-wmt19-en-de
| 711
|
'''simple docstring'''
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow
from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class lowerCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ):
'''simple docstring'''
_lowerCamelCase =StableDiffusionInpaintPipeline
_lowerCamelCase =TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
_lowerCamelCase =TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
_lowerCamelCase =frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
_lowerCamelCase =frozenset([] )
def __snake_case ( self : List[str] ):
torch.manual_seed(0 )
UpperCAmelCase = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a__ , )
UpperCAmelCase = PNDMScheduler(skip_prk_steps=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-0_5 , 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,
'''safety_checker''': None,
'''feature_extractor''': None,
}
return components
def __snake_case ( self : Dict , a__ : List[Any] , a__ : Tuple=0 ):
# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(a__ ) ).to(a__ )
UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0]
UpperCAmelCase = Image.fromarray(np.uinta(a__ ) ).convert('''RGB''' ).resize((64, 64) )
UpperCAmelCase = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) )
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''',
'''image''': init_image,
'''mask_image''': mask_image,
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
}
return inputs
def __snake_case ( self : int ):
UpperCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
UpperCAmelCase = self.get_dummy_components()
UpperCAmelCase = StableDiffusionInpaintPipeline(**a__ )
UpperCAmelCase = sd_pipe.to(a__ )
sd_pipe.set_progress_bar_config(disable=a__ )
UpperCAmelCase = self.get_dummy_inputs(a__ )
UpperCAmelCase = sd_pipe(**a__ ).images
UpperCAmelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
UpperCAmelCase = np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def __snake_case ( self : List[Any] ):
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
@slow
@require_torch_gpu
class lowerCAmelCase__ ( unittest.TestCase ):
'''simple docstring'''
def __snake_case ( self : Optional[int] ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __snake_case ( self : Any ):
UpperCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
UpperCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
UpperCAmelCase = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
'''/yellow_cat_sitting_on_a_park_bench.npy''' )
UpperCAmelCase = '''stabilityai/stable-diffusion-2-inpainting'''
UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained(a__ , safety_checker=a__ )
pipe.to(a__ )
pipe.set_progress_bar_config(disable=a__ )
pipe.enable_attention_slicing()
UpperCAmelCase = '''Face of a yellow cat, high resolution, sitting on a park bench'''
UpperCAmelCase = torch.manual_seed(0 )
UpperCAmelCase = pipe(
prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , output_type='''np''' , )
UpperCAmelCase = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 9e-3
def __snake_case ( self : int ):
UpperCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
UpperCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
UpperCAmelCase = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
'''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' )
UpperCAmelCase = '''stabilityai/stable-diffusion-2-inpainting'''
UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained(
a__ , torch_dtype=torch.floataa , safety_checker=a__ , )
pipe.to(a__ )
pipe.set_progress_bar_config(disable=a__ )
pipe.enable_attention_slicing()
UpperCAmelCase = '''Face of a yellow cat, high resolution, sitting on a park bench'''
UpperCAmelCase = torch.manual_seed(0 )
UpperCAmelCase = pipe(
prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , output_type='''np''' , )
UpperCAmelCase = output.images[0]
assert image.shape == (512, 512, 3)
assert np.abs(expected_image - image ).max() < 5e-1
def __snake_case ( self : List[str] ):
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
UpperCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/sd2-inpaint/init_image.png''' )
UpperCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' )
UpperCAmelCase = '''stabilityai/stable-diffusion-2-inpainting'''
UpperCAmelCase = PNDMScheduler.from_pretrained(a__ , subfolder='''scheduler''' )
UpperCAmelCase = StableDiffusionInpaintPipeline.from_pretrained(
a__ , safety_checker=a__ , scheduler=a__ , torch_dtype=torch.floataa , )
pipe.to(a__ )
pipe.set_progress_bar_config(disable=a__ )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
UpperCAmelCase = '''Face of a yellow cat, high resolution, sitting on a park bench'''
UpperCAmelCase = torch.manual_seed(0 )
UpperCAmelCase = pipe(
prompt=a__ , image=a__ , mask_image=a__ , generator=a__ , num_inference_steps=2 , output_type='''np''' , )
UpperCAmelCase = torch.cuda.max_memory_allocated()
# make sure that less than 2.65 GB is allocated
assert mem_bytes < 2.65 * 10**9
| 570
| 0
|
"""simple docstring"""
from sklearn.metrics import fa_score
import datasets
__lowerCamelCase = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n"
__lowerCamelCase = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n"
__lowerCamelCase = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _lowercase ( datasets.Metric ):
def lowerCAmelCase__ ( self ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Sequence(datasets.Value('''int32''' ) ),
'''references''': datasets.Sequence(datasets.Value('''int32''' ) ),
}
if self.config_name == '''multilabel'''
else {
'''predictions''': datasets.Value('''int32''' ),
'''references''': datasets.Value('''int32''' ),
} ) , reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'''] , )
def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None , UpperCamelCase_=1 , UpperCamelCase_="binary" , UpperCamelCase_=None ):
__magic_name__ = fa_score(
UpperCamelCase_ , UpperCamelCase_ , labels=UpperCamelCase_ , pos_label=UpperCamelCase_ , average=UpperCamelCase_ , sample_weight=UpperCamelCase_ )
return {"f1": float(UpperCamelCase_ ) if score.size == 1 else score}
| 490
|
"""simple docstring"""
import argparse
import logging
import os
import sys
import numpy as np
import onnxruntime
import torch
from bart_onnx.generation_onnx import BARTBeamSearchGenerator
from bart_onnx.reduce_onnx_size import remove_dup_initializers
import transformers
from transformers import BartForConditionalGeneration, BartTokenizer
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=os.environ.get("LOGLEVEL", "INFO").upper(),
stream=sys.stdout,
)
__lowerCamelCase = logging.getLogger(__name__)
__lowerCamelCase = {"facebook/bart-base": BartForConditionalGeneration}
__lowerCamelCase = {"facebook/bart-base": BartTokenizer}
def lowercase ( ) -> List[str]:
__magic_name__ = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' )
parser.add_argument(
'''--validation_file''' , type=__UpperCamelCase , default=__UpperCamelCase , help='''A csv or a json file containing the validation data.''' )
parser.add_argument(
'''--max_length''' , type=__UpperCamelCase , default=5 , help='''The maximum total input sequence length after tokenization.''' , )
parser.add_argument(
'''--num_beams''' , type=__UpperCamelCase , default=__UpperCamelCase , help=(
'''Number of beams to use for evaluation. This argument will be '''
'''passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.'''
) , )
parser.add_argument(
'''--model_name_or_path''' , type=__UpperCamelCase , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=__UpperCamelCase , )
parser.add_argument(
'''--config_name''' , type=__UpperCamelCase , default=__UpperCamelCase , help='''Pretrained config name or path if not the same as model_name''' , )
parser.add_argument(
'''--device''' , type=__UpperCamelCase , default='''cpu''' , help='''Device where the model will be run''' , )
parser.add_argument('''--output_file_path''' , type=__UpperCamelCase , default=__UpperCamelCase , help='''Where to store the final ONNX file.''' )
__magic_name__ = parser.parse_args()
return args
def lowercase ( __UpperCamelCase , __UpperCamelCase="cpu" ) -> int:
__magic_name__ = model_dict[model_name].from_pretrained(__UpperCamelCase ).to(__UpperCamelCase )
__magic_name__ = tokenizer_dict[model_name].from_pretrained(__UpperCamelCase )
if model_name in ["facebook/bart-base"]:
__magic_name__ = 0
__magic_name__ = None
__magic_name__ = 0
return huggingface_model, tokenizer
def lowercase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Any:
model.eval()
__magic_name__ = None
__magic_name__ = torch.jit.script(BARTBeamSearchGenerator(__UpperCamelCase ) )
with torch.no_grad():
__magic_name__ = '''My friends are cool but they eat too many carbs.'''
__magic_name__ = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors='''pt''' ).to(model.device )
__magic_name__ = model.generate(
inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , num_beams=__UpperCamelCase , max_length=__UpperCamelCase , early_stopping=__UpperCamelCase , decoder_start_token_id=model.config.decoder_start_token_id , )
torch.onnx.export(
__UpperCamelCase , (
inputs['''input_ids'''],
inputs['''attention_mask'''],
num_beams,
max_length,
model.config.decoder_start_token_id,
) , __UpperCamelCase , opset_version=14 , input_names=['''input_ids''', '''attention_mask''', '''num_beams''', '''max_length''', '''decoder_start_token_id'''] , output_names=['''output_ids'''] , dynamic_axes={
'''input_ids''': {0: '''batch''', 1: '''seq'''},
'''output_ids''': {0: '''batch''', 1: '''seq_out'''},
} , example_outputs=__UpperCamelCase , )
logger.info('''Model exported to {}'''.format(__UpperCamelCase ) )
__magic_name__ = remove_dup_initializers(os.path.abspath(__UpperCamelCase ) )
logger.info('''Deduplicated and optimized model written to {}'''.format(__UpperCamelCase ) )
__magic_name__ = onnxruntime.InferenceSession(__UpperCamelCase )
__magic_name__ = ort_sess.run(
__UpperCamelCase , {
'''input_ids''': inputs['''input_ids'''].cpu().numpy(),
'''attention_mask''': inputs['''attention_mask'''].cpu().numpy(),
'''num_beams''': np.array(__UpperCamelCase ),
'''max_length''': np.array(__UpperCamelCase ),
'''decoder_start_token_id''': np.array(model.config.decoder_start_token_id ),
} , )
np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 )
logger.info('''Model outputs from torch and ONNX Runtime are similar.''' )
logger.info('''Success.''' )
def lowercase ( ) -> Any:
__magic_name__ = parse_args()
__magic_name__ = 5
__magic_name__ = 4
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , )
logger.setLevel(logging.INFO )
transformers.utils.logging.set_verbosity_error()
__magic_name__ = torch.device(args.device )
__magic_name__ , __magic_name__ = load_model_tokenizer(args.model_name_or_path , __UpperCamelCase )
if model.config.decoder_start_token_id is None:
raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' )
model.to(__UpperCamelCase )
if args.max_length:
__magic_name__ = args.max_length
if args.num_beams:
__magic_name__ = args.num_beams
if args.output_file_path:
__magic_name__ = args.output_file_path
else:
__magic_name__ = '''BART.onnx'''
logger.info('''Exporting model to ONNX''' )
export_and_validate_model(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
if __name__ == "__main__":
main()
| 490
| 1
|
import copy
import tempfile
import unittest
from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder
def __SCREAMING_SNAKE_CASE ( UpperCamelCase : str , UpperCamelCase : Dict , UpperCamelCase : List[Any] , UpperCamelCase : Dict=None , UpperCamelCase : Tuple=None , UpperCamelCase : List[str]=None , UpperCamelCase : List[str]=None , UpperCamelCase : List[str]=None , ) -> Union[str, Any]:
"""simple docstring"""
if attention_mask is None:
a_ = input_ids.ne(config.pad_token_id )
if decoder_attention_mask is None:
a_ = decoder_input_ids.ne(config.pad_token_id )
if head_mask is None:
a_ = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=snake_case_ )
if decoder_head_mask is None:
a_ = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=snake_case_ )
if cross_attn_head_mask is None:
a_ = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=snake_case_ )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
class lowerCamelCase_ :
def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=20 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , ):
a_ = parent
a_ = batch_size
a_ = seq_length
a_ = is_training
a_ = use_labels
a_ = vocab_size
a_ = hidden_size
a_ = num_hidden_layers
a_ = num_attention_heads
a_ = intermediate_size
a_ = hidden_act
a_ = hidden_dropout_prob
a_ = attention_probs_dropout_prob
a_ = encoder_layerdrop
a_ = decoder_layerdrop
a_ = max_position_embeddings
a_ = eos_token_id
a_ = pad_token_id
a_ = bos_token_id
def __magic_name__ ( self ):
a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
a_ = self.eos_token_id # Eos Token
a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
# we need to clamp the input ids here to avoid having pad token in between
# this is because for M2M100 the position_ids are prepared such that
# all pad tokens have pos id = 2 and rest are between 2..seq_length
# and the seq_length here is seq_length - num_pad_tokens
# but when using past, there is no way of knowing if the past input ids had
# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
# position_ids being off by num_pad_tokens in past input
a_ = input_ids.clamp(self.pad_token_id + 1 )
a_ = decoder_input_ids.clamp(self.pad_token_id + 1 )
a_ = self.get_config()
a_ = prepare_mam_aaa_inputs_dict(__A , __A , __A )
return config, inputs_dict
def __magic_name__ ( self ):
return MaMaaaConfig(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , )
def __magic_name__ ( self ):
a_ = self.prepare_config_and_inputs()
return config, inputs_dict
def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
a_ = MaMaaaModel(config=__A ).get_decoder().to(__A ).eval()
a_ = inputs_dict["input_ids"]
a_ = inputs_dict["attention_mask"]
a_ = inputs_dict["head_mask"]
# first forward pass
a_ = model(__A , attention_mask=__A , head_mask=__A , use_cache=__A )
a_ = outputs.to_tuple()
# create hypothetical multiple next token and extent to next_input_ids
a_ = ids_tensor((self.batch_size, 3) , config.vocab_size )
a_ = ids_tensor((self.batch_size, 3) , 2 )
# append to next input_ids and
a_ = torch.cat([input_ids, next_tokens] , dim=-1 )
a_ = torch.cat([attention_mask, next_attn_mask] , dim=-1 )
a_ = model(__A , attention_mask=__A )["last_hidden_state"]
a_ = model(__A , attention_mask=__A , past_key_values=__A )[
"last_hidden_state"
]
# select random slice
a_ = ids_tensor((1,) , output_from_past.shape[-1] ).item()
a_ = output_from_no_past[:, -3:, random_slice_idx].detach()
a_ = 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(__A , __A , atol=1E-2 ) )
def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
a_ = MaMaaaModel(config=__A ).to(__A ).eval()
a_ = model(**__A )
a_ = outputs.encoder_last_hidden_state
a_ = outputs.last_hidden_state
with tempfile.TemporaryDirectory() as tmpdirname:
a_ = model.get_encoder()
encoder.save_pretrained(__A )
a_ = MaMaaaEncoder.from_pretrained(__A ).to(__A )
a_ = encoder(inputs_dict["""input_ids"""] , attention_mask=inputs_dict["""attention_mask"""] )[
0
]
self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 )
with tempfile.TemporaryDirectory() as tmpdirname:
a_ = model.get_decoder()
decoder.save_pretrained(__A )
a_ = MaMaaaDecoder.from_pretrained(__A ).to(__A )
a_ = decoder(
input_ids=inputs_dict["""decoder_input_ids"""] , attention_mask=inputs_dict["""decoder_attention_mask"""] , encoder_hidden_states=__A , encoder_attention_mask=inputs_dict["""attention_mask"""] , )[0]
self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 )
@require_torch
class lowerCamelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
_lowerCamelCase : Optional[Any] = (
(
MaMaaaModel,
MaMaaaForConditionalGeneration,
)
if is_torch_available()
else ()
)
_lowerCamelCase : List[Any] = (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
_lowerCamelCase : Tuple = (
{
"""conversational""": MaMaaaForConditionalGeneration,
"""feature-extraction""": MaMaaaModel,
"""summarization""": MaMaaaForConditionalGeneration,
"""text2text-generation""": MaMaaaForConditionalGeneration,
"""translation""": MaMaaaForConditionalGeneration,
}
if is_torch_available()
else {}
)
_lowerCamelCase : List[Any] = True
_lowerCamelCase : Any = True
_lowerCamelCase : str = False
_lowerCamelCase : List[str] = False
def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
if pipeline_test_casse_name == "TranslationPipelineTests":
# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
return True
return False
def __magic_name__ ( self ):
a_ = MaMaaaModelTester(self )
a_ = ConfigTester(self , config_class=__A )
def __magic_name__ ( self ):
self.config_tester.run_common_tests()
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
a_ = model_class(__A )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(__A )
a_ = model_class.from_pretrained(__A , output_loading_info=__A )
self.assertEqual(info["""missing_keys"""] , [] )
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(*__A )
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_encoder_decoder_model_standalone(*__A )
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
a_ = model_class(__A )
model.to(__A )
model.eval()
a_ = copy.deepcopy(self._prepare_for_class(__A , __A ) )
if not self.is_encoder_decoder:
a_ = inputs["input_ids"]
del inputs["input_ids"]
else:
a_ = inputs["input_ids"]
a_ = inputs.get("""decoder_input_ids""" , __A )
del inputs["input_ids"]
inputs.pop("""decoder_input_ids""" , __A )
a_ = model.get_input_embeddings()
if not self.is_encoder_decoder:
a_ = wte(__A )
else:
a_ = wte(__A )
a_ = wte(__A )
with torch.no_grad():
model(**__A )[0]
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs()
a_ = input_dict["input_ids"]
a_ = input_ids.ne(1 ).to(__A )
a_ = MaMaaaForConditionalGeneration(__A ).eval().to(__A )
if torch_device == "cuda":
model.half()
model.generate(__A , attention_mask=__A )
model.generate(num_beams=4 , do_sample=__A , early_stopping=__A , num_return_sequences=3 )
def __SCREAMING_SNAKE_CASE ( UpperCamelCase : int ) -> List[Any]:
"""simple docstring"""
return torch.tensor(snake_case_ , dtype=torch.long , device=snake_case_ )
_A = 1e-4
@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class lowerCamelCase_ ( unittest.TestCase ):
@cached_property
def __magic_name__ ( self ):
return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" )
def __magic_name__ ( self ):
a_ = MaMaaaModel.from_pretrained("""facebook/m2m100_418M""" ).to(__A )
a_ = _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]] )
a_ = _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]] )
a_ = prepare_mam_aaa_inputs_dict(model.config , __A , __A )
with torch.no_grad():
a_ = model(**__A )[0]
a_ = torch.Size((1, 11, 1024) )
self.assertEqual(output.shape , __A )
# change to expected output here
a_ = torch.tensor(
[[-0.7_7_8_0, -0.1_6_7_6, 0.1_0_3_8], [-6.7_5_5_6, -1.3_9_9_2, 0.0_5_6_7], [-7.5_3_8_3, -0.5_9_2_0, -0.2_7_7_9]] , device=__A )
self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=__A ) )
def __magic_name__ ( self ):
a_ = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(__A )
# change to intended input
a_ = _long_tensor([[12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38, 2]] )
a_ = _long_tensor([[2, 12_8028, 98, 12, 3_0527, 2732, 159, 7755, 6_1904, 3_9144, 38]] )
a_ = prepare_mam_aaa_inputs_dict(model.config , __A , __A )
with torch.no_grad():
a_ = model(**__A )[0]
a_ = torch.Size((1, 11, model.config.vocab_size) )
self.assertEqual(output.shape , __A )
# change to expected output here
a_ = torch.tensor(
[[-1.0_4_4_8, -1.0_4_1_1, 3.7_9_9_2], [-3.2_1_9_1, -3.2_3_8_6, -1.3_4_5_1], [-3.6_2_1_0, -3.5_9_9_3, 0.4_9_2_5]] , device=__A )
self.assertTrue(torch.allclose(output[:, :3, :3] , __A , atol=__A ) )
def __magic_name__ ( self ):
a_ = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(__A )
a_ = MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" , src_lang="""fr""" , tgt_lang="""en""" )
a_ = [
"L'affaire NSA souligne l'absence totale de débat sur le renseignement",
"Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.",
"Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"
" Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"
" l'ampleur de la surveillance américaine sur l'ensemble des communications en France.",
]
# The below article tests that we don't add any hypotheses outside of the top n_beams
a_ = tokenizer(__A , padding=__A , return_tensors="""pt""" )
a_ = model.generate(
input_ids=dct["""input_ids"""].to(__A ) , attention_mask=dct["""attention_mask"""].to(__A ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id("""en""" ) , )
a_ = [
"The NSA case highlights the total absence of intelligence debate",
"I think there are two levels of response from the French government.",
"When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."
" Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"
" communications in France.",
]
a_ = tokenizer.batch_decode(
hypotheses_batch.tolist() , clean_up_tokenization_spaces=__A , skip_special_tokens=__A )
assert generated == expected_en
| 703
|
import copy
import inspect
import unittest
from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
require_torch,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import SwiftFormerForImageClassification, SwiftFormerModel
from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import ViTImageProcessor
class lowerCamelCase_ :
def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=224 , _SCREAMING_SNAKE_CASE=1000 , _SCREAMING_SNAKE_CASE=[3, 3, 6, 4] , _SCREAMING_SNAKE_CASE=[48, 56, 112, 220] , ):
a_ = parent
a_ = batch_size
a_ = num_channels
a_ = is_training
a_ = use_labels
a_ = hidden_dropout_prob
a_ = attention_probs_dropout_prob
a_ = num_labels
a_ = image_size
a_ = layer_depths
a_ = embed_dims
def __magic_name__ ( self ):
a_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
a_ = None
if self.use_labels:
a_ = ids_tensor([self.batch_size] , self.num_labels )
a_ = self.get_config()
return config, pixel_values, labels
def __magic_name__ ( self ):
return SwiftFormerConfig(
depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=_SCREAMING_SNAKE_CASE , layer_scale_init_value=1E-5 , )
def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
a_ = SwiftFormerModel(config=_SCREAMING_SNAKE_CASE )
model.to(_SCREAMING_SNAKE_CASE )
model.eval()
a_ = model(_SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) )
def __magic_name__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
a_ = self.num_labels
a_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE )
model.to(_SCREAMING_SNAKE_CASE )
model.eval()
a_ = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
a_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE )
model.to(_SCREAMING_SNAKE_CASE )
model.eval()
a_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
a_ = model(_SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __magic_name__ ( self ):
((a_) , (a_) , (a_)) = self.prepare_config_and_inputs()
a_ = {"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowerCamelCase : List[Any] = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
_lowerCamelCase : Optional[Any] = (
{"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification}
if is_torch_available()
else {}
)
_lowerCamelCase : Optional[Any] = False
_lowerCamelCase : Dict = False
_lowerCamelCase : Any = False
_lowerCamelCase : Tuple = False
_lowerCamelCase : List[Any] = False
def __magic_name__ ( self ):
a_ = SwiftFormerModelTester(self )
a_ = ConfigTester(
self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , )
def __magic_name__ ( self ):
self.config_tester.run_common_tests()
@unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" )
def __magic_name__ ( self ):
pass
def __magic_name__ ( self ):
a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ = model_class(_SCREAMING_SNAKE_CASE )
a_ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) )
def __magic_name__ ( self ):
a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ = model_class(_SCREAMING_SNAKE_CASE )
a_ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a_ = [*signature.parameters.keys()]
a_ = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE )
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE )
def __magic_name__ ( self ):
a_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE )
@slow
def __magic_name__ ( self ):
for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
a_ = SwiftFormerModel.from_pretrained(_SCREAMING_SNAKE_CASE )
self.assertIsNotNone(_SCREAMING_SNAKE_CASE )
@unittest.skip(reason="""SwiftFormer does not output attentions""" )
def __magic_name__ ( self ):
pass
def __magic_name__ ( self ):
def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
a_ = model_class(_SCREAMING_SNAKE_CASE )
model.to(_SCREAMING_SNAKE_CASE )
model.eval()
with torch.no_grad():
a_ = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
a_ = outputs.hidden_states
a_ = 8
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # TODO
# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
# with the width and height being successively divided by 2, after every 2 blocks
for i in range(len(_SCREAMING_SNAKE_CASE ) ):
self.assertEqual(
hidden_states[i].shape , torch.Size(
[
self.model_tester.batch_size,
self.model_tester.embed_dims[i // 2],
(self.model_tester.image_size // 4) // 2 ** (i // 2),
(self.model_tester.image_size // 4) // 2 ** (i // 2),
] ) , )
a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a_ = True
check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
a_ = True
check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def __magic_name__ ( self ):
def _config_zero_init(_SCREAMING_SNAKE_CASE ):
a_ = copy.deepcopy(_SCREAMING_SNAKE_CASE )
for key in configs_no_init.__dict__.keys():
if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 1E-10 )
if isinstance(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ):
a_ = _config_zero_init(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
return configs_no_init
a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common()
a_ = _config_zero_init(_SCREAMING_SNAKE_CASE )
for model_class in self.all_model_classes:
a_ = model_class(config=_SCREAMING_SNAKE_CASE )
for name, param in model.named_parameters():
if param.requires_grad:
self.assertIn(
((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , )
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def __magic_name__ ( self ):
pass
def __SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
"""simple docstring"""
a_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_torch
@require_vision
class lowerCamelCase_ ( unittest.TestCase ):
@cached_property
def __magic_name__ ( self ):
return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None
@slow
def __magic_name__ ( self ):
a_ = SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(_SCREAMING_SNAKE_CASE )
a_ = self.default_image_processor
a_ = prepare_img()
a_ = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(_SCREAMING_SNAKE_CASE )
# forward pass
with torch.no_grad():
a_ = model(**_SCREAMING_SNAKE_CASE )
# verify the logits
a_ = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE )
a_ = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(_SCREAMING_SNAKE_CASE )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) )
| 403
| 0
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCAmelCase_ = {
"configuration_xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMOnnxConfig"],
"tokenization_xlm": ["XLMTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ = [
"XLM_PRETRAINED_MODEL_ARCHIVE_LIST",
"XLMForMultipleChoice",
"XLMForQuestionAnswering",
"XLMForQuestionAnsweringSimple",
"XLMForSequenceClassification",
"XLMForTokenClassification",
"XLMModel",
"XLMPreTrainedModel",
"XLMWithLMHeadModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ = [
"TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFXLMForMultipleChoice",
"TFXLMForQuestionAnsweringSimple",
"TFXLMForSequenceClassification",
"TFXLMForTokenClassification",
"TFXLMMainLayer",
"TFXLMModel",
"TFXLMPreTrainedModel",
"TFXLMWithLMHeadModel",
]
if TYPE_CHECKING:
from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig
from .tokenization_xlm import XLMTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlm import (
XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
XLMForMultipleChoice,
XLMForQuestionAnswering,
XLMForQuestionAnsweringSimple,
XLMForSequenceClassification,
XLMForTokenClassification,
XLMModel,
XLMPreTrainedModel,
XLMWithLMHeadModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xlm import (
TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXLMForMultipleChoice,
TFXLMForQuestionAnsweringSimple,
TFXLMForSequenceClassification,
TFXLMForTokenClassification,
TFXLMMainLayer,
TFXLMModel,
TFXLMPreTrainedModel,
TFXLMWithLMHeadModel,
)
else:
import sys
UpperCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 32
|
def __lowerCamelCase ( _lowerCAmelCase ) -> str:
_UpperCAmelCase = []
_UpperCAmelCase = set({"(", "[", "{"} )
_UpperCAmelCase = set({")", "]", "}"} )
_UpperCAmelCase = {"{": "}", "[": "]", "(": ")"}
for i in range(len(_lowerCAmelCase ) ):
if s[i] in open_brackets:
stack.append(s[i] )
elif s[i] in closed_brackets and (
len(_lowerCAmelCase ) == 0 or (len(_lowerCAmelCase ) > 0 and open_to_closed[stack.pop()] != s[i])
):
return False
return len(_lowerCAmelCase ) == 0
def __lowerCamelCase ( ) -> str:
_UpperCAmelCase = input("Enter sequence of brackets: " )
if is_balanced(_lowerCAmelCase ):
print(_lowerCAmelCase , "is balanced" )
else:
print(_lowerCAmelCase , "is not balanced" )
if __name__ == "__main__":
main()
| 684
| 0
|
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
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 (
TF_MODEL_FOR_PRETRAINING_MAPPING,
TFMobileBertForMaskedLM,
TFMobileBertForMultipleChoice,
TFMobileBertForNextSentencePrediction,
TFMobileBertForPreTraining,
TFMobileBertForQuestionAnswering,
TFMobileBertForSequenceClassification,
TFMobileBertForTokenClassification,
TFMobileBertModel,
)
@require_tf
class lowerCAmelCase ( a , a , unittest.TestCase ):
"""simple docstring"""
__lowercase :List[Any] = (
(
TFMobileBertModel,
TFMobileBertForMaskedLM,
TFMobileBertForNextSentencePrediction,
TFMobileBertForPreTraining,
TFMobileBertForQuestionAnswering,
TFMobileBertForSequenceClassification,
TFMobileBertForTokenClassification,
TFMobileBertForMultipleChoice,
)
if is_tf_available()
else ()
)
__lowercase :Optional[int] = (
{
"feature-extraction": TFMobileBertModel,
"fill-mask": TFMobileBertForMaskedLM,
"question-answering": TFMobileBertForQuestionAnswering,
"text-classification": TFMobileBertForSequenceClassification,
"token-classification": TFMobileBertForTokenClassification,
"zero-shot": TFMobileBertForSequenceClassification,
}
if is_tf_available()
else {}
)
__lowercase :List[Any] = False
__lowercase :List[str] = False
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=False ) -> int:
'''simple docstring'''
lowerCamelCase_ = super()._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ )
if return_labels:
if model_class in get_values(UpperCamelCase__ ):
lowerCamelCase_ = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa )
return inputs_dict
class lowerCAmelCase ( a ):
"""simple docstring"""
def __init__( self , UpperCamelCase__ , UpperCamelCase__=13 , UpperCamelCase__=7 , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=True , UpperCamelCase__=99 , UpperCamelCase__=32 , UpperCamelCase__=32 , UpperCamelCase__=2 , UpperCamelCase__=4 , UpperCamelCase__=37 , UpperCamelCase__="gelu" , UpperCamelCase__=0.1 , UpperCamelCase__=0.1 , UpperCamelCase__=512 , UpperCamelCase__=16 , UpperCamelCase__=2 , UpperCamelCase__=0.02 , UpperCamelCase__=3 , UpperCamelCase__=4 , UpperCamelCase__=None , ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = parent
lowerCamelCase_ = batch_size
lowerCamelCase_ = seq_length
lowerCamelCase_ = is_training
lowerCamelCase_ = use_input_mask
lowerCamelCase_ = use_token_type_ids
lowerCamelCase_ = use_labels
lowerCamelCase_ = vocab_size
lowerCamelCase_ = hidden_size
lowerCamelCase_ = num_hidden_layers
lowerCamelCase_ = num_attention_heads
lowerCamelCase_ = intermediate_size
lowerCamelCase_ = hidden_act
lowerCamelCase_ = hidden_dropout_prob
lowerCamelCase_ = attention_probs_dropout_prob
lowerCamelCase_ = max_position_embeddings
lowerCamelCase_ = type_vocab_size
lowerCamelCase_ = type_sequence_label_size
lowerCamelCase_ = initializer_range
lowerCamelCase_ = num_labels
lowerCamelCase_ = num_choices
lowerCamelCase_ = scope
lowerCamelCase_ = embedding_size
def _lowerCAmelCase ( self ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCamelCase_ = None
if self.use_input_mask:
lowerCamelCase_ = random_attention_mask([self.batch_size, self.seq_length] )
lowerCamelCase_ = None
if self.use_token_type_ids:
lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
lowerCamelCase_ = None
lowerCamelCase_ = None
lowerCamelCase_ = None
if self.use_labels:
lowerCamelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowerCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
lowerCamelCase_ = ids_tensor([self.batch_size] , self.num_choices )
lowerCamelCase_ = 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 , 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 , embedding_size=self.embedding_size , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Tuple:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertModel(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
lowerCamelCase_ = [input_ids, input_mask]
lowerCamelCase_ = model(UpperCamelCase__ )
lowerCamelCase_ = model(UpperCamelCase__ )
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 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertForMaskedLM(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertForNextSentencePrediction(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) )
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertForPreTraining(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
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 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = self.num_labels
lowerCamelCase_ = TFMobileBertForSequenceClassification(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = self.num_choices
lowerCamelCase_ = TFMobileBertForMultipleChoice(config=UpperCamelCase__ )
lowerCamelCase_ = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) )
lowerCamelCase_ = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) )
lowerCamelCase_ = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) )
lowerCamelCase_ = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
lowerCamelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> str:
'''simple docstring'''
lowerCamelCase_ = self.num_labels
lowerCamelCase_ = TFMobileBertForTokenClassification(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertForQuestionAnswering(config=UpperCamelCase__ )
lowerCamelCase_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
lowerCamelCase_ = model(UpperCamelCase__ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _lowerCAmelCase ( self ) -> int:
'''simple docstring'''
lowerCamelCase_ = self.prepare_config_and_inputs()
(
(
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) , (
lowerCamelCase_
) ,
) = config_and_inputs
lowerCamelCase_ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
def _lowerCAmelCase ( self ) -> List[str]:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertModelTest.TFMobileBertModelTester(self )
lowerCamelCase_ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 )
def _lowerCAmelCase ( self ) -> Optional[int]:
'''simple docstring'''
self.config_tester.run_common_tests()
def _lowerCAmelCase ( self ) -> int:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_model(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> List[str]:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> Dict:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCamelCase__ )
def _lowerCAmelCase ( self ) -> Tuple:
'''simple docstring'''
lowerCamelCase_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCamelCase__ )
@slow
def _lowerCAmelCase ( self ) -> Optional[Any]:
'''simple docstring'''
for model_name in ["google/mobilebert-uncased"]:
lowerCamelCase_ = TFMobileBertModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
@require_tf
class lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
@slow
def _lowerCAmelCase ( self ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''' )
lowerCamelCase_ = tf.constant([[0, 1, 2, 3, 4, 5]] )
lowerCamelCase_ = model(UpperCamelCase__ )[0]
lowerCamelCase_ = [1, 6, 30_522]
self.assertEqual(output.shape , UpperCamelCase__ )
lowerCamelCase_ = tf.constant(
[
[
[-4.5_919_547, -9.248_295, -9.645_256],
[-6.7_306_175, -6.440_284, -6.6_052_837],
[-7.2_743_506, -6.7_847_915, -6.024_673],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , UpperCamelCase__ , atol=1e-4 )
| 712
|
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaImgaImgPipeline,
KandinskyVaaPriorPipeline,
UNetaDConditionModel,
VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class lowerCAmelCase ( a , unittest.TestCase ):
"""simple docstring"""
__lowercase :Optional[int] = KandinskyVaaImgaImgPipeline
__lowercase :Dict = ["image_embeds", "negative_image_embeds", "image"]
__lowercase :Union[str, Any] = [
"image_embeds",
"negative_image_embeds",
"image",
]
__lowercase :str = [
"generator",
"height",
"width",
"strength",
"guidance_scale",
"num_inference_steps",
"return_dict",
"guidance_scale",
"num_images_per_prompt",
"output_type",
"return_dict",
]
__lowercase :Union[str, Any] = False
@property
def _lowerCAmelCase ( self ) -> str:
'''simple docstring'''
return 32
@property
def _lowerCAmelCase ( self ) -> List[str]:
'''simple docstring'''
return 32
@property
def _lowerCAmelCase ( self ) -> List[str]:
'''simple docstring'''
return self.time_input_dim
@property
def _lowerCAmelCase ( self ) -> str:
'''simple docstring'''
return self.time_input_dim * 4
@property
def _lowerCAmelCase ( self ) -> Tuple:
'''simple docstring'''
return 100
@property
def _lowerCAmelCase ( self ) -> str:
'''simple docstring'''
torch.manual_seed(0 )
lowerCamelCase_ = {
'''in_channels''': 4,
# Out channels is double in channels because predicts mean and variance
'''out_channels''': 8,
'''addition_embed_type''': '''image''',
'''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
'''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
'''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
'''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
'''layers_per_block''': 1,
'''encoder_hid_dim''': self.text_embedder_hidden_size,
'''encoder_hid_dim_type''': '''image_proj''',
'''cross_attention_dim''': self.cross_attention_dim,
'''attention_head_dim''': 4,
'''resnet_time_scale_shift''': '''scale_shift''',
'''class_embed_type''': None,
}
lowerCamelCase_ = UNetaDConditionModel(**UpperCamelCase__ )
return model
@property
def _lowerCAmelCase ( self ) -> List[str]:
'''simple docstring'''
return {
"block_out_channels": [32, 64],
"down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": [
"AttnUpDecoderBlock2D",
"UpDecoderBlock2D",
],
"vq_embed_dim": 4,
}
@property
def _lowerCAmelCase ( self ) -> Union[str, Any]:
'''simple docstring'''
torch.manual_seed(0 )
lowerCamelCase_ = VQModel(**self.dummy_movq_kwargs )
return model
def _lowerCAmelCase ( self ) -> Any:
'''simple docstring'''
lowerCamelCase_ = self.dummy_unet
lowerCamelCase_ = self.dummy_movq
lowerCamelCase_ = {
'''num_train_timesteps''': 1_000,
'''beta_schedule''': '''linear''',
'''beta_start''': 0.00_085,
'''beta_end''': 0.012,
'''clip_sample''': False,
'''set_alpha_to_one''': False,
'''steps_offset''': 0,
'''prediction_type''': '''epsilon''',
'''thresholding''': False,
}
lowerCamelCase_ = DDIMScheduler(**UpperCamelCase__ )
lowerCamelCase_ = {
'''unet''': unet,
'''scheduler''': scheduler,
'''movq''': movq,
}
return components
def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__=0 ) -> Any:
'''simple docstring'''
lowerCamelCase_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ )
lowerCamelCase_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
UpperCamelCase__ )
# create init_image
lowerCamelCase_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ )
lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowerCamelCase_ = Image.fromarray(np.uinta(UpperCamelCase__ ) ).convert('''RGB''' ).resize((256, 256) )
if str(UpperCamelCase__ ).startswith('''mps''' ):
lowerCamelCase_ = torch.manual_seed(UpperCamelCase__ )
else:
lowerCamelCase_ = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ )
lowerCamelCase_ = {
'''image''': init_image,
'''image_embeds''': image_embeds,
'''negative_image_embeds''': negative_image_embeds,
'''generator''': generator,
'''height''': 64,
'''width''': 64,
'''num_inference_steps''': 10,
'''guidance_scale''': 7.0,
'''strength''': 0.2,
'''output_type''': '''np''',
}
return inputs
def _lowerCAmelCase ( self ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase_ = '''cpu'''
lowerCamelCase_ = self.get_dummy_components()
lowerCamelCase_ = self.pipeline_class(**UpperCamelCase__ )
lowerCamelCase_ = pipe.to(UpperCamelCase__ )
pipe.set_progress_bar_config(disable=UpperCamelCase__ )
lowerCamelCase_ = pipe(**self.get_dummy_inputs(UpperCamelCase__ ) )
lowerCamelCase_ = output.images
lowerCamelCase_ = pipe(
**self.get_dummy_inputs(UpperCamelCase__ ) , return_dict=UpperCamelCase__ , )[0]
lowerCamelCase_ = image[0, -3:, -3:, -1]
lowerCamelCase_ = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
lowerCamelCase_ = np.array(
[0.6_199_778, 0.63_984_406, 0.46_145_785, 0.62_944_984, 0.5_622_215, 0.47_306_132, 0.47_441_456, 0.4_607_606, 0.48_719_263] )
assert (
np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""
@slow
@require_torch_gpu
class lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def _lowerCAmelCase ( self ) -> Dict:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _lowerCAmelCase ( self ) -> List[Any]:
'''simple docstring'''
lowerCamelCase_ = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/kandinskyv22/kandinskyv22_img2img_frog.npy''' )
lowerCamelCase_ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' )
lowerCamelCase_ = '''A red cartoon frog, 4k'''
lowerCamelCase_ = KandinskyVaaPriorPipeline.from_pretrained(
'''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa )
pipe_prior.to(UpperCamelCase__ )
lowerCamelCase_ = KandinskyVaaImgaImgPipeline.from_pretrained(
'''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa )
lowerCamelCase_ = pipeline.to(UpperCamelCase__ )
pipeline.set_progress_bar_config(disable=UpperCamelCase__ )
lowerCamelCase_ = torch.Generator(device='''cpu''' ).manual_seed(0 )
lowerCamelCase_ , lowerCamelCase_ = pipe_prior(
UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple()
lowerCamelCase_ = pipeline(
image=UpperCamelCase__ , image_embeds=UpperCamelCase__ , negative_image_embeds=UpperCamelCase__ , generator=UpperCamelCase__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='''np''' , )
lowerCamelCase_ = output.images[0]
assert image.shape == (768, 768, 3)
assert_mean_pixel_difference(UpperCamelCase__ , UpperCamelCase__ )
| 66
| 0
|
'''simple docstring'''
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
__SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
class lowerCAmelCase__ ( A__ ):
"""simple docstring"""
__UpperCamelCase = ["input_features", "is_longer"]
def __init__( self : Optional[int] , A__ : Optional[int]=6_4 , A__ : Optional[Any]=4_8_0_0_0 , A__ : List[Any]=4_8_0 , A__ : Union[str, Any]=1_0 , A__ : List[Any]=1_0_2_4 , A__ : List[Any]=0.0 , A__ : Optional[int]=False , A__ : float = 0 , A__ : float = 1_4_0_0_0 , A__ : int = None , A__ : str = "fusion" , A__ : str = "repeatpad" , **A__ : int , ) -> List[str]:
'''simple docstring'''
super().__init__(
feature_size=__lowerCamelCase , sampling_rate=__lowerCamelCase , padding_value=__lowerCamelCase , return_attention_mask=__lowerCamelCase , **__lowerCamelCase , )
a__ : Dict = top_db
a__ : Optional[int] = truncation
a__ : List[str] = padding
a__ : Union[str, Any] = fft_window_size
a__ : Optional[int] = (fft_window_size >> 1) + 1
a__ : List[str] = hop_length
a__ : List[str] = max_length_s
a__ : Optional[Any] = max_length_s * sampling_rate
a__ : int = sampling_rate
a__ : Tuple = frequency_min
a__ : Optional[int] = frequency_max
a__ : str = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__lowerCamelCase , min_frequency=__lowerCamelCase , max_frequency=__lowerCamelCase , sampling_rate=__lowerCamelCase , norm=__lowerCamelCase , mel_scale='''htk''' , )
a__ : Optional[int] = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__lowerCamelCase , min_frequency=__lowerCamelCase , max_frequency=__lowerCamelCase , sampling_rate=__lowerCamelCase , norm='''slaney''' , mel_scale='''slaney''' , )
def __lowerCAmelCase ( self : Union[str, Any] ) -> Dict[str, Any]:
'''simple docstring'''
a__ : Any = copy.deepcopy(self.__dict__ )
a__ : List[Any] = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
if "mel_filters_slaney" in output:
del output["mel_filters_slaney"]
return output
def __lowerCAmelCase ( self : str , A__ : np.array , A__ : Optional[np.array] = None ) -> np.ndarray:
'''simple docstring'''
a__ : str = spectrogram(
__lowerCamelCase , window_function(self.fft_window_size , '''hann''' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=__lowerCamelCase , log_mel='''dB''' , )
return log_mel_spectrogram.T
def __lowerCAmelCase ( self : str , A__ : int , A__ : int , A__ : List[Any] ) -> Union[str, Any]:
'''simple docstring'''
a__ : Tuple = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 )
if len(ranges[1] ) == 0:
# if the audio is too short, we just use the first chunk
a__ : Union[str, Any] = [0]
if len(ranges[2] ) == 0:
# if the audio is too short, we just use the first chunk
a__ : Union[str, Any] = [0]
# randomly choose index for each part
a__ : Dict = np.random.choice(ranges[0] )
a__ : Union[str, Any] = np.random.choice(ranges[1] )
a__ : List[str] = np.random.choice(ranges[2] )
a__ : Optional[int] = mel[idx_front : idx_front + chunk_frames, :]
a__ : Tuple = mel[idx_middle : idx_middle + chunk_frames, :]
a__ : Any = mel[idx_back : idx_back + chunk_frames, :]
a__ : List[Any] = torch.tensor(mel[None, None, :] )
a__ : str = torch.nn.functional.interpolate(
__lowerCamelCase , size=[chunk_frames, 6_4] , mode='''bilinear''' , align_corners=__lowerCamelCase )
a__ : List[Any] = mel_shrink[0][0].numpy()
a__ : Dict = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 )
return mel_fusion
def __lowerCAmelCase ( self : List[Any] , A__ : np.array , A__ : Dict , A__ : Tuple , A__ : Dict ) -> np.array:
'''simple docstring'''
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
a__ : Union[str, Any] = True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
a__ : Union[str, Any] = len(__lowerCamelCase ) - max_length
a__ : Dict = np.random.randint(0 , overflow + 1 )
a__ : Any = waveform[idx : idx + max_length]
a__ : Any = self._np_extract_fbank_features(__lowerCamelCase , self.mel_filters_slaney )[None, :]
elif truncation == "fusion":
a__ : Optional[int] = self._np_extract_fbank_features(__lowerCamelCase , self.mel_filters )
a__ : int = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
a__ : List[str] = mel.shape[0]
if chunk_frames == total_frames:
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
# In this case, we just use the whole audio.
a__ : str = np.stack([mel, mel, mel, mel] , axis=0 )
a__ : str = False
else:
a__ : Any = self._random_mel_fusion(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
a__ : Optional[int] = True
else:
raise NotImplementedError(F'data_truncating {truncation} not implemented' )
else:
a__ : Tuple = False
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
if waveform.shape[0] < max_length:
if padding == "repeat":
a__ : Tuple = int(max_length / len(__lowerCamelCase ) )
a__ : List[Any] = np.stack(np.tile(__lowerCamelCase , n_repeat + 1 ) )[:max_length]
if padding == "repeatpad":
a__ : Optional[int] = int(max_length / len(__lowerCamelCase ) )
a__ : List[str] = np.stack(np.tile(__lowerCamelCase , __lowerCamelCase ) )
a__ : Optional[Any] = np.pad(__lowerCamelCase , (0, max_length - waveform.shape[0]) , mode='''constant''' , constant_values=0 )
if truncation == "fusion":
a__ : Union[str, Any] = self._np_extract_fbank_features(__lowerCamelCase , self.mel_filters )
a__ : List[Any] = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 )
else:
a__ : List[Any] = self._np_extract_fbank_features(__lowerCamelCase , self.mel_filters_slaney )[None, :]
return input_mel, longer
def __call__( self : Optional[Any] , A__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , A__ : str = None , A__ : Optional[str] = None , A__ : Optional[int] = None , A__ : Optional[int] = None , A__ : Optional[Union[str, TensorType]] = None , **A__ : List[str] , ) -> BatchFeature:
'''simple docstring'''
a__ : Dict = truncation if truncation is not None else self.truncation
a__ : Dict = padding if padding else self.padding
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'
F' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'
F' was sampled with {self.sampling_rate} and not {sampling_rate}.' )
else:
logger.warning(
'''It is strongly recommended to pass the `sampling_rate` argument to this function. '''
'''Failing to do so can result in silent errors that might be hard to debug.''' )
a__ : str = isinstance(__lowerCamelCase , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(F'Only mono-channel audio is supported for input to {self}' )
a__ : Optional[Any] = is_batched_numpy or (
isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
a__ : str = [np.asarray(__lowerCamelCase , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(__lowerCamelCase , np.ndarray ):
a__ : List[Any] = np.asarray(__lowerCamelCase , dtype=np.floataa )
elif isinstance(__lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
a__ : Any = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
a__ : str = [np.asarray(__lowerCamelCase )]
# convert to mel spectrogram, truncate and pad if needed.
a__ : Union[str, Any] = [
self._get_input_mel(__lowerCamelCase , max_length if max_length else self.nb_max_samples , __lowerCamelCase , __lowerCamelCase )
for waveform in raw_speech
]
a__ : str = []
a__ : List[str] = []
for mel, longer in padded_inputs:
input_mel.append(__lowerCamelCase )
is_longer.append(__lowerCamelCase )
if truncation == "fusion" and sum(__lowerCamelCase ) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
a__ : Tuple = np.random.randint(0 , len(__lowerCamelCase ) )
a__ : List[str] = True
if isinstance(input_mel[0] , __lowerCamelCase ):
a__ : Optional[Any] = [np.asarray(__lowerCamelCase , dtype=np.floataa ) for feature in input_mel]
# is_longer is a list of bool
a__ : Dict = [[longer] for longer in is_longer]
a__ : Any = {'''input_features''': input_mel, '''is_longer''': is_longer}
a__ : Optional[int] = BatchFeature(__lowerCamelCase )
if return_tensors is not None:
a__ : Union[str, Any] = input_features.convert_to_tensors(__lowerCamelCase )
return input_features
| 688
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
_SCREAMING_SNAKE_CASE : str = {
'''configuration_swiftformer''': [
'''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''SwiftFormerConfig''',
'''SwiftFormerOnnxConfig''',
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE : Optional[int] = [
'''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''SwiftFormerForImageClassification''',
'''SwiftFormerModel''',
'''SwiftFormerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_swiftformer import (
SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
SwiftFormerConfig,
SwiftFormerOnnxConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swiftformer import (
SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
SwiftFormerForImageClassification,
SwiftFormerModel,
SwiftFormerPreTrainedModel,
)
else:
import sys
_SCREAMING_SNAKE_CASE : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 493
| 0
|
import os
import re
import warnings
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
if TYPE_CHECKING:
from ...tokenization_utils_base import TextInput
from ...utils import logging
lowerCAmelCase = logging.get_logger(__name__)
lowerCAmelCase = {'vocab_file': 'spiece.model'}
lowerCAmelCase = {
'vocab_file': {
't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model',
't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model',
't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model',
't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model',
't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model',
}
}
# TODO(PVP) - this should be removed in Transformers v5
lowerCAmelCase = {
't5-small': 512,
't5-base': 512,
't5-large': 512,
't5-3b': 512,
't5-11b': 512,
}
lowerCAmelCase = '▁'
class _a ( UpperCamelCase__ ):
_lowercase : Optional[int] = VOCAB_FILES_NAMES
_lowercase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP
_lowercase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_lowercase : Optional[Any] = ['''input_ids''', '''attention_mask''']
def __init__( self: str , UpperCamelCase_: List[str] , UpperCamelCase_: Tuple="</s>" , UpperCamelCase_: Optional[Any]="<unk>" , UpperCamelCase_: Optional[int]="<pad>" , UpperCamelCase_: List[Any]=100 , UpperCamelCase_: List[str]=None , UpperCamelCase_: Optional[Dict[str, Any]] = None , UpperCamelCase_: Dict=True , **UpperCamelCase_: Optional[Any] , ) -> None:
"""simple docstring"""
if extra_ids > 0 and additional_special_tokens is None:
lowercase__ = [f'<extra_id_{i}>' for i in range(UpperCamelCase_ )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
lowercase__ = len(set(filter(lambda UpperCamelCase_ : bool('''extra_id''' in str(UpperCamelCase_ ) ) , UpperCamelCase_ ) ) )
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''' )
lowercase__ = legacy
lowercase__ = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , extra_ids=UpperCamelCase_ , additional_special_tokens=UpperCamelCase_ , sp_model_kwargs=self.sp_model_kwargs , legacy=UpperCamelCase_ , **UpperCamelCase_ , )
lowercase__ = vocab_file
lowercase__ = extra_ids
lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(UpperCamelCase_ )
@staticmethod
def lowerCamelCase_ ( UpperCamelCase_: List[Any] , UpperCamelCase_: Union[str, Any] , UpperCamelCase_: str ) -> Any:
"""simple docstring"""
if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes:
lowercase__ = 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.''' , UpperCamelCase_ , )
return max_model_length
@property
def lowerCamelCase_ ( self: Union[str, Any] ) -> List[str]:
"""simple docstring"""
return self.sp_model.get_piece_size() + self._extra_ids
def lowerCamelCase_ ( self: Dict ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = {self.convert_ids_to_tokens(UpperCamelCase_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def lowerCamelCase_ ( self: Optional[Any] , UpperCamelCase_: List[int] , UpperCamelCase_: Optional[List[int]] = None , UpperCamelCase_: bool = False ) -> List[int]:
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(UpperCamelCase_ )) + [1]
return ([0] * len(UpperCamelCase_ )) + [1] + ([0] * len(UpperCamelCase_ )) + [1]
def lowerCamelCase_ ( self: Any ) -> Optional[int]:
"""simple docstring"""
return list(
set(filter(lambda UpperCamelCase_ : bool(re.search(r'''<extra_id_\d+>''' , UpperCamelCase_ ) ) is not None , self.additional_special_tokens ) ) )
def lowerCamelCase_ ( self: Union[str, Any] ) -> str:
"""simple docstring"""
return [self._convert_token_to_id(UpperCamelCase_ ) for token in self.get_sentinel_tokens()]
def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: List[int] ) -> List[int]:
"""simple docstring"""
if len(UpperCamelCase_ ) > 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 lowerCamelCase_ ( self: Union[str, Any] , UpperCamelCase_: List[int] , UpperCamelCase_: Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
lowercase__ = [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 lowerCamelCase_ ( self: Dict , UpperCamelCase_: List[int] , UpperCamelCase_: Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
lowercase__ = self._add_eos_if_not_present(UpperCamelCase_ )
if token_ids_a is None:
return token_ids_a
else:
lowercase__ = self._add_eos_if_not_present(UpperCamelCase_ )
return token_ids_a + token_ids_a
def __getstate__( self: Optional[Any] ) -> List[Any]:
"""simple docstring"""
lowercase__ = self.__dict__.copy()
lowercase__ = None
return state
def __setstate__( self: Any , UpperCamelCase_: str ) -> Optional[int]:
"""simple docstring"""
lowercase__ = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
lowercase__ = {}
lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def lowerCamelCase_ ( self: Any , UpperCamelCase_: "TextInput" , **UpperCamelCase_: List[Any] ) -> List[str]:
"""simple docstring"""
if not self.legacy:
lowercase__ = SPIECE_UNDERLINE + text.replace(UpperCamelCase_ , ''' ''' )
return super().tokenize(UpperCamelCase_ , **UpperCamelCase_ )
def lowerCamelCase_ ( self: List[str] , UpperCamelCase_: int , **UpperCamelCase_: str ) -> List[Any]:
"""simple docstring"""
if not self.legacy:
lowercase__ = text.startswith(UpperCamelCase_ )
if is_first:
lowercase__ = text[1:]
lowercase__ = self.sp_model.encode(UpperCamelCase_ , out_type=UpperCamelCase_ )
if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(UpperCamelCase_ ):
lowercase__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
return tokens
def lowerCamelCase_ ( self: Tuple , UpperCamelCase_: Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
if token.startswith('''<extra_id_''' ):
lowercase__ = re.match(r'''<extra_id_(\d+)>''' , UpperCamelCase_ )
lowercase__ = int(match.group(1 ) )
return self.vocab_size - num - 1
return self.sp_model.piece_to_id(UpperCamelCase_ )
def lowerCamelCase_ ( self: Any , UpperCamelCase_: Optional[Any] ) -> Union[str, Any]:
"""simple docstring"""
if index < self.sp_model.get_piece_size():
lowercase__ = self.sp_model.IdToPiece(UpperCamelCase_ )
else:
lowercase__ = f'<extra_id_{self.vocab_size - 1 - index}>'
return token
def lowerCamelCase_ ( self: str , UpperCamelCase_: int ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ = []
lowercase__ = ''''''
lowercase__ = 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(UpperCamelCase_ ) + token
lowercase__ = True
lowercase__ = []
else:
current_sub_tokens.append(UpperCamelCase_ )
lowercase__ = False
out_string += self.sp_model.decode(UpperCamelCase_ )
return out_string.strip()
def lowerCamelCase_ ( self: str , UpperCamelCase_: str , UpperCamelCase_: Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
if not os.path.isdir(UpperCamelCase_ ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
lowercase__ = os.path.join(
UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , UpperCamelCase_ )
elif not os.path.isfile(self.vocab_file ):
with open(UpperCamelCase_ , '''wb''' ) as fi:
lowercase__ = self.sp_model.serialized_model_proto()
fi.write(UpperCamelCase_ )
return (out_vocab_file,)
| 429
|
from __future__ import annotations
import inspect
import unittest
from typing import List, Tuple
from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class _a :
def __init__( self: str , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Optional[Any]=3 , UpperCamelCase_: int=32 , UpperCamelCase_: Union[str, Any]=3 , UpperCamelCase_: str=10 , UpperCamelCase_: Tuple=[10, 20, 30, 40] , UpperCamelCase_: str=[1, 1, 2, 1] , UpperCamelCase_: Optional[Any]=True , UpperCamelCase_: Optional[int]=True , UpperCamelCase_: str="relu" , UpperCamelCase_: Optional[Any]=3 , UpperCamelCase_: Union[str, Any]=None , ) -> Dict:
"""simple docstring"""
lowercase__ = parent
lowercase__ = batch_size
lowercase__ = image_size
lowercase__ = num_channels
lowercase__ = embeddings_size
lowercase__ = hidden_sizes
lowercase__ = depths
lowercase__ = is_training
lowercase__ = use_labels
lowercase__ = hidden_act
lowercase__ = num_labels
lowercase__ = scope
lowercase__ = len(UpperCamelCase_ )
def lowerCamelCase_ ( self: List[str] ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase__ = None
if self.use_labels:
lowercase__ = ids_tensor([self.batch_size] , self.num_labels )
lowercase__ = self.get_config()
return config, pixel_values, labels
def lowerCamelCase_ ( self: int ) -> Dict:
"""simple docstring"""
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def lowerCamelCase_ ( self: Optional[int] , UpperCamelCase_: Dict , UpperCamelCase_: List[str] , UpperCamelCase_: Any ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = TFRegNetModel(config=UpperCamelCase_ )
lowercase__ = model(UpperCamelCase_ , training=UpperCamelCase_ )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def lowerCamelCase_ ( self: str , UpperCamelCase_: Dict , UpperCamelCase_: Any , UpperCamelCase_: Any ) -> Tuple:
"""simple docstring"""
lowercase__ = self.num_labels
lowercase__ = TFRegNetForImageClassification(UpperCamelCase_ )
lowercase__ = model(UpperCamelCase_ , labels=UpperCamelCase_ , training=UpperCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCamelCase_ ( self: Optional[Any] ) -> List[Any]:
"""simple docstring"""
lowercase__ = self.prepare_config_and_inputs()
lowercase__ , lowercase__ , lowercase__ = config_and_inputs
lowercase__ = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_tf
class _a ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ):
_lowercase : Optional[int] = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
_lowercase : str = (
{'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
if is_tf_available()
else {}
)
_lowercase : Union[str, Any] = False
_lowercase : Optional[int] = False
_lowercase : List[Any] = False
_lowercase : Dict = False
_lowercase : List[str] = False
def lowerCamelCase_ ( self: Dict ) -> Dict:
"""simple docstring"""
lowercase__ = TFRegNetModelTester(self )
lowercase__ = ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ )
def lowerCamelCase_ ( self: str ) -> Optional[int]:
"""simple docstring"""
return
@unittest.skip(reason='''RegNet does not use inputs_embeds''' )
def lowerCamelCase_ ( self: Optional[int] ) -> Any:
"""simple docstring"""
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , )
@slow
def lowerCamelCase_ ( self: Tuple ) -> Dict:
"""simple docstring"""
super().test_keras_fit()
@unittest.skip(reason='''RegNet does not support input and output embeddings''' )
def lowerCamelCase_ ( self: Dict ) -> Optional[Any]:
"""simple docstring"""
pass
def lowerCamelCase_ ( self: Optional[int] ) -> Optional[Any]:
"""simple docstring"""
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase__ = model_class(UpperCamelCase_ )
lowercase__ = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase__ = [*signature.parameters.keys()]
lowercase__ = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , UpperCamelCase_ )
def lowerCamelCase_ ( self: int ) -> str:
"""simple docstring"""
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase_ )
def lowerCamelCase_ ( self: List[str] ) -> Optional[Any]:
"""simple docstring"""
def check_hidden_states_output(UpperCamelCase_: List[str] , UpperCamelCase_: Any , UpperCamelCase_: Dict ):
lowercase__ = model_class(UpperCamelCase_ )
lowercase__ = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) , training=UpperCamelCase_ )
lowercase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
lowercase__ = self.model_tester.num_stages
self.assertEqual(len(UpperCamelCase_ ) , expected_num_stages + 1 )
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
lowercase__ = ['''basic''', '''bottleneck''']
for model_class in self.all_model_classes:
for layer_type in layers_type:
lowercase__ = layer_type
lowercase__ = True
check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase__ = True
check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
def lowerCamelCase_ ( self: List[str] ) -> Dict:
"""simple docstring"""
lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common()
def check_equivalence(UpperCamelCase_: int , UpperCamelCase_: List[Any] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Optional[Any]={} ):
lowercase__ = model(UpperCamelCase_ , return_dict=UpperCamelCase_ , **UpperCamelCase_ )
lowercase__ = model(UpperCamelCase_ , return_dict=UpperCamelCase_ , **UpperCamelCase_ ).to_tuple()
def recursive_check(UpperCamelCase_: Optional[int] , UpperCamelCase_: Any ):
if isinstance(UpperCamelCase_ , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(UpperCamelCase_ , UpperCamelCase_ ):
recursive_check(UpperCamelCase_ , UpperCamelCase_ )
elif tuple_object is None:
return
else:
self.assertTrue(
all(tf.equal(UpperCamelCase_ , UpperCamelCase_ ) ) , msg=(
'''Tuple and dict output are not equal. Difference:'''
f' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}'
) , )
recursive_check(UpperCamelCase_ , UpperCamelCase_ )
for model_class in self.all_model_classes:
lowercase__ = model_class(UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ )
check_equivalence(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ )
check_equivalence(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ )
check_equivalence(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , {'''output_hidden_states''': True} )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ )
lowercase__ = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ )
check_equivalence(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , {'''output_hidden_states''': True} )
def lowerCamelCase_ ( self: List[Any] ) -> str:
"""simple docstring"""
lowercase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_ )
@slow
def lowerCamelCase_ ( self: List[str] ) -> Dict:
"""simple docstring"""
for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase__ = TFRegNetModel.from_pretrained(UpperCamelCase_ )
self.assertIsNotNone(UpperCamelCase_ )
def _a ( ):
"""simple docstring"""
lowercase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_tf
@require_vision
class _a ( unittest.TestCase ):
@cached_property
def lowerCamelCase_ ( self: Any ) -> Optional[int]:
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def lowerCamelCase_ ( self: Dict ) -> Dict:
"""simple docstring"""
lowercase__ = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
lowercase__ = self.default_image_processor
lowercase__ = prepare_img()
lowercase__ = image_processor(images=UpperCamelCase_ , return_tensors='''tf''' )
# forward pass
lowercase__ = model(**UpperCamelCase_ , training=UpperCamelCase_ )
# verify the logits
lowercase__ = tf.TensorShape((1, 1_000) )
self.assertEqual(outputs.logits.shape , UpperCamelCase_ )
lowercase__ = tf.constant([-0.4180, -1.5051, -3.4836] )
tf.debugging.assert_near(outputs.logits[0, :3] , UpperCamelCase_ , atol=1E-4 )
| 429
| 1
|
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_A: int = logging.get_logger(__name__)
_A: Dict = {
"""tanreinama/GPTSAN-2.8B-spout_is_uniform""": (
"""https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json"""
),
}
class UpperCAmelCase ( UpperCAmelCase_ ):
_A : Optional[Any] = """gptsan-japanese"""
_A : Tuple = [
"""past_key_values""",
]
_A : Optional[int] = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """num_heads""",
"""num_hidden_layers""": """num_layers""",
}
def __init__( self , __A=36_000 , __A=1_280 , __A=1_024 , __A=8_192 , __A=4_096 , __A=128 , __A=10 , __A=0 , __A=16 , __A=16 , __A=128 , __A=0.0 , __A=1E-5 , __A=False , __A=0.0 , __A="float32" , __A=False , __A=False , __A=False , __A=0.0_0_2 , __A=False , __A=True , __A=35_998 , __A=35_995 , __A=35_999 , **__A , ):
__UpperCAmelCase = vocab_size
__UpperCAmelCase = max_position_embeddings
__UpperCAmelCase = d_model
__UpperCAmelCase = d_ff
__UpperCAmelCase = d_ext
__UpperCAmelCase = d_spout
__UpperCAmelCase = num_switch_layers
__UpperCAmelCase = num_ext_layers
__UpperCAmelCase = num_switch_layers + num_ext_layers
__UpperCAmelCase = num_heads
__UpperCAmelCase = num_experts
__UpperCAmelCase = expert_capacity
__UpperCAmelCase = dropout_rate
__UpperCAmelCase = layer_norm_epsilon
__UpperCAmelCase = router_bias
__UpperCAmelCase = router_jitter_noise
__UpperCAmelCase = router_dtype
__UpperCAmelCase = router_ignore_padding_tokens
__UpperCAmelCase = output_hidden_states
__UpperCAmelCase = output_attentions
__UpperCAmelCase = initializer_factor
__UpperCAmelCase = output_router_logits
__UpperCAmelCase = use_cache
super().__init__(
separator_token_id=__A , pad_token_id=__A , eos_token_id=__A , **__A , )
| 126
|
'''simple docstring'''
from typing import Any
import numpy as np
def _lowerCAmelCase ( _lowerCAmelCase )-> bool:
return np.array_equal(_lowerCAmelCase , matrix.conjugate().T )
def _lowerCAmelCase ( _lowerCAmelCase , _lowerCAmelCase )-> Any:
__UpperCAmelCase = v.conjugate().T
__UpperCAmelCase = v_star.dot(_lowerCAmelCase )
assert isinstance(_lowerCAmelCase , np.ndarray )
return (v_star_dot.dot(_lowerCAmelCase )) / (v_star.dot(_lowerCAmelCase ))
def _lowerCAmelCase ( )-> None:
__UpperCAmelCase = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] )
__UpperCAmelCase = np.array([[1], [2], [3]] )
assert is_hermitian(_lowerCAmelCase ), F'{a} is not hermitian.'
print(rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) )
__UpperCAmelCase = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] )
assert is_hermitian(_lowerCAmelCase ), F'{a} is not hermitian.'
assert rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) == float(3 )
if __name__ == "__main__":
import doctest
doctest.testmod()
tests()
| 126
| 1
|
'''simple docstring'''
import gc
import unittest
from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class a_ ( unittest.TestCase ):
def A__ ( self ) -> List[Any]:
"""simple docstring"""
super().tearDown()
gc.collect()
def A__ ( self ) -> List[str]:
"""simple docstring"""
UpperCamelCase ,UpperCamelCase = FlaxStableDiffusionPipeline.from_pretrained(
"""stabilityai/stable-diffusion-2""" , revision="""bf16""" , dtype=jnp.bfloataa , )
UpperCamelCase = """A painting of a squirrel eating a burger"""
UpperCamelCase = jax.device_count()
UpperCamelCase = num_samples * [prompt]
UpperCamelCase = sd_pipe.prepare_inputs(_SCREAMING_SNAKE_CASE )
UpperCamelCase = replicate(_SCREAMING_SNAKE_CASE )
UpperCamelCase = shard(_SCREAMING_SNAKE_CASE )
UpperCamelCase = jax.random.PRNGKey(0 )
UpperCamelCase = jax.random.split(_SCREAMING_SNAKE_CASE , jax.device_count() )
UpperCamelCase = sd_pipe(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , num_inference_steps=25 , jit=_SCREAMING_SNAKE_CASE )[0]
assert images.shape == (jax.device_count(), 1, 768, 768, 3)
UpperCamelCase = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
UpperCamelCase = images[0, 253:256, 253:256, -1]
UpperCamelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) )
UpperCamelCase = jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] )
print(F"output_slice: {output_slice}" )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
def A__ ( self ) -> Any:
"""simple docstring"""
UpperCamelCase = """stabilityai/stable-diffusion-2"""
UpperCamelCase ,UpperCamelCase = FlaxDPMSolverMultistepScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder="""scheduler""" )
UpperCamelCase ,UpperCamelCase = FlaxStableDiffusionPipeline.from_pretrained(
_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , revision="""bf16""" , dtype=jnp.bfloataa , )
UpperCamelCase = scheduler_params
UpperCamelCase = """A painting of a squirrel eating a burger"""
UpperCamelCase = jax.device_count()
UpperCamelCase = num_samples * [prompt]
UpperCamelCase = sd_pipe.prepare_inputs(_SCREAMING_SNAKE_CASE )
UpperCamelCase = replicate(_SCREAMING_SNAKE_CASE )
UpperCamelCase = shard(_SCREAMING_SNAKE_CASE )
UpperCamelCase = jax.random.PRNGKey(0 )
UpperCamelCase = jax.random.split(_SCREAMING_SNAKE_CASE , jax.device_count() )
UpperCamelCase = sd_pipe(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , num_inference_steps=25 , jit=_SCREAMING_SNAKE_CASE )[0]
assert images.shape == (jax.device_count(), 1, 768, 768, 3)
UpperCamelCase = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
UpperCamelCase = images[0, 253:256, 253:256, -1]
UpperCamelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) )
UpperCamelCase = jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] )
print(F"output_slice: {output_slice}" )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
| 704
|
'''simple docstring'''
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ = {
'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json',
# See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}
class a_ ( lowerCamelCase ):
lowercase = """deformable_detr"""
lowercase = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
}
def __init__( self , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=1024 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="relu" , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="sine" , _SCREAMING_SNAKE_CASE="resnet50" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=300 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.2_5 , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> List[str]:
"""simple docstring"""
if backbone_config is not None and use_timm_backbone:
raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" )
if not use_timm_backbone:
if backbone_config is None:
logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" )
UpperCamelCase = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] )
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
UpperCamelCase = backbone_config.get("""model_type""" )
UpperCamelCase = CONFIG_MAPPING[backbone_model_type]
UpperCamelCase = config_class.from_dict(_SCREAMING_SNAKE_CASE )
UpperCamelCase = use_timm_backbone
UpperCamelCase = backbone_config
UpperCamelCase = num_channels
UpperCamelCase = num_queries
UpperCamelCase = max_position_embeddings
UpperCamelCase = d_model
UpperCamelCase = encoder_ffn_dim
UpperCamelCase = encoder_layers
UpperCamelCase = encoder_attention_heads
UpperCamelCase = decoder_ffn_dim
UpperCamelCase = decoder_layers
UpperCamelCase = decoder_attention_heads
UpperCamelCase = dropout
UpperCamelCase = attention_dropout
UpperCamelCase = activation_dropout
UpperCamelCase = activation_function
UpperCamelCase = init_std
UpperCamelCase = init_xavier_std
UpperCamelCase = encoder_layerdrop
UpperCamelCase = auxiliary_loss
UpperCamelCase = position_embedding_type
UpperCamelCase = backbone
UpperCamelCase = use_pretrained_backbone
UpperCamelCase = dilation
# deformable attributes
UpperCamelCase = num_feature_levels
UpperCamelCase = encoder_n_points
UpperCamelCase = decoder_n_points
UpperCamelCase = two_stage
UpperCamelCase = two_stage_num_proposals
UpperCamelCase = with_box_refine
if two_stage is True and with_box_refine is False:
raise ValueError("""If two_stage is True, with_box_refine must be True.""" )
# Hungarian matcher
UpperCamelCase = class_cost
UpperCamelCase = bbox_cost
UpperCamelCase = giou_cost
# Loss coefficients
UpperCamelCase = mask_loss_coefficient
UpperCamelCase = dice_loss_coefficient
UpperCamelCase = bbox_loss_coefficient
UpperCamelCase = giou_loss_coefficient
UpperCamelCase = eos_coefficient
UpperCamelCase = focal_alpha
UpperCamelCase = disable_custom_kernels
super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
@property
def A__ ( self ) -> int:
"""simple docstring"""
return self.encoder_attention_heads
@property
def A__ ( self ) -> int:
"""simple docstring"""
return self.d_model
def A__ ( self ) -> Tuple:
"""simple docstring"""
UpperCamelCase = copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
UpperCamelCase = self.backbone_config.to_dict()
UpperCamelCase = self.__class__.model_type
return output
| 35
| 0
|
'''simple docstring'''
def a_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ):
A_ = [redshift, radiation_density, matter_density, dark_energy]
if any(p < 0 for p in parameters ):
raise ValueError("All input parameters must be positive" )
if any(p > 1 for p in parameters[1:4] ):
raise ValueError("Relative densities cannot be greater than one" )
else:
A_ = 1 - (matter_density + radiation_density + dark_energy)
A_ = (
radiation_density * (redshift + 1) ** 4
+ matter_density * (redshift + 1) ** 3
+ curvature * (redshift + 1) ** 2
+ dark_energy
)
A_ = hubble_constant * e_a ** (1 / 2)
return hubble
if __name__ == "__main__":
import doctest
# run doctest
doctest.testmod()
# demo LCDM approximation
__SCREAMING_SNAKE_CASE : Tuple = 0.3
print(
hubble_parameter(
hubble_constant=68.3,
radiation_density=1E-4,
matter_density=matter_density,
dark_energy=1 - matter_density,
redshift=0,
)
)
| 452
|
'''simple docstring'''
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
DYNAMO_BACKENDS,
_ask_field,
_ask_options,
_convert_dynamo_backend,
_convert_mixed_precision,
_convert_sagemaker_distributed_mode,
_convert_yes_no_to_bool,
)
if is_botoa_available():
import botoa # noqa: F401
def a_ ( UpperCamelCase_ ):
A_ = botoa.client("iam" )
A_ = {
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"}
],
}
try:
# create the role, associated with the chosen trust policy
iam_client.create_role(
RoleName=UpperCamelCase_ , AssumeRolePolicyDocument=json.dumps(UpperCamelCase_ , indent=2 ) )
A_ = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sagemaker:*",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:BatchCheckLayerAvailability",
"ecr:GetAuthorizationToken",
"cloudwatch:PutMetricData",
"cloudwatch:GetMetricData",
"cloudwatch:GetMetricStatistics",
"cloudwatch:ListMetrics",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
"logs:GetLogEvents",
"s3:CreateBucket",
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:GetObject",
"s3:PutObject",
],
"Resource": "*",
}
],
}
# attach policy to role
iam_client.put_role_policy(
RoleName=UpperCamelCase_ , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(UpperCamelCase_ , indent=2 ) , )
except iam_client.exceptions.EntityAlreadyExistsException:
print(f"role {role_name} already exists. Using existing one" )
def a_ ( UpperCamelCase_ ):
A_ = botoa.client("iam" )
return iam_client.get_role(RoleName=UpperCamelCase_ )["Role"]["Arn"]
def a_ ( ):
A_ = _ask_options(
"How do you want to authorize?" , ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "] , UpperCamelCase_ , )
A_ = None
if credentials_configuration == 0:
A_ = _ask_field("Enter your AWS Profile name: [default] " , default="default" )
A_ = aws_profile
else:
print(
"Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"
"`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" )
A_ = _ask_field("AWS Access Key ID: " )
A_ = aws_access_key_id
A_ = _ask_field("AWS Secret Access Key: " )
A_ = aws_secret_access_key
A_ = _ask_field("Enter your AWS Region: [us-east-1]" , default="us-east-1" )
A_ = aws_region
A_ = _ask_options(
"Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?" , ["Provide IAM Role name", "Create new IAM role using credentials"] , UpperCamelCase_ , )
if role_management == 0:
A_ = _ask_field("Enter your IAM role name: " )
else:
A_ = "accelerate_sagemaker_execution_role"
print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" )
_create_iam_role_for_sagemaker(UpperCamelCase_ )
A_ = _ask_field(
"Do you want to use custom Docker image? [yes/NO]: " , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
A_ = None
if is_custom_docker_image:
A_ = _ask_field("Enter your Docker image: " , lambda UpperCamelCase_ : str(UpperCamelCase_ ).lower() )
A_ = _ask_field(
"Do you want to provide SageMaker input channels with data locations? [yes/NO]: " , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
A_ = None
if is_sagemaker_inputs_enabled:
A_ = _ask_field(
"Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): " , lambda UpperCamelCase_ : str(UpperCamelCase_ ).lower() , )
A_ = _ask_field(
"Do you want to enable SageMaker metrics? [yes/NO]: " , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
A_ = None
if is_sagemaker_metrics_enabled:
A_ = _ask_field(
"Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): " , lambda UpperCamelCase_ : str(UpperCamelCase_ ).lower() , )
A_ = _ask_options(
"What is the distributed mode?" , ["No distributed training", "Data parallelism"] , _convert_sagemaker_distributed_mode , )
A_ = {}
A_ = _ask_field(
"Do you wish to optimize your script with torch dynamo?[yes/NO]:" , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
if use_dynamo:
A_ = "dynamo_"
A_ = _ask_options(
"Which dynamo backend would you like to use?" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , )
A_ = _ask_field(
"Do you want to customize the defaults sent to torch.compile? [yes/NO]: " , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
if use_custom_options:
A_ = _ask_options(
"Which mode do you want to use?" , UpperCamelCase_ , lambda UpperCamelCase_ : TORCH_DYNAMO_MODES[int(UpperCamelCase_ )] , default="default" , )
A_ = _ask_field(
"Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: " , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
A_ = _ask_field(
"Do you want to enable dynamic shape tracing? [yes/NO]: " , _convert_yes_no_to_bool , default=UpperCamelCase_ , error_message="Please enter yes or no." , )
A_ = "Which EC2 instance type you want to use for your training?"
if distributed_type != SageMakerDistributedType.NO:
A_ = _ask_options(
UpperCamelCase_ , UpperCamelCase_ , lambda UpperCamelCase_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(UpperCamelCase_ )] )
else:
eca_instance_query += "? [ml.p3.2xlarge]:"
A_ = _ask_field(UpperCamelCase_ , lambda UpperCamelCase_ : str(UpperCamelCase_ ).lower() , default="ml.p3.2xlarge" )
A_ = 1
if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
A_ = _ask_field(
"How many machines do you want use? [1]: " , UpperCamelCase_ , default=1 , )
A_ = _ask_options(
"Do you wish to use FP16 or BF16 (mixed precision)?" , ["no", "fp16", "bf16", "fp8"] , _convert_mixed_precision , )
if use_dynamo and mixed_precision == "no":
print(
"Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." )
return SageMakerConfig(
image_uri=UpperCamelCase_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=UpperCamelCase_ , use_cpu=UpperCamelCase_ , dynamo_config=UpperCamelCase_ , eca_instance_type=UpperCamelCase_ , profile=UpperCamelCase_ , region=UpperCamelCase_ , iam_role_name=UpperCamelCase_ , mixed_precision=UpperCamelCase_ , num_machines=UpperCamelCase_ , sagemaker_inputs_file=UpperCamelCase_ , sagemaker_metrics_file=UpperCamelCase_ , )
| 452
| 1
|
"""simple docstring"""
import warnings
from ...utils import logging
from .image_processing_segformer import SegformerImageProcessor
UpperCamelCase__ = logging.get_logger(__name__)
class a__ ( UpperCamelCase_ ):
def __init__( self : Dict ,*a__ : List[str] ,**a__ : Tuple) -> None:
"""simple docstring"""
warnings.warn(
'''The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
''' Please use SegformerImageProcessor instead.''' ,a__ ,)
super().__init__(*a__ ,**a__)
| 439
|
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ = logging.get_logger(__name__)
UpperCamelCase__ = {
'''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''',
}
class a__ ( UpperCamelCase_ ):
snake_case__ = '''roc_bert'''
def __init__( self : Union[str, Any] ,a__ : Union[str, Any]=3_0522 ,a__ : List[Any]=768 ,a__ : Tuple=12 ,a__ : Optional[int]=12 ,a__ : Any=3072 ,a__ : Optional[int]="gelu" ,a__ : Union[str, Any]=0.1 ,a__ : List[str]=0.1 ,a__ : Dict=512 ,a__ : int=2 ,a__ : Dict=0.02 ,a__ : Dict=1E-12 ,a__ : int=True ,a__ : Optional[int]=0 ,a__ : Union[str, Any]="absolute" ,a__ : List[Any]=None ,a__ : str=True ,a__ : str=True ,a__ : List[str]=768 ,a__ : Optional[int]=910 ,a__ : Any=512 ,a__ : str=2_4858 ,a__ : List[str]=True ,**a__ : str ,) -> List[str]:
"""simple docstring"""
_lowerCAmelCase:Tuple = vocab_size
_lowerCAmelCase:Any = max_position_embeddings
_lowerCAmelCase:Union[str, Any] = hidden_size
_lowerCAmelCase:Optional[Any] = num_hidden_layers
_lowerCAmelCase:int = num_attention_heads
_lowerCAmelCase:int = intermediate_size
_lowerCAmelCase:Union[str, Any] = hidden_act
_lowerCAmelCase:Any = hidden_dropout_prob
_lowerCAmelCase:List[Any] = attention_probs_dropout_prob
_lowerCAmelCase:List[Any] = initializer_range
_lowerCAmelCase:Dict = type_vocab_size
_lowerCAmelCase:Dict = layer_norm_eps
_lowerCAmelCase:str = use_cache
_lowerCAmelCase:Any = enable_pronunciation
_lowerCAmelCase:List[str] = enable_shape
_lowerCAmelCase:Optional[int] = pronunciation_embed_dim
_lowerCAmelCase:Union[str, Any] = pronunciation_vocab_size
_lowerCAmelCase:str = shape_embed_dim
_lowerCAmelCase:List[Any] = shape_vocab_size
_lowerCAmelCase:str = concat_input
_lowerCAmelCase:Optional[int] = position_embedding_type
_lowerCAmelCase:Any = classifier_dropout
super().__init__(pad_token_id=a__ ,**a__)
| 439
| 1
|
'''simple docstring'''
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
_UpperCAmelCase : Dict = logging.get_logger(__name__)
_UpperCAmelCase : Optional[int] = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_UpperCAmelCase : Any = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class __magic_name__ :
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Model type selected in the list: ' + ', '.join(__SCREAMING_SNAKE_CASE )} )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
UpperCamelCase__ = field(
default=1_28 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
UpperCamelCase__ = field(
default=1_28 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , )
UpperCamelCase__ = field(
default=64 , metadata={
'help': (
'The maximum number of tokens for the question. Questions longer than this will '
'be truncated to this length.'
)
} , )
UpperCamelCase__ = field(
default=30 , metadata={
'help': (
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
)
} , )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
UpperCamelCase__ = field(
default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
UpperCamelCase__ = field(
default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
UpperCamelCase__ = field(
default=0 , metadata={
'help': (
'language id of input for language-specific xlm models (see'
' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
)
} , )
UpperCamelCase__ = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} )
class __magic_name__ ( __SCREAMING_SNAKE_CASE ):
UpperCamelCase__ = 'train'
UpperCamelCase__ = 'dev'
class __magic_name__ ( __SCREAMING_SNAKE_CASE ):
UpperCamelCase__ = 42
UpperCamelCase__ = 42
UpperCamelCase__ = 42
UpperCamelCase__ = 42
def __init__( self , snake_case_ , snake_case_ , snake_case_ = None , snake_case_ = Split.train , snake_case_ = False , snake_case_ = None , snake_case_ = "pt" , ):
lowercase =args
lowercase =is_language_sensitive
lowercase =SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(snake_case_ , snake_case_ ):
try:
lowercase =Split[mode]
except KeyError:
raise KeyError('''mode is not a valid split name''' )
lowercase =mode
# Load data features from cache or dataset file
lowercase ='''v2''' if args.version_2_with_negative else '''v1'''
lowercase =os.path.join(
cache_dir if cache_dir is not None else args.data_dir , f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}' , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
lowercase =cached_features_file + '''.lock'''
with FileLock(snake_case_ ):
if os.path.exists(snake_case_ ) and not args.overwrite_cache:
lowercase =time.time()
lowercase =torch.load(snake_case_ )
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
lowercase =self.old_features['''features''']
lowercase =self.old_features.get('''dataset''' , snake_case_ )
lowercase =self.old_features.get('''examples''' , snake_case_ )
logger.info(
f'Loading features from cached file {cached_features_file} [took %.3f s]' , time.time() - start )
if self.dataset is None or self.examples is None:
logger.warning(
f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
''' future run''' )
else:
if mode == Split.dev:
lowercase =self.processor.get_dev_examples(args.data_dir )
else:
lowercase =self.processor.get_train_examples(args.data_dir )
lowercase , lowercase =squad_convert_examples_to_features(
examples=self.examples , tokenizer=snake_case_ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=snake_case_ , )
lowercase =time.time()
torch.save(
{'''features''': self.features, '''dataset''': self.dataset, '''examples''': self.examples} , snake_case_ , )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' )
def __len__( self ):
return len(self.features )
def __getitem__( self , snake_case_ ):
# Convert to Tensors and build dataset
lowercase =self.features[i]
lowercase =torch.tensor(feature.input_ids , dtype=torch.long )
lowercase =torch.tensor(feature.attention_mask , dtype=torch.long )
lowercase =torch.tensor(feature.token_type_ids , dtype=torch.long )
lowercase =torch.tensor(feature.cls_index , dtype=torch.long )
lowercase =torch.tensor(feature.p_mask , dtype=torch.float )
lowercase =torch.tensor(feature.is_impossible , dtype=torch.float )
lowercase ={
'''input_ids''': input_ids,
'''attention_mask''': attention_mask,
'''token_type_ids''': token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({'''cls_index''': cls_index, '''p_mask''': p_mask} )
if self.args.version_2_with_negative:
inputs.update({'''is_impossible''': is_impossible} )
if self.is_language_sensitive:
inputs.update({'''langs''': (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} )
if self.mode == Split.train:
lowercase =torch.tensor(feature.start_position , dtype=torch.long )
lowercase =torch.tensor(feature.end_position , dtype=torch.long )
inputs.update({'''start_positions''': start_positions, '''end_positions''': end_positions} )
return inputs
| 72
|
'''simple docstring'''
import unicodedata
from dataclasses import dataclass
from typing import Optional, Union
import numpy as np
from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
def UpperCamelCase ( lowercase_ : List[str] , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : Tuple ) -> List[Any]:
'''simple docstring'''
if isinstance(lowercase_ , lowercase_ ):
lowercase =np.full((len(lowercase_ ), sequence_length, 2) , lowercase_ )
else:
lowercase =np.full((len(lowercase_ ), sequence_length) , lowercase_ )
for i, tensor in enumerate(lowercase_ ):
if padding_side == "right":
if isinstance(lowercase_ , lowercase_ ):
lowercase =tensor[:sequence_length]
else:
lowercase =tensor[:sequence_length]
else:
if isinstance(lowercase_ , lowercase_ ):
lowercase =tensor[:sequence_length]
else:
lowercase =tensor[:sequence_length]
return out_tensor.tolist()
def UpperCamelCase ( lowercase_ : Optional[Any] ) -> str:
'''simple docstring'''
lowercase =ord(lowercase_ )
if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6):
return True
lowercase =unicodedata.category(lowercase_ )
if cat.startswith('''P''' ):
return True
return False
@dataclass
class __magic_name__ ( __SCREAMING_SNAKE_CASE ):
UpperCamelCase__ = 42
UpperCamelCase__ = True
UpperCamelCase__ = None
UpperCamelCase__ = None
UpperCamelCase__ = -1_00
UpperCamelCase__ = "pt"
def _A( self , snake_case_ ):
import torch
lowercase ='''label''' if '''label''' in features[0].keys() else '''labels'''
lowercase =[feature[label_name] for feature in features] if label_name in features[0].keys() else None
lowercase =self.tokenizer.pad(
snake_case_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , )
if labels is None:
return batch
lowercase =torch.tensor(batch['''entity_ids'''] ).shape[1]
lowercase =self.tokenizer.padding_side
if padding_side == "right":
lowercase =[
list(snake_case_ ) + [self.label_pad_token_id] * (sequence_length - len(snake_case_ )) for label in labels
]
else:
lowercase =[
[self.label_pad_token_id] * (sequence_length - len(snake_case_ )) + list(snake_case_ ) for label in labels
]
lowercase =[feature['''ner_tags'''] for feature in features]
lowercase =padding_tensor(snake_case_ , -1 , snake_case_ , snake_case_ )
lowercase =[feature['''original_entity_spans'''] for feature in features]
lowercase =padding_tensor(snake_case_ , (-1, -1) , snake_case_ , snake_case_ )
lowercase ={k: torch.tensor(snake_case_ , dtype=torch.intaa ) for k, v in batch.items()}
return batch
| 72
| 1
|
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
lowerCAmelCase_ : List[Any] = {
"configuration_rembert": ["REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RemBertConfig", "RemBertOnnxConfig"]
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ : Optional[int] = ["RemBertTokenizer"]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ : Optional[int] = ["RemBertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ : Optional[int] = [
"REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"RemBertForCausalLM",
"RemBertForMaskedLM",
"RemBertForMultipleChoice",
"RemBertForQuestionAnswering",
"RemBertForSequenceClassification",
"RemBertForTokenClassification",
"RemBertLayer",
"RemBertModel",
"RemBertPreTrainedModel",
"load_tf_weights_in_rembert",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ : Any = [
"TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFRemBertForCausalLM",
"TFRemBertForMaskedLM",
"TFRemBertForMultipleChoice",
"TFRemBertForQuestionAnswering",
"TFRemBertForSequenceClassification",
"TFRemBertForTokenClassification",
"TFRemBertLayer",
"TFRemBertModel",
"TFRemBertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_rembert import RemBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_rembert_fast import RemBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_rembert import (
REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
RemBertForCausalLM,
RemBertForMaskedLM,
RemBertForMultipleChoice,
RemBertForQuestionAnswering,
RemBertForSequenceClassification,
RemBertForTokenClassification,
RemBertLayer,
RemBertModel,
RemBertPreTrainedModel,
load_tf_weights_in_rembert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_rembert import (
TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFRemBertForCausalLM,
TFRemBertForMaskedLM,
TFRemBertForMultipleChoice,
TFRemBertForQuestionAnswering,
TFRemBertForSequenceClassification,
TFRemBertForTokenClassification,
TFRemBertLayer,
TFRemBertModel,
TFRemBertPreTrainedModel,
)
else:
import sys
lowerCAmelCase_ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 289
|
'''simple docstring'''
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
from ...utils.dataclasses import (
ComputeEnvironment,
DistributedType,
DynamoBackend,
PrecisionType,
SageMakerDistributedType,
)
from ..menu import BulletMenu
lowerCAmelCase_ : List[Any] = [
"EAGER",
"AOT_EAGER",
"INDUCTOR",
"NVFUSER",
"AOT_NVFUSER",
"AOT_CUDAGRAPHS",
"OFI",
"FX2TRT",
"ONNXRT",
"IPEX",
]
def _lowerCamelCase (__lowerCamelCase : Tuple , __lowerCamelCase : Tuple=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : List[Any]=None ) -> Any:
a__ = True
while ask_again:
a__ = input(__lowerCamelCase )
try:
if default is not None and len(__lowerCamelCase ) == 0:
return default
return convert_value(__lowerCamelCase ) if convert_value is not None else result
except Exception:
if error_message is not None:
print(__lowerCamelCase )
def _lowerCamelCase (__lowerCamelCase : Dict , __lowerCamelCase : List[Any]=[] , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=0 ) -> List[Any]:
a__ = BulletMenu(__lowerCamelCase , __lowerCamelCase )
a__ = menu.run(default_choice=__lowerCamelCase )
return convert_value(__lowerCamelCase ) if convert_value is not None else result
def _lowerCamelCase (__lowerCamelCase : Tuple ) -> Optional[Any]:
a__ = int(__lowerCamelCase )
return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value] )
def _lowerCamelCase (__lowerCamelCase : List[str] ) -> Optional[int]:
a__ = int(__lowerCamelCase )
return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value] )
def _lowerCamelCase (__lowerCamelCase : List[Any] ) -> Optional[Any]:
a__ = int(__lowerCamelCase )
return DynamoBackend(DYNAMO_BACKENDS[value] ).value
def _lowerCamelCase (__lowerCamelCase : str ) -> str:
a__ = int(__lowerCamelCase )
return PrecisionType(["no", "fp16", "bf16", "fp8"][value] )
def _lowerCamelCase (__lowerCamelCase : int ) -> Optional[Any]:
a__ = int(__lowerCamelCase )
return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value] )
def _lowerCamelCase (__lowerCamelCase : Any ) -> List[Any]:
return {"yes": True, "no": False}[value.lower()]
class UpperCamelCase__ ( argparse.RawDescriptionHelpFormatter ):
def __a ( self : Dict , lowerCamelCase : int , lowerCamelCase : Optional[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ):
'''simple docstring'''
a__ = super()._format_usage(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )
a__ = usage.replace("<command> [<args>] " , "" )
return usage
| 289
| 1
|
from typing import List, Optional, Union
import torch
from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
is_accelerate_available,
is_accelerate_version,
logging,
randn_tensor,
replace_example_docstring,
)
a__ : List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name
a__ : Tuple = """
Examples:
```py
>>> import torch
>>> import numpy as np
>>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
>>> from transformers import pipeline
>>> from diffusers.utils import load_image
>>> def make_hint(image, depth_estimator):
... image = depth_estimator(image)[\"depth\"]
... image = np.array(image)
... image = image[:, :, None]
... image = np.concatenate([image, image, image], axis=2)
... detected_map = torch.from_numpy(image).float() / 255.0
... hint = detected_map.permute(2, 0, 1)
... return hint
>>> depth_estimator = pipeline(\"depth-estimation\")
>>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
... )
>>> pipe_prior = pipe_prior.to(\"cuda\")
>>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(
... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16
... )
>>> pipe = pipe.to(\"cuda\")
>>> img = load_image(
... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
... \"/kandinsky/cat.png\"
... ).resize((768, 768))
>>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")
>>> prompt = \"A robot, 4k photo\"
>>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"
>>> generator = torch.Generator(device=\"cuda\").manual_seed(43)
>>> image_emb, zero_image_emb = pipe_prior(
... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
... ).to_tuple()
>>> images = pipe(
... image_embeds=image_emb,
... negative_image_embeds=zero_image_emb,
... hint=hint,
... num_inference_steps=50,
... generator=generator,
... height=768,
... width=768,
... ).images
>>> images[0].save(\"robot_cat.png\")
```
"""
def snake_case (UpperCamelCase : Optional[int] , UpperCamelCase : List[Any] , UpperCamelCase : Any=8 ):
'''simple docstring'''
lowerCamelCase__ = height // scale_factor**2
if height % scale_factor**2 != 0:
new_height += 1
lowerCamelCase__ = width // scale_factor**2
if width % scale_factor**2 != 0:
new_width += 1
return new_height * scale_factor, new_width * scale_factor
class lowercase ( UpperCAmelCase_ ):
"""simple docstring"""
def __init__( self : Union[str, Any] , a_ : UNetaDConditionModel , a_ : DDPMScheduler , a_ : VQModel , ):
"""simple docstring"""
super().__init__()
self.register_modules(
unet=a_ , scheduler=a_ , movq=a_ , )
lowerCamelCase__ = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def _UpperCamelCase ( self : str , a_ : Optional[Any] , a_ : Dict , a_ : Dict , a_ : Dict , a_ : Dict , a_ : Dict ):
"""simple docstring"""
if latents is None:
lowerCamelCase__ = randn_tensor(a_ , generator=a_ , device=a_ , dtype=a_ )
else:
if latents.shape != shape:
raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}''' )
lowerCamelCase__ = latents.to(a_ )
lowerCamelCase__ = latents * scheduler.init_noise_sigma
return latents
def _UpperCamelCase ( self : List[str] , a_ : Optional[int]=0 ):
"""simple docstring"""
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError("""Please install accelerate via `pip install accelerate`""" )
lowerCamelCase__ = torch.device(F'''cuda:{gpu_id}''' )
lowerCamelCase__ = [
self.unet,
self.movq,
]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(a_ , a_ )
def _UpperCamelCase ( self : Any , a_ : Tuple=0 ):
"""simple docstring"""
if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ):
from accelerate import cpu_offload_with_hook
else:
raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" )
lowerCamelCase__ = torch.device(F'''cuda:{gpu_id}''' )
if self.device.type != "cpu":
self.to("""cpu""" , silence_dtype_warnings=a_ )
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
lowerCamelCase__ = None
for cpu_offloaded_model in [self.unet, self.movq]:
lowerCamelCase__ , lowerCamelCase__ = cpu_offload_with_hook(a_ , a_ , prev_module_hook=a_ )
# We'll offload the last model manually.
lowerCamelCase__ = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def _UpperCamelCase ( self : Tuple ):
"""simple docstring"""
if not hasattr(self.unet , """_hf_hook""" ):
return self.device
for module in self.unet.modules():
if (
hasattr(a_ , """_hf_hook""" )
and hasattr(module._hf_hook , """execution_device""" )
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device )
return self.device
@torch.no_grad()
@replace_example_docstring(a_ )
def __call__( self : Any , a_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , a_ : torch.FloatTensor , a_ : int = 5_12 , a_ : int = 5_12 , a_ : int = 1_00 , a_ : float = 4.0 , a_ : int = 1 , a_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a_ : Optional[torch.FloatTensor] = None , a_ : Optional[str] = "pil" , a_ : bool = True , ):
"""simple docstring"""
lowerCamelCase__ = self._execution_device
lowerCamelCase__ = guidance_scale > 1.0
if isinstance(a_ , a_ ):
lowerCamelCase__ = torch.cat(a_ , dim=0 )
if isinstance(a_ , a_ ):
lowerCamelCase__ = torch.cat(a_ , dim=0 )
if isinstance(a_ , a_ ):
lowerCamelCase__ = torch.cat(a_ , dim=0 )
lowerCamelCase__ = image_embeds.shape[0] * num_images_per_prompt
if do_classifier_free_guidance:
lowerCamelCase__ = image_embeds.repeat_interleave(a_ , dim=0 )
lowerCamelCase__ = negative_image_embeds.repeat_interleave(a_ , dim=0 )
lowerCamelCase__ = hint.repeat_interleave(a_ , dim=0 )
lowerCamelCase__ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=a_ )
lowerCamelCase__ = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=a_ )
self.scheduler.set_timesteps(a_ , device=a_ )
lowerCamelCase__ = self.scheduler.timesteps
lowerCamelCase__ = self.movq.config.latent_channels
lowerCamelCase__ , lowerCamelCase__ = downscale_height_and_width(a_ , a_ , self.movq_scale_factor )
# create initial latent
lowerCamelCase__ = self.prepare_latents(
(batch_size, num_channels_latents, height, width) , image_embeds.dtype , a_ , a_ , a_ , self.scheduler , )
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__ = {"""image_embeds""": image_embeds, """hint""": hint}
lowerCamelCase__ = self.unet(
sample=a_ , timestep=a_ , encoder_hidden_states=a_ , added_cond_kwargs=a_ , return_dict=a_ , )[0]
if do_classifier_free_guidance:
lowerCamelCase__ , lowerCamelCase__ = noise_pred.split(latents.shape[1] , dim=1 )
lowerCamelCase__ , lowerCamelCase__ = noise_pred.chunk(2 )
lowerCamelCase__ , lowerCamelCase__ = variance_pred.chunk(2 )
lowerCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
lowerCamelCase__ = torch.cat([noise_pred, variance_pred_text] , dim=1 )
if not (
hasattr(self.scheduler.config , """variance_type""" )
and self.scheduler.config.variance_type in ["learned", "learned_range"]
):
lowerCamelCase__ , lowerCamelCase__ = noise_pred.split(latents.shape[1] , dim=1 )
# compute the previous noisy sample x_t -> x_t-1
lowerCamelCase__ = self.scheduler.step(
a_ , a_ , a_ , generator=a_ , )[0]
# post-processing
lowerCamelCase__ = self.movq.decode(a_ , force_not_quantize=a_ )["""sample"""]
if output_type not in ["pt", "np", "pil"]:
raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' )
if output_type in ["np", "pil"]:
lowerCamelCase__ = image * 0.5 + 0.5
lowerCamelCase__ = image.clamp(0 , 1 )
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 ImagePipelineOutput(images=a_ )
| 165
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
a__ : Any = {
"""configuration_wav2vec2""": ["""WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Wav2Vec2Config"""],
"""feature_extraction_wav2vec2""": ["""Wav2Vec2FeatureExtractor"""],
"""processing_wav2vec2""": ["""Wav2Vec2Processor"""],
"""tokenization_wav2vec2""": ["""Wav2Vec2CTCTokenizer""", """Wav2Vec2Tokenizer"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Dict = [
"""WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""Wav2Vec2ForAudioFrameClassification""",
"""Wav2Vec2ForCTC""",
"""Wav2Vec2ForMaskedLM""",
"""Wav2Vec2ForPreTraining""",
"""Wav2Vec2ForSequenceClassification""",
"""Wav2Vec2ForXVector""",
"""Wav2Vec2Model""",
"""Wav2Vec2PreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Any = [
"""TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFWav2Vec2ForCTC""",
"""TFWav2Vec2Model""",
"""TFWav2Vec2PreTrainedModel""",
"""TFWav2Vec2ForSequenceClassification""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a__ : Optional[int] = [
"""FlaxWav2Vec2ForCTC""",
"""FlaxWav2Vec2ForPreTraining""",
"""FlaxWav2Vec2Model""",
"""FlaxWav2Vec2PreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_wavaveca import WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, WavaVecaConfig
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .processing_wavaveca import WavaVecaProcessor
from .tokenization_wavaveca import WavaVecaCTCTokenizer, WavaVecaTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_wavaveca import (
WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST,
WavaVecaForAudioFrameClassification,
WavaVecaForCTC,
WavaVecaForMaskedLM,
WavaVecaForPreTraining,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
WavaVecaModel,
WavaVecaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_wavaveca import (
TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST,
TFWavaVecaForCTC,
TFWavaVecaForSequenceClassification,
TFWavaVecaModel,
TFWavaVecaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_wavaveca import (
FlaxWavaVecaForCTC,
FlaxWavaVecaForPreTraining,
FlaxWavaVecaModel,
FlaxWavaVecaPreTrainedModel,
)
else:
import sys
a__ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 165
| 1
|
'''simple docstring'''
import unittest
import numpy as np
from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_flax_available():
from transformers.models.roberta.modeling_flax_roberta import (
FlaxRobertaForCausalLM,
FlaxRobertaForMaskedLM,
FlaxRobertaForMultipleChoice,
FlaxRobertaForQuestionAnswering,
FlaxRobertaForSequenceClassification,
FlaxRobertaForTokenClassification,
FlaxRobertaModel,
)
class snake_case ( unittest.TestCase ):
"""simple docstring"""
def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=7 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=99 , lowerCAmelCase_=32 , lowerCAmelCase_=5 , lowerCAmelCase_=4 , lowerCAmelCase_=37 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=512 , lowerCAmelCase_=16 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=4 , ):
__lowercase = parent
__lowercase = batch_size
__lowercase = seq_length
__lowercase = is_training
__lowercase = use_attention_mask
__lowercase = use_token_type_ids
__lowercase = use_labels
__lowercase = vocab_size
__lowercase = hidden_size
__lowercase = num_hidden_layers
__lowercase = num_attention_heads
__lowercase = intermediate_size
__lowercase = hidden_act
__lowercase = hidden_dropout_prob
__lowercase = attention_probs_dropout_prob
__lowercase = max_position_embeddings
__lowercase = type_vocab_size
__lowercase = type_sequence_label_size
__lowercase = initializer_range
__lowercase = num_choices
def snake_case__ ( self ):
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__lowercase = None
if self.use_attention_mask:
__lowercase = random_attention_mask([self.batch_size, self.seq_length] )
__lowercase = None
if self.use_token_type_ids:
__lowercase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__lowercase = RobertaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case_ , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def snake_case__ ( self ):
__lowercase = self.prepare_config_and_inputs()
__lowercase , __lowercase , __lowercase , __lowercase = config_and_inputs
__lowercase = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
return config, inputs_dict
def snake_case__ ( self ):
__lowercase = self.prepare_config_and_inputs()
__lowercase , __lowercase , __lowercase , __lowercase = config_and_inputs
__lowercase = True
__lowercase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
__lowercase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
token_type_ids,
encoder_hidden_states,
encoder_attention_mask,
)
@require_flax
class snake_case ( _a ,unittest.TestCase ):
"""simple docstring"""
__lowerCAmelCase = True
__lowerCAmelCase = (
(
FlaxRobertaModel,
FlaxRobertaForCausalLM,
FlaxRobertaForMaskedLM,
FlaxRobertaForSequenceClassification,
FlaxRobertaForTokenClassification,
FlaxRobertaForMultipleChoice,
FlaxRobertaForQuestionAnswering,
)
if is_flax_available()
else ()
)
def snake_case__ ( self ):
__lowercase = FlaxRobertaModelTester(self )
@slow
def snake_case__ ( self ):
for model_class_name in self.all_model_classes:
__lowercase = model_class_name.from_pretrained("roberta-base" , from_pt=snake_case_ )
__lowercase = model(np.ones((1, 1) ) )
self.assertIsNotNone(snake_case_ )
| 720
|
import argparse
import requests
import torch
from PIL import Image
from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor
def __lowercase ( _UpperCAmelCase ) -> int:
'''simple docstring'''
__lowercase = SwinConfig(image_size=192 )
if "base" in model_name:
__lowercase = 6
__lowercase = 128
__lowercase = (2, 2, 18, 2)
__lowercase = (4, 8, 16, 32)
elif "large" in model_name:
__lowercase = 12
__lowercase = 192
__lowercase = (2, 2, 18, 2)
__lowercase = (6, 12, 24, 48)
else:
raise ValueError("Model not supported, only supports base and large variants" )
__lowercase = window_size
__lowercase = embed_dim
__lowercase = depths
__lowercase = num_heads
return config
def __lowercase ( _UpperCAmelCase ) -> List[str]:
'''simple docstring'''
if "encoder.mask_token" in name:
__lowercase = name.replace("encoder.mask_token" , "embeddings.mask_token" )
if "encoder.patch_embed.proj" in name:
__lowercase = name.replace("encoder.patch_embed.proj" , "embeddings.patch_embeddings.projection" )
if "encoder.patch_embed.norm" in name:
__lowercase = name.replace("encoder.patch_embed.norm" , "embeddings.norm" )
if "attn.proj" in name:
__lowercase = name.replace("attn.proj" , "attention.output.dense" )
if "attn" in name:
__lowercase = name.replace("attn" , "attention.self" )
if "norm1" in name:
__lowercase = name.replace("norm1" , "layernorm_before" )
if "norm2" in name:
__lowercase = name.replace("norm2" , "layernorm_after" )
if "mlp.fc1" in name:
__lowercase = name.replace("mlp.fc1" , "intermediate.dense" )
if "mlp.fc2" in name:
__lowercase = name.replace("mlp.fc2" , "output.dense" )
if name == "encoder.norm.weight":
__lowercase = "layernorm.weight"
if name == "encoder.norm.bias":
__lowercase = "layernorm.bias"
if "decoder" in name:
pass
else:
__lowercase = "swin." + name
return name
def __lowercase ( _UpperCAmelCase , _UpperCAmelCase ) -> Any:
'''simple docstring'''
for key in orig_state_dict.copy().keys():
__lowercase = orig_state_dict.pop(_UpperCAmelCase )
if "attn_mask" in key:
pass
elif "qkv" in key:
__lowercase = key.split("." )
__lowercase = int(key_split[2] )
__lowercase = int(key_split[4] )
__lowercase = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
__lowercase = val[:dim, :]
__lowercase = val[
dim : dim * 2, :
]
__lowercase = val[-dim:, :]
else:
__lowercase = val[
:dim
]
__lowercase = val[
dim : dim * 2
]
__lowercase = val[
-dim:
]
else:
__lowercase = val
return orig_state_dict
def __lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> int:
'''simple docstring'''
__lowercase = torch.load(_UpperCAmelCase , map_location="cpu" )["model"]
__lowercase = get_swin_config(_UpperCAmelCase )
__lowercase = SwinForMaskedImageModeling(_UpperCAmelCase )
model.eval()
__lowercase = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase )
model.load_state_dict(_UpperCAmelCase )
__lowercase = "http://images.cocodataset.org/val2017/000000039769.jpg"
__lowercase = ViTImageProcessor(size={"height": 192, "width": 192} )
__lowercase = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw )
__lowercase = image_processor(images=_UpperCAmelCase , return_tensors="pt" )
with torch.no_grad():
__lowercase = model(**_UpperCAmelCase ).logits
print(outputs.keys() )
print("Looks ok!" )
if pytorch_dump_folder_path is not None:
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(_UpperCAmelCase )
print(f'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(_UpperCAmelCase )
if push_to_hub:
print(f'''Pushing model and image processor for {model_name} to hub''' )
model.push_to_hub(f'''microsoft/{model_name}''' )
image_processor.push_to_hub(f'''microsoft/{model_name}''' )
if __name__ == "__main__":
lowerCAmelCase__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='swin-base-simmim-window6-192',
type=str,
choices=['swin-base-simmim-window6-192', 'swin-large-simmim-window12-192'],
help='Name of the Swin SimMIM model you\'d like to convert.',
)
parser.add_argument(
'--checkpoint_path',
default='/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth',
type=str,
help='Path to the original PyTorch checkpoint (.pth file).',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
lowerCAmelCase__ = parser.parse_args()
convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
| 576
| 0
|
"""simple docstring"""
from .configuration_bert_masked import MaskedBertConfig
from .modeling_bert_masked import (
MaskedBertForMultipleChoice,
MaskedBertForQuestionAnswering,
MaskedBertForSequenceClassification,
MaskedBertForTokenClassification,
MaskedBertModel,
)
from .modules import *
| 571
|
"""simple docstring"""
def a_ ( __a ):
if not all(x.isalpha() for x in string ):
raise ValueError('''String must only contain alphabetic characters.''' )
A__ = sorted(string.lower() )
return len(__a ) == len(set(__a ) )
if __name__ == "__main__":
__snake_case : Any = input('Enter a string ').strip()
__snake_case : Dict = is_isogram(input_str)
print(f'{input_str} is {"an" if isogram else "not an"} isogram.')
| 571
| 1
|
'''simple docstring'''
from __future__ import annotations
from PIL import Image
# Define glider example
__magic_name__ : str = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
]
# Define blinker example
__magic_name__ : List[Any] = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
def snake_case_ ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = []
for i in range(len(SCREAMING_SNAKE_CASE__ ) ):
_snake_case = []
for j in range(len(cells[i] ) ):
# Get the number of live neighbours
_snake_case = 0
if i > 0 and j > 0:
neighbour_count += cells[i - 1][j - 1]
if i > 0:
neighbour_count += cells[i - 1][j]
if i > 0 and j < len(cells[i] ) - 1:
neighbour_count += cells[i - 1][j + 1]
if j > 0:
neighbour_count += cells[i][j - 1]
if j < len(cells[i] ) - 1:
neighbour_count += cells[i][j + 1]
if i < len(SCREAMING_SNAKE_CASE__ ) - 1 and j > 0:
neighbour_count += cells[i + 1][j - 1]
if i < len(SCREAMING_SNAKE_CASE__ ) - 1:
neighbour_count += cells[i + 1][j]
if i < len(SCREAMING_SNAKE_CASE__ ) - 1 and j < len(cells[i] ) - 1:
neighbour_count += cells[i + 1][j + 1]
# Rules of the game of life (excerpt from Wikipedia):
# 1. Any live cell with two or three live neighbours survives.
# 2. Any dead cell with three live neighbours becomes a live cell.
# 3. All other live cells die in the next generation.
# Similarly, all other dead cells stay dead.
_snake_case = cells[i][j] == 1
if (
(alive and 2 <= neighbour_count <= 3)
or not alive
and neighbour_count == 3
):
next_generation_row.append(1 )
else:
next_generation_row.append(0 )
next_generation.append(SCREAMING_SNAKE_CASE__ )
return next_generation
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = []
for _ in range(SCREAMING_SNAKE_CASE__ ):
# Create output image
_snake_case = Image.new("RGB" , (len(cells[0] ), len(SCREAMING_SNAKE_CASE__ )) )
_snake_case = img.load()
# Save cells to image
for x in range(len(SCREAMING_SNAKE_CASE__ ) ):
for y in range(len(cells[0] ) ):
_snake_case = 2_55 - cells[y][x] * 2_55
_snake_case = (colour, colour, colour)
# Save image
images.append(SCREAMING_SNAKE_CASE__ )
_snake_case = new_generation(SCREAMING_SNAKE_CASE__ )
return images
if __name__ == "__main__":
__magic_name__ : Optional[Any] = generate_images(GLIDER, 16)
images[0].save("""out.gif""", save_all=True, append_images=images[1:])
| 368
|
'''simple docstring'''
import functools
def snake_case_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
_snake_case = len(SCREAMING_SNAKE_CASE__ )
_snake_case = len(SCREAMING_SNAKE_CASE__ )
@functools.cache
def min_distance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> 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
_snake_case = int(worda[indexa] != worda[indexa] ) # current letters not identical
return min(
1 + min_distance(indexa + 1 , SCREAMING_SNAKE_CASE__ ) , 1 + min_distance(SCREAMING_SNAKE_CASE__ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , )
return min_distance(0 , 0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 368
| 1
|
'''simple docstring'''
def A__ ( __lowerCAmelCase : str ):
assert column_title.isupper()
lowerCamelCase__ = 0
lowerCamelCase__ = len(__lowerCAmelCase ) - 1
lowerCamelCase__ = 0
while index >= 0:
lowerCamelCase__ = (ord(column_title[index] ) - 64) * pow(26 , __lowerCAmelCase )
answer += value
power += 1
index -= 1
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 50
|
# 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
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
__SCREAMING_SNAKE_CASE : Any ={
'''configuration_efficientnet''': [
'''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''EfficientNetConfig''',
'''EfficientNetOnnxConfig''',
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE : List[str] =['''EfficientNetImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE : Optional[int] =[
'''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''EfficientNetForImageClassification''',
'''EfficientNetModel''',
'''EfficientNetPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_efficientnet import (
EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
EfficientNetConfig,
EfficientNetOnnxConfig,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_efficientnet import EfficientNetImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_efficientnet import (
EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
EfficientNetForImageClassification,
EfficientNetModel,
EfficientNetPreTrainedModel,
)
else:
import sys
__SCREAMING_SNAKE_CASE : str =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
| 428
| 0
|
class UpperCamelCase_ :
def __init__( self : str ) -> Optional[Any]:
UpperCAmelCase_ : str = 0
UpperCAmelCase_ : Tuple = 0
UpperCAmelCase_ : Optional[Any] = {}
def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : Union[str, Any] ) -> Union[str, Any]:
if vertex not in self.adjacency:
UpperCAmelCase_ : str = {}
self.num_vertices += 1
def _SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase_ : Any , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str] ) -> Tuple:
self.add_vertex(lowerCAmelCase_ )
self.add_vertex(lowerCAmelCase_ )
if head == tail:
return
UpperCAmelCase_ : str = weight
UpperCAmelCase_ : Union[str, Any] = weight
def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]:
UpperCAmelCase_ : List[str] = self.get_edges()
for edge in edges:
UpperCAmelCase_ : Dict = edge
edges.remove((tail, head, weight) )
for i in range(len(lowerCAmelCase_ ) ):
UpperCAmelCase_ : List[Any] = list(edges[i] )
edges.sort(key=lambda lowerCAmelCase_ : e[2] )
for i in range(len(lowerCAmelCase_ ) - 1 ):
if edges[i][2] >= edges[i + 1][2]:
UpperCAmelCase_ : List[Any] = edges[i][2] + 1
for edge in edges:
UpperCAmelCase_ : Union[str, Any] = edge
UpperCAmelCase_ : Optional[int] = weight
UpperCAmelCase_ : List[str] = weight
def __str__( self : List[str] ) -> Dict:
UpperCAmelCase_ : Optional[int] = ""
for tail in self.adjacency:
for head in self.adjacency[tail]:
UpperCAmelCase_ : Optional[Any] = self.adjacency[head][tail]
string += f"""{head} -> {tail} == {weight}\n"""
return string.rstrip("\n" )
def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]:
UpperCAmelCase_ : str = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]) )
return output
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]:
return self.adjacency.keys()
@staticmethod
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Any=None , lowerCAmelCase_ : Tuple=None ) -> Union[str, Any]:
UpperCAmelCase_ : List[str] = Graph()
if vertices is None:
UpperCAmelCase_ : Optional[Any] = []
if edges is None:
UpperCAmelCase_ : List[Any] = []
for vertex in vertices:
g.add_vertex(lowerCAmelCase_ )
for edge in edges:
g.add_edge(*lowerCAmelCase_ )
return g
class UpperCamelCase_ :
def __init__( self : int ) -> List[Any]:
UpperCAmelCase_ : Tuple = {}
UpperCAmelCase_ : List[str] = {}
def __len__( self : Optional[int] ) -> List[str]:
return len(self.parent )
def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : Any ) -> str:
if item in self.parent:
return self.find(lowerCAmelCase_ )
UpperCAmelCase_ : List[str] = item
UpperCAmelCase_ : Dict = 0
return item
def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase_ : int ) -> Dict:
if item not in self.parent:
return self.make_set(lowerCAmelCase_ )
if item != self.parent[item]:
UpperCAmelCase_ : Optional[int] = self.find(self.parent[item] )
return self.parent[item]
def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[int] ) -> List[Any]:
UpperCAmelCase_ : Union[str, Any] = self.find(lowerCAmelCase_ )
UpperCAmelCase_ : Any = self.find(lowerCAmelCase_ )
if roota == roota:
return roota
if self.rank[roota] > self.rank[roota]:
UpperCAmelCase_ : Tuple = roota
return roota
if self.rank[roota] < self.rank[roota]:
UpperCAmelCase_ : List[Any] = roota
return roota
if self.rank[roota] == self.rank[roota]:
self.rank[roota] += 1
UpperCAmelCase_ : Optional[Any] = roota
return roota
return None
@staticmethod
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase_ : Union[str, Any] ) -> int:
UpperCAmelCase_ : Union[str, Any] = graph.num_vertices
UpperCAmelCase_ : Any = Graph.UnionFind()
UpperCAmelCase_ : int = []
while num_components > 1:
UpperCAmelCase_ : Dict = {}
for vertex in graph.get_vertices():
UpperCAmelCase_ : Dict = -1
UpperCAmelCase_ : Dict = graph.get_edges()
for edge in edges:
UpperCAmelCase_ : List[Any] = edge
edges.remove((tail, head, weight) )
for edge in edges:
UpperCAmelCase_ : Union[str, Any] = edge
UpperCAmelCase_ : Optional[Any] = union_find.find(lowerCAmelCase_ )
UpperCAmelCase_ : Dict = union_find.find(lowerCAmelCase_ )
if seta != seta:
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
UpperCAmelCase_ : str = [head, tail, weight]
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
UpperCAmelCase_ : Optional[Any] = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
UpperCAmelCase_ : Tuple = cheap_edge[vertex]
if union_find.find(lowerCAmelCase_ ) != union_find.find(lowerCAmelCase_ ):
union_find.union(lowerCAmelCase_ , lowerCAmelCase_ )
mst_edges.append(cheap_edge[vertex] )
UpperCAmelCase_ : List[Any] = num_components - 1
UpperCAmelCase_ : List[str] = Graph.build(edges=lowerCAmelCase_ )
return mst
| 704
|
"""simple docstring"""
import math
from typing import Callable, List, Optional, Union
import numpy as np
import PIL
import torch
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler
def snake_case ( A__ ,A__ ,A__=[] ):
UpperCAmelCase_ : int = size[0] - overlap_pixels * 2
UpperCAmelCase_ : Dict = size[1] - overlap_pixels * 2
for letter in ["l", "r"]:
if letter in remove_borders:
size_x += overlap_pixels
for letter in ["t", "b"]:
if letter in remove_borders:
size_y += overlap_pixels
UpperCAmelCase_ : Union[str, Any] = np.ones((size_y, size_x) ,dtype=np.uinta ) * 2_55
UpperCAmelCase_ : Optional[int] = np.pad(A__ ,mode="linear_ramp" ,pad_width=A__ ,end_values=0 )
if "l" in remove_borders:
UpperCAmelCase_ : List[str] = mask[:, overlap_pixels : mask.shape[1]]
if "r" in remove_borders:
UpperCAmelCase_ : Any = mask[:, 0 : mask.shape[1] - overlap_pixels]
if "t" in remove_borders:
UpperCAmelCase_ : Optional[int] = mask[overlap_pixels : mask.shape[0], :]
if "b" in remove_borders:
UpperCAmelCase_ : Any = mask[0 : mask.shape[0] - overlap_pixels, :]
return mask
def snake_case ( A__ ,A__ ,A__ ):
return max(A__ ,min(A__ ,A__ ) )
def snake_case ( A__ ,A__ ,A__ ):
return (
clamp(rect[0] ,min[0] ,max[0] ),
clamp(rect[1] ,min[1] ,max[1] ),
clamp(rect[2] ,min[0] ,max[0] ),
clamp(rect[3] ,min[1] ,max[1] ),
)
def snake_case ( A__ ,A__ ,A__ ):
UpperCAmelCase_ : List[str] = list(A__ )
rect[0] -= overlap
rect[1] -= overlap
rect[2] += overlap
rect[3] += overlap
UpperCAmelCase_ : Optional[Any] = clamp_rect(A__ ,[0, 0] ,[image_size[0], image_size[1]] )
return rect
def snake_case ( A__ ,A__ ,A__ ,A__ ):
UpperCAmelCase_ : Dict = Image.new("RGB" ,(tile.size[0] + original_slice, tile.size[1]) )
result.paste(
original_image.resize((tile.size[0], tile.size[1]) ,Image.BICUBIC ).crop(
(slice_x, 0, slice_x + original_slice, tile.size[1]) ) ,(0, 0) ,)
result.paste(A__ ,(original_slice, 0) )
return result
def snake_case ( A__ ,A__ ):
UpperCAmelCase_ : Optional[int] = (original_image_slice * 4, 0, tile.size[0], tile.size[1])
UpperCAmelCase_ : Optional[int] = tile.crop(A__ )
return tile
def snake_case ( A__ ,A__ ):
UpperCAmelCase_ : List[str] = n % d
return n - divisor
class UpperCamelCase_ (__A ):
def __init__( self : List[str] , lowerCAmelCase_ : AutoencoderKL , lowerCAmelCase_ : CLIPTextModel , lowerCAmelCase_ : CLIPTokenizer , lowerCAmelCase_ : UNetaDConditionModel , lowerCAmelCase_ : DDPMScheduler , lowerCAmelCase_ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCAmelCase_ : int = 350 , ) -> Optional[Any]:
super().__init__(
vae=lowerCAmelCase_ , text_encoder=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , unet=lowerCAmelCase_ , low_res_scheduler=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , max_noise_level=lowerCAmelCase_ , )
def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Any , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : Any , **lowerCAmelCase_ : List[str] ) -> Dict:
torch.manual_seed(0 )
UpperCAmelCase_ : Optional[Any] = (
min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ),
min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ),
min(image.size[0] , (x + 1) * tile_size ),
min(image.size[1] , (y + 1) * tile_size ),
)
UpperCAmelCase_ : Dict = add_overlap_rect(lowerCAmelCase_ , lowerCAmelCase_ , image.size )
UpperCAmelCase_ : Tuple = image.crop(lowerCAmelCase_ )
UpperCAmelCase_ : Any = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
UpperCAmelCase_ : int = translated_slice_x - (original_image_slice / 2)
UpperCAmelCase_ : Any = max(0 , lowerCAmelCase_ )
UpperCAmelCase_ : Optional[Any] = squeeze_tile(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
UpperCAmelCase_ : Any = to_input.size
UpperCAmelCase_ : Optional[int] = to_input.resize((tile_size, tile_size) , Image.BICUBIC )
UpperCAmelCase_ : Optional[Any] = super(lowerCAmelCase_ , self ).__call__(image=lowerCAmelCase_ , **lowerCAmelCase_ ).images[0]
UpperCAmelCase_ : Union[str, Any] = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC )
UpperCAmelCase_ : List[Any] = unsqueeze_tile(lowerCAmelCase_ , lowerCAmelCase_ )
UpperCAmelCase_ : List[str] = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC )
UpperCAmelCase_ : List[Any] = []
if x == 0:
remove_borders.append("l" )
elif crop_rect[2] == image.size[0]:
remove_borders.append("r" )
if y == 0:
remove_borders.append("t" )
elif crop_rect[3] == image.size[1]:
remove_borders.append("b" )
UpperCAmelCase_ : str = Image.fromarray(
make_transparency_mask(
(upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=lowerCAmelCase_ ) , mode="L" , )
final_image.paste(
lowerCAmelCase_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , lowerCAmelCase_ )
@torch.no_grad()
def __call__( self : int , lowerCAmelCase_ : Union[str, List[str]] , lowerCAmelCase_ : Union[PIL.Image.Image, List[PIL.Image.Image]] , lowerCAmelCase_ : int = 75 , lowerCAmelCase_ : float = 9.0 , lowerCAmelCase_ : int = 50 , lowerCAmelCase_ : Optional[Union[str, List[str]]] = None , lowerCAmelCase_ : Optional[int] = 1 , lowerCAmelCase_ : float = 0.0 , lowerCAmelCase_ : Optional[torch.Generator] = None , lowerCAmelCase_ : Optional[torch.FloatTensor] = None , lowerCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : int = 128 , lowerCAmelCase_ : int = 32 , lowerCAmelCase_ : int = 32 , ) -> int:
UpperCAmelCase_ : List[Any] = Image.new("RGB" , (image.size[0] * 4, image.size[1] * 4) )
UpperCAmelCase_ : Any = math.ceil(image.size[0] / tile_size )
UpperCAmelCase_ : str = math.ceil(image.size[1] / tile_size )
UpperCAmelCase_ : Any = tcx * tcy
UpperCAmelCase_ : List[Any] = 0
for y in range(lowerCAmelCase_ ):
for x in range(lowerCAmelCase_ ):
self._process_tile(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , prompt=lowerCAmelCase_ , num_inference_steps=lowerCAmelCase_ , guidance_scale=lowerCAmelCase_ , noise_level=lowerCAmelCase_ , negative_prompt=lowerCAmelCase_ , num_images_per_prompt=lowerCAmelCase_ , eta=lowerCAmelCase_ , generator=lowerCAmelCase_ , latents=lowerCAmelCase_ , )
current_count += 1
if callback is not None:
callback({"progress": current_count / total_tile_count, "image": final_image} )
return final_image
def snake_case ( ):
# Run a demo
UpperCAmelCase_ : List[str] = "stabilityai/stable-diffusion-x4-upscaler"
UpperCAmelCase_ : Optional[Any] = StableDiffusionTiledUpscalePipeline.from_pretrained(A__ ,revision="fp16" ,torch_dtype=torch.floataa )
UpperCAmelCase_ : Optional[int] = pipe.to("cuda" )
UpperCAmelCase_ : Tuple = Image.open("../../docs/source/imgs/diffusers_library.jpg" )
def callback(A__ ):
print(F"""progress: {obj['progress']:.4f}""" )
obj["image"].save("diffusers_library_progress.jpg" )
UpperCAmelCase_ : Union[str, Any] = pipe(image=A__ ,prompt="Black font, white background, vector" ,noise_level=40 ,callback=A__ )
final_image.save("diffusers_library.jpg" )
if __name__ == "__main__":
main()
| 463
| 0
|
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
execute_subprocess_async,
require_cpu,
require_huggingface_suite,
require_multi_gpu,
require_single_gpu,
)
from accelerate.utils import patch_environment
@require_huggingface_suite
class SCREAMING_SNAKE_CASE__ (unittest.TestCase ):
def snake_case_ ( self):
lowercase__ : int = inspect.getfile(accelerate.test_utils)
lowercase__ : Dict = os.path.sep.join(
mod_file.split(os.path.sep)[:-1] + ['scripts', 'external_deps', 'test_metrics.py'])
from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401
lowercase__ : Optional[Any] = test_metrics
@require_cpu
def snake_case_ ( self):
debug_launcher(self.test_metrics.main , num_processes=1)
@require_cpu
def snake_case_ ( self):
debug_launcher(self.test_metrics.main)
@require_single_gpu
def snake_case_ ( self):
self.test_metrics.main()
@require_multi_gpu
def snake_case_ ( self):
print(f"""Found {torch.cuda.device_count()} devices.""")
lowercase__ : int = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1):
execute_subprocess_async(a , env=os.environ.copy())
| 164
|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
snake_case_ = logging.get_logger(__name__)
snake_case_ = {
'''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''',
'''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''',
}
class SCREAMING_SNAKE_CASE__ (__snake_case ):
__lowerCamelCase : Dict = """luke"""
def __init__( self , a=5_0267 , a=50_0000 , a=768 , a=256 , a=12 , a=12 , a=3072 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=2 , a=0.02 , a=1e-12 , a=True , a=None , a=1 , a=0 , a=2 , **a , ):
super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a)
lowercase__ : Tuple = vocab_size
lowercase__ : Optional[Any] = entity_vocab_size
lowercase__ : Optional[int] = hidden_size
lowercase__ : List[str] = entity_emb_size
lowercase__ : Union[str, Any] = num_hidden_layers
lowercase__ : Any = num_attention_heads
lowercase__ : List[str] = hidden_act
lowercase__ : Any = intermediate_size
lowercase__ : str = hidden_dropout_prob
lowercase__ : List[Any] = attention_probs_dropout_prob
lowercase__ : List[Any] = max_position_embeddings
lowercase__ : Dict = type_vocab_size
lowercase__ : Tuple = initializer_range
lowercase__ : Any = layer_norm_eps
lowercase__ : Optional[Any] = use_entity_aware_attention
lowercase__ : Union[str, Any] = classifier_dropout
| 164
| 1
|
'''simple docstring'''
import copy
import re
class a :
"""simple docstring"""
__lowerCAmelCase = """hp"""
__lowerCAmelCase = {}
__lowerCAmelCase = None
@classmethod
def lowercase_ ( cls , snake_case_ , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Union[str, Any] = prefix
__UpperCAmelCase: Tuple = defaults
cls.build_naming_info()
@staticmethod
def lowercase_ ( snake_case_ , snake_case_ ):
'''simple docstring'''
if len(lowerCamelCase_ ) == 0:
return ""
__UpperCAmelCase: Optional[Any] = None
if any(char.isdigit() for char in word ):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''' )
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(lowerCamelCase_ ) + 1 ):
__UpperCAmelCase: List[str] = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
__UpperCAmelCase: Any = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(snake_case_ ):
__UpperCAmelCase: str = """"""
while integer != 0:
__UpperCAmelCase: Optional[int] = chr(ord("""A""" ) + integer % 10 ) + s
integer //= 10
return s
__UpperCAmelCase: Union[str, Any] = 0
while True:
__UpperCAmelCase: List[Any] = word + """#""" + int_to_alphabetic(lowerCamelCase_ )
if sword in info["reverse_short_word"]:
continue
else:
__UpperCAmelCase: List[str] = sword
break
__UpperCAmelCase: Tuple = short_word
__UpperCAmelCase: int = word
return short_word
@staticmethod
def lowercase_ ( snake_case_ , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Dict = param_name.split("""_""" )
__UpperCAmelCase: Dict = [TrialShortNamer.shortname_for_word(lowerCamelCase_ , lowerCamelCase_ ) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
__UpperCAmelCase: Tuple = ["""""", """_"""]
for separator in separators:
__UpperCAmelCase: List[Any] = separator.join(lowerCamelCase_ )
if shortname not in info["reverse_short_param"]:
__UpperCAmelCase: str = shortname
__UpperCAmelCase: List[str] = param_name
return shortname
return param_name
@staticmethod
def lowercase_ ( snake_case_ , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: Dict = TrialShortNamer.shortname_for_key(lowerCamelCase_ , lowerCamelCase_ )
__UpperCAmelCase: Optional[Any] = short_name
__UpperCAmelCase: int = param_name
@classmethod
def lowercase_ ( cls ):
'''simple docstring'''
if cls.NAMING_INFO is not None:
return
__UpperCAmelCase: Optional[Any] = {
"""short_word""": {},
"""reverse_short_word""": {},
"""short_param""": {},
"""reverse_short_param""": {},
}
__UpperCAmelCase: Dict = list(cls.DEFAULTS.keys() )
for k in field_keys:
cls.add_new_param_name(lowerCamelCase_ , lowerCamelCase_ )
__UpperCAmelCase: Tuple = info
@classmethod
def lowercase_ ( cls , snake_case_ ):
'''simple docstring'''
cls.build_naming_info()
assert cls.PREFIX is not None
__UpperCAmelCase: List[Any] = [copy.copy(cls.PREFIX )]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''' )
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
__UpperCAmelCase: Dict = cls.NAMING_INFO["""short_param"""][k]
if isinstance(lowerCamelCase_ , lowerCamelCase_ ):
__UpperCAmelCase: List[str] = 1 if v else 0
__UpperCAmelCase: Dict = """""" if isinstance(lowerCamelCase_ , (int, float) ) else """-"""
__UpperCAmelCase: List[Any] = F'''{key}{sep}{v}'''
name.append(lowerCamelCase_ )
return "_".join(lowerCamelCase_ )
@classmethod
def lowercase_ ( cls , snake_case_ ):
'''simple docstring'''
__UpperCAmelCase: int = repr[len(cls.PREFIX ) + 1 :]
if repr == "":
__UpperCAmelCase: Optional[Any] = []
else:
__UpperCAmelCase: Union[str, Any] = repr.split("""_""" )
__UpperCAmelCase: int = {}
for value in values:
if "-" in value:
__UpperCAmelCase: List[Any] = value.split("""-""" )
else:
__UpperCAmelCase: Union[str, Any] = re.sub("""[0-9.]""" , """""" , lowerCamelCase_ )
__UpperCAmelCase: str = float(re.sub("""[^0-9.]""" , """""" , lowerCamelCase_ ) )
__UpperCAmelCase: Tuple = cls.NAMING_INFO["""reverse_short_param"""][p_k]
__UpperCAmelCase: List[str] = p_v
for k in cls.DEFAULTS:
if k not in parameters:
__UpperCAmelCase: Tuple = cls.DEFAULTS[k]
return parameters
| 713
|
'''simple docstring'''
import itertools
import math
def UpperCamelCase__ ( _lowercase : int ) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(_lowercase ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def UpperCamelCase__ ( ) -> Optional[int]:
__UpperCAmelCase: Union[str, Any] = 2
while True:
if is_prime(_lowercase ):
yield num
num += 1
def UpperCamelCase__ ( _lowercase : int = 1_0_0_0_1 ) -> int:
return next(itertools.islice(prime_generator() , nth - 1 , _lowercase ) )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 466
| 0
|
def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ):
if p < 2:
raise ValueError('p should not be less than 2!' )
elif p == 2:
return True
lowercase = 4
lowercase = (1 << p) - 1
for _ in range(p - 2 ):
lowercase = ((s * s) - 2) % m
return s == 0
if __name__ == "__main__":
print(lucas_lehmer_test(7))
print(lucas_lehmer_test(11))
| 84
|
from collections import Counter
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
lowercase_ = datasets.load_iris()
lowercase_ = np.array(data['''data'''])
lowercase_ = np.array(data['''target'''])
lowercase_ = data['''target_names''']
lowercase_ , lowercase_ , lowercase_ , lowercase_ = train_test_split(X, y)
def __lowerCAmelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] ) -> Optional[int]:
return np.linalg.norm(np.array(__lowerCamelCase ) - np.array(__lowerCamelCase ) )
def __lowerCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int=5 ) -> str:
__lowerCAmelCase =zip(__lowerCamelCase , __lowerCamelCase )
# List of distances of all points from the point to be classified
__lowerCAmelCase =[]
for data_point in data:
__lowerCAmelCase =euclidean_distance(data_point[0] , __lowerCamelCase )
distances.append((distance, data_point[1]) )
# Choosing 'k' points with the least distances.
__lowerCAmelCase =[i[1] for i in sorted(__lowerCamelCase )[:k]]
# Most commonly occurring class among them
# is the class into which the point is classified
__lowerCAmelCase =Counter(__lowerCamelCase ).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]))
| 354
| 0
|
import copy
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
_lowercase = logging.get_logger(__name__)
_lowercase = {
'''microsoft/conditional-detr-resnet-50''': (
'''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'''
),
}
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = 'conditional_detr'
UpperCamelCase_ = ['past_key_values']
UpperCamelCase_ = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self : Union[str, Any] ,lowerCAmelCase__ : Optional[int]=True ,lowerCAmelCase__ : Dict=None ,lowerCAmelCase__ : Optional[int]=3 ,lowerCAmelCase__ : int=3_00 ,lowerCAmelCase__ : List[Any]=6 ,lowerCAmelCase__ : int=20_48 ,lowerCAmelCase__ : str=8 ,lowerCAmelCase__ : Tuple=6 ,lowerCAmelCase__ : str=20_48 ,lowerCAmelCase__ : str=8 ,lowerCAmelCase__ : Union[str, Any]=0.0 ,lowerCAmelCase__ : Optional[Any]=0.0 ,lowerCAmelCase__ : Optional[Any]=True ,lowerCAmelCase__ : str="relu" ,lowerCAmelCase__ : List[str]=2_56 ,lowerCAmelCase__ : Dict=0.1 ,lowerCAmelCase__ : Optional[int]=0.0 ,lowerCAmelCase__ : Dict=0.0 ,lowerCAmelCase__ : str=0.02 ,lowerCAmelCase__ : List[str]=1.0 ,lowerCAmelCase__ : Any=False ,lowerCAmelCase__ : int="sine" ,lowerCAmelCase__ : int="resnet50" ,lowerCAmelCase__ : Tuple=True ,lowerCAmelCase__ : Tuple=False ,lowerCAmelCase__ : Optional[int]=2 ,lowerCAmelCase__ : List[str]=5 ,lowerCAmelCase__ : Any=2 ,lowerCAmelCase__ : Dict=1 ,lowerCAmelCase__ : Any=1 ,lowerCAmelCase__ : Optional[int]=2 ,lowerCAmelCase__ : Tuple=5 ,lowerCAmelCase__ : Any=2 ,lowerCAmelCase__ : Union[str, Any]=0.25 ,**lowerCAmelCase__ : Optional[int] ,) -> Optional[int]:
'''simple docstring'''
if backbone_config is not None and use_timm_backbone:
raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." )
if not use_timm_backbone:
if backbone_config is None:
logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." )
lowerCAmelCase_ : Dict = CONFIG_MAPPING["resnet"](out_features=["stage4"] )
elif isinstance(lowerCAmelCase__ ,lowerCAmelCase__ ):
lowerCAmelCase_ : Dict = backbone_config.get("model_type" )
lowerCAmelCase_ : Tuple = CONFIG_MAPPING[backbone_model_type]
lowerCAmelCase_ : Tuple = config_class.from_dict(lowerCAmelCase__ )
lowerCAmelCase_ : Optional[int] = use_timm_backbone
lowerCAmelCase_ : Optional[int] = backbone_config
lowerCAmelCase_ : Union[str, Any] = num_channels
lowerCAmelCase_ : int = num_queries
lowerCAmelCase_ : Union[str, Any] = d_model
lowerCAmelCase_ : Tuple = encoder_ffn_dim
lowerCAmelCase_ : Union[str, Any] = encoder_layers
lowerCAmelCase_ : List[Any] = encoder_attention_heads
lowerCAmelCase_ : Optional[Any] = decoder_ffn_dim
lowerCAmelCase_ : Optional[int] = decoder_layers
lowerCAmelCase_ : Tuple = decoder_attention_heads
lowerCAmelCase_ : Tuple = dropout
lowerCAmelCase_ : List[Any] = attention_dropout
lowerCAmelCase_ : int = activation_dropout
lowerCAmelCase_ : Optional[int] = activation_function
lowerCAmelCase_ : Tuple = init_std
lowerCAmelCase_ : Optional[Any] = init_xavier_std
lowerCAmelCase_ : List[Any] = encoder_layerdrop
lowerCAmelCase_ : List[str] = decoder_layerdrop
lowerCAmelCase_ : int = encoder_layers
lowerCAmelCase_ : List[Any] = auxiliary_loss
lowerCAmelCase_ : int = position_embedding_type
lowerCAmelCase_ : Tuple = backbone
lowerCAmelCase_ : Dict = use_pretrained_backbone
lowerCAmelCase_ : str = dilation
# Hungarian matcher
lowerCAmelCase_ : List[str] = class_cost
lowerCAmelCase_ : Union[str, Any] = bbox_cost
lowerCAmelCase_ : Dict = giou_cost
# Loss coefficients
lowerCAmelCase_ : Tuple = mask_loss_coefficient
lowerCAmelCase_ : str = dice_loss_coefficient
lowerCAmelCase_ : Dict = cls_loss_coefficient
lowerCAmelCase_ : str = bbox_loss_coefficient
lowerCAmelCase_ : Optional[int] = giou_loss_coefficient
lowerCAmelCase_ : Optional[Any] = focal_alpha
super().__init__(is_encoder_decoder=lowerCAmelCase__ ,**lowerCAmelCase__ )
@property
def UpperCAmelCase_ ( self : str ) -> int:
'''simple docstring'''
return self.encoder_attention_heads
@property
def UpperCAmelCase_ ( self : str ) -> int:
'''simple docstring'''
return self.d_model
def UpperCAmelCase_ ( self : Optional[int] ) -> str:
'''simple docstring'''
lowerCAmelCase_ : int = copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
lowerCAmelCase_ : Optional[Any] = self.backbone_config.to_dict()
lowerCAmelCase_ : Any = self.__class__.model_type
return output
class __snake_case ( snake_case__ ):
"""simple docstring"""
UpperCamelCase_ = version.parse('1.11' )
@property
def UpperCAmelCase_ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
return OrderedDict(
[
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
("pixel_mask", {0: "batch"}),
] )
@property
def UpperCAmelCase_ ( self : int ) -> float:
'''simple docstring'''
return 1e-5
@property
def UpperCAmelCase_ ( self : Optional[int] ) -> int:
'''simple docstring'''
return 12
| 712
|
import pytest
_lowercase = '''__dummy_dataset1__'''
_lowercase = '''
import json
import os
import datasets
REPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"
URLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}
class __DummyDataset1__(datasets.GeneratorBasedBuilder):
def _info(self):
features = datasets.Features(
{
"tokens": datasets.Sequence(datasets.Value("string")),
"ner_tags": datasets.Sequence(
datasets.features.ClassLabel(
names=[
"O",
"B-PER",
"I-PER",
"B-ORG",
"I-ORG",
"B-LOC",
"I-LOC",
]
)
),
"langs": datasets.Sequence(datasets.Value("string")),
"spans": datasets.Sequence(datasets.Value("string")),
}
)
return datasets.DatasetInfo(features=features)
def _split_generators(self, dl_manager):
dl_path = dl_manager.download(URLS)
return [
datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),
datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),
]
def _generate_examples(self, filepath):
with open(filepath, "r", encoding="utf-8") as f:
for i, line in enumerate(f):
yield i, json.loads(line)
'''
@pytest.fixture
def UpperCamelCase ( ):
return DATASET_LOADING_SCRIPT_NAME
@pytest.fixture
def UpperCamelCase ( ):
return DATASET_LOADING_SCRIPT_CODE
@pytest.fixture
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__):
lowerCAmelCase_ : List[Any] = dataset_loading_script_name
lowerCAmelCase_ : List[str] = tmp_path / "datasets" / script_name
script_dir.mkdir(parents=snake_case__)
lowerCAmelCase_ : List[Any] = script_dir / F'''{script_name}.py'''
with open(snake_case__ , "w") as f:
f.write(snake_case__)
return str(snake_case__)
| 683
| 0
|
'''simple docstring'''
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: float, SCREAMING_SNAKE_CASE__: list[float] ) -> float:
"""simple docstring"""
if discount_rate < 0:
raise ValueError('Discount rate cannot be negative' )
if not cash_flows:
raise ValueError('Cash flows list cannot be empty' )
__a = sum(
cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(SCREAMING_SNAKE_CASE__ ) )
return round(SCREAMING_SNAKE_CASE__, ndigits=2 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 448
|
'''simple docstring'''
import copy
import random
from transformers import CLIPTokenizer
class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ):
def __init__( self , *lowerCamelCase , **lowerCamelCase ) ->Union[str, Any]:
'''simple docstring'''
super().__init__(*lowerCamelCase , **lowerCamelCase )
__a = {}
def __UpperCamelCase ( self , lowerCamelCase , *lowerCamelCase , **lowerCamelCase ) ->Dict:
'''simple docstring'''
__a = super().add_tokens(lowerCamelCase , *lowerCamelCase , **lowerCamelCase )
if num_added_tokens == 0:
raise ValueError(
F"""The tokenizer already contains the token {placeholder_token}. Please pass a different"""
' `placeholder_token` that is not already in the tokenizer.' )
def __UpperCamelCase ( self , lowerCamelCase , *lowerCamelCase , lowerCamelCase=1 , **lowerCamelCase ) ->List[str]:
'''simple docstring'''
__a = []
if num_vec_per_token == 1:
self.try_adding_tokens(lowerCamelCase , *lowerCamelCase , **lowerCamelCase )
output.append(lowerCamelCase )
else:
__a = []
for i in range(lowerCamelCase ):
__a = placeholder_token + F"""_{i}"""
self.try_adding_tokens(lowerCamelCase , *lowerCamelCase , **lowerCamelCase )
output.append(lowerCamelCase )
# handle cases where there is a new placeholder token that contains the current placeholder token but is larger
for token in self.token_map:
if token in placeholder_token:
raise ValueError(
F"""The tokenizer already has placeholder token {token} that can get confused with"""
F""" {placeholder_token}keep placeholder tokens independent""" )
__a = output
def __UpperCamelCase ( self , lowerCamelCase , lowerCamelCase=False , lowerCamelCase=1.0 ) ->int:
'''simple docstring'''
if isinstance(lowerCamelCase , lowerCamelCase ):
__a = []
for i in range(len(lowerCamelCase ) ):
output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=lowerCamelCase ) )
return output
for placeholder_token in self.token_map:
if placeholder_token in text:
__a = self.token_map[placeholder_token]
__a = tokens[: 1 + int(len(lowerCamelCase ) * prop_tokens_to_load )]
if vector_shuffle:
__a = copy.copy(lowerCamelCase )
random.shuffle(lowerCamelCase )
__a = text.replace(lowerCamelCase , ' '.join(lowerCamelCase ) )
return text
def __call__( self , lowerCamelCase , *lowerCamelCase , lowerCamelCase=False , lowerCamelCase=1.0 , **lowerCamelCase ) ->Optional[int]:
'''simple docstring'''
return super().__call__(
self.replace_placeholder_tokens_in_text(
lowerCamelCase , vector_shuffle=lowerCamelCase , prop_tokens_to_load=lowerCamelCase ) , *lowerCamelCase , **lowerCamelCase , )
def __UpperCamelCase ( self , lowerCamelCase , *lowerCamelCase , lowerCamelCase=False , lowerCamelCase=1.0 , **lowerCamelCase ) ->List[Any]:
'''simple docstring'''
return super().encode(
self.replace_placeholder_tokens_in_text(
lowerCamelCase , vector_shuffle=lowerCamelCase , prop_tokens_to_load=lowerCamelCase ) , *lowerCamelCase , **lowerCamelCase , )
| 448
| 1
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_tokenizers_available,
is_torch_available,
)
__UpperCAmelCase = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase = ["""NllbTokenizer"""]
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase = ["""NllbTokenizerFast"""]
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_nllb import NllbTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_nllb_fast import NllbTokenizerFast
else:
import sys
__UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 718
|
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class SCREAMING_SNAKE_CASE ( a_ ):
"""simple docstring"""
lowerCamelCase : Optional[Any] =(DPMSolverSinglestepScheduler,)
lowerCamelCase : Optional[Any] =(("num_inference_steps", 25),)
def SCREAMING_SNAKE_CASE ( self : str , **lowerCAmelCase : str ) -> List[str]:
"""simple docstring"""
__lowerCAmelCase : List[str] = {
"""num_train_timesteps""": 10_00,
"""beta_start""": 0.0001,
"""beta_end""": 0.02,
"""beta_schedule""": """linear""",
"""solver_order""": 2,
"""prediction_type""": """epsilon""",
"""thresholding""": False,
"""sample_max_value""": 1.0,
"""algorithm_type""": """dpmsolver++""",
"""solver_type""": """midpoint""",
"""lambda_min_clipped""": -float("""inf""" ),
"""variance_type""": None,
}
config.update(**lowerCAmelCase )
return config
def SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase : Union[str, Any]=0 , **lowerCAmelCase : Dict ) -> int:
"""simple docstring"""
__lowerCAmelCase : Dict = dict(self.forward_default_kwargs )
__lowerCAmelCase : List[str] = kwargs.pop("""num_inference_steps""" , lowerCAmelCase )
__lowerCAmelCase : Any = self.dummy_sample
__lowerCAmelCase : Dict = 0.1 * sample
__lowerCAmelCase : Dict = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
__lowerCAmelCase : Any = self.get_scheduler_config(**lowerCAmelCase )
__lowerCAmelCase : Any = scheduler_class(**lowerCAmelCase )
scheduler.set_timesteps(lowerCAmelCase )
# copy over dummy past residuals
__lowerCAmelCase : Dict = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase )
__lowerCAmelCase : Dict = scheduler_class.from_pretrained(lowerCAmelCase )
new_scheduler.set_timesteps(lowerCAmelCase )
# copy over dummy past residuals
__lowerCAmelCase : Union[str, Any] = dummy_past_residuals[: new_scheduler.config.solver_order]
__lowerCAmelCase ,__lowerCAmelCase : Tuple = sample, sample
for t in range(lowerCAmelCase , time_step + scheduler.config.solver_order + 1 ):
__lowerCAmelCase : Any = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , **lowerCAmelCase ).prev_sample
__lowerCAmelCase : Union[str, Any] = new_scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , **lowerCAmelCase ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]:
"""simple docstring"""
pass
def SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase : List[str]=0 , **lowerCAmelCase : List[Any] ) -> Dict:
"""simple docstring"""
__lowerCAmelCase : str = dict(self.forward_default_kwargs )
__lowerCAmelCase : Union[str, Any] = kwargs.pop("""num_inference_steps""" , lowerCAmelCase )
__lowerCAmelCase : Optional[int] = self.dummy_sample
__lowerCAmelCase : Dict = 0.1 * sample
__lowerCAmelCase : Optional[int] = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
__lowerCAmelCase : Optional[int] = self.get_scheduler_config()
__lowerCAmelCase : List[Any] = scheduler_class(**lowerCAmelCase )
scheduler.set_timesteps(lowerCAmelCase )
# copy over dummy past residuals (must be after setting timesteps)
__lowerCAmelCase : Any = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(lowerCAmelCase )
__lowerCAmelCase : Dict = scheduler_class.from_pretrained(lowerCAmelCase )
# copy over dummy past residuals
new_scheduler.set_timesteps(lowerCAmelCase )
# copy over dummy past residual (must be after setting timesteps)
__lowerCAmelCase : Optional[int] = dummy_past_residuals[: new_scheduler.config.solver_order]
__lowerCAmelCase : Union[str, Any] = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , **lowerCAmelCase ).prev_sample
__lowerCAmelCase : Optional[int] = new_scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , **lowerCAmelCase ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase : str=None , **lowerCAmelCase : Optional[Any] ) -> Tuple:
"""simple docstring"""
if scheduler is None:
__lowerCAmelCase : Dict = self.scheduler_classes[0]
__lowerCAmelCase : Dict = self.get_scheduler_config(**lowerCAmelCase )
__lowerCAmelCase : Optional[Any] = scheduler_class(**lowerCAmelCase )
__lowerCAmelCase : List[str] = self.scheduler_classes[0]
__lowerCAmelCase : int = self.get_scheduler_config(**lowerCAmelCase )
__lowerCAmelCase : Any = scheduler_class(**lowerCAmelCase )
__lowerCAmelCase : str = 10
__lowerCAmelCase : str = self.dummy_model()
__lowerCAmelCase : Optional[int] = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase )
for i, t in enumerate(scheduler.timesteps ):
__lowerCAmelCase : Optional[Any] = model(lowerCAmelCase , lowerCAmelCase )
__lowerCAmelCase : int = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).prev_sample
return sample
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str:
"""simple docstring"""
__lowerCAmelCase : str = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
__lowerCAmelCase : Union[str, Any] = 50
__lowerCAmelCase : Union[str, Any] = self.dummy_model()
__lowerCAmelCase : Any = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase )
# make sure that the first t is uneven
for i, t in enumerate(scheduler.timesteps[3:] ):
__lowerCAmelCase : Dict = model(lowerCAmelCase , lowerCAmelCase )
__lowerCAmelCase : str = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).prev_sample
__lowerCAmelCase : List[str] = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.2574 ) < 1e-3
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
for timesteps in [25, 50, 1_00, 9_99, 10_00]:
self.check_over_configs(num_train_timesteps=lowerCAmelCase )
def SCREAMING_SNAKE_CASE ( self : int ) -> Tuple:
"""simple docstring"""
__lowerCAmelCase : Optional[Any] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
__lowerCAmelCase : int = self.full_loop(scheduler=lowerCAmelCase )
__lowerCAmelCase : Any = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.2791 ) < 1e-3
__lowerCAmelCase : Optional[Any] = DEISMultistepScheduler.from_config(scheduler.config )
__lowerCAmelCase : Dict = DPMSolverMultistepScheduler.from_config(scheduler.config )
__lowerCAmelCase : Any = UniPCMultistepScheduler.from_config(scheduler.config )
__lowerCAmelCase : Any = DPMSolverSinglestepScheduler.from_config(scheduler.config )
__lowerCAmelCase : List[str] = self.full_loop(scheduler=lowerCAmelCase )
__lowerCAmelCase : str = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.2791 ) < 1e-3
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> List[Any]:
"""simple docstring"""
self.check_over_configs(thresholding=lowerCAmelCase )
for order in [1, 2, 3]:
for solver_type in ["midpoint", "heun"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=lowerCAmelCase , prediction_type=lowerCAmelCase , sample_max_value=lowerCAmelCase , algorithm_type="""dpmsolver++""" , solver_order=lowerCAmelCase , solver_type=lowerCAmelCase , )
def SCREAMING_SNAKE_CASE ( self : int ) -> Any:
"""simple docstring"""
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=lowerCAmelCase )
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
for algorithm_type in ["dpmsolver", "dpmsolver++"]:
for solver_type in ["midpoint", "heun"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=lowerCAmelCase , solver_type=lowerCAmelCase , prediction_type=lowerCAmelCase , algorithm_type=lowerCAmelCase , )
__lowerCAmelCase : Optional[Any] = self.full_loop(
solver_order=lowerCAmelCase , solver_type=lowerCAmelCase , prediction_type=lowerCAmelCase , algorithm_type=lowerCAmelCase , )
assert not torch.isnan(lowerCAmelCase ).any(), "Samples have nan numbers"
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict:
"""simple docstring"""
self.check_over_configs(lower_order_final=lowerCAmelCase )
self.check_over_configs(lower_order_final=lowerCAmelCase )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any:
"""simple docstring"""
self.check_over_configs(lambda_min_clipped=-float("""inf""" ) )
self.check_over_configs(lambda_min_clipped=-5.1 )
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple:
"""simple docstring"""
self.check_over_configs(variance_type=lowerCAmelCase )
self.check_over_configs(variance_type="""learned_range""" )
def SCREAMING_SNAKE_CASE ( self : int ) -> str:
"""simple docstring"""
for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]:
self.check_over_forward(num_inference_steps=lowerCAmelCase , time_step=0 )
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
__lowerCAmelCase : List[Any] = self.full_loop()
__lowerCAmelCase : Any = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.2791 ) < 1e-3
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str:
"""simple docstring"""
__lowerCAmelCase : List[Any] = self.full_loop(use_karras_sigmas=lowerCAmelCase )
__lowerCAmelCase : Tuple = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.2248 ) < 1e-3
def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]:
"""simple docstring"""
__lowerCAmelCase : Union[str, Any] = self.full_loop(prediction_type="""v_prediction""" )
__lowerCAmelCase : Optional[int] = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.1453 ) < 1e-3
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
"""simple docstring"""
__lowerCAmelCase : List[str] = self.full_loop(prediction_type="""v_prediction""" , use_karras_sigmas=lowerCAmelCase )
__lowerCAmelCase : List[str] = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_mean.item() - 0.0649 ) < 1e-3
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]:
"""simple docstring"""
__lowerCAmelCase : List[str] = self.scheduler_classes[0]
__lowerCAmelCase : Union[str, Any] = self.get_scheduler_config(thresholding=lowerCAmelCase , dynamic_thresholding_ratio=0 )
__lowerCAmelCase : str = scheduler_class(**lowerCAmelCase )
__lowerCAmelCase : List[str] = 10
__lowerCAmelCase : str = self.dummy_model()
__lowerCAmelCase : List[Any] = self.dummy_sample_deter.half()
scheduler.set_timesteps(lowerCAmelCase )
for i, t in enumerate(scheduler.timesteps ):
__lowerCAmelCase : Union[str, Any] = model(lowerCAmelCase , lowerCAmelCase )
__lowerCAmelCase : List[Any] = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).prev_sample
assert sample.dtype == torch.floataa
| 218
| 0
|
"""simple docstring"""
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import doctest
import sys
import warnings
from os.path import abspath, dirname, join
import _pytest
from transformers.testing_utils import HfDoctestModule, HfDocTestParser
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
UpperCamelCase__ :Dict = abspath(join(dirname(__file__), """src"""))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="""ignore""", category=FutureWarning)
def A_ ( snake_case__ ) -> Optional[int]:
config.addinivalue_line(
'''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' )
config.addinivalue_line(
'''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' )
config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' )
config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' )
config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' )
config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' )
def A_ ( snake_case__ ) -> List[Any]:
from transformers.testing_utils import pytest_addoption_shared
pytest_addoption_shared(__UpperCamelCase )
def A_ ( snake_case__ ) -> Union[str, Any]:
from transformers.testing_utils import pytest_terminal_summary_main
_UpperCamelCase :Tuple = terminalreporter.config.getoption('''--make-reports''' )
if make_reports:
pytest_terminal_summary_main(__UpperCamelCase , id=__UpperCamelCase )
def A_ ( snake_case__ , snake_case__ ) -> Tuple:
# If no tests are collected, pytest exists with code 5, which makes the CI fail.
if exitstatus == 5:
_UpperCamelCase :Optional[Any] = 0
# Doctest custom flag to ignore output.
UpperCamelCase__ :Dict = doctest.register_optionflag("""IGNORE_RESULT""")
UpperCamelCase__ :Optional[int] = doctest.OutputChecker
class A( lowerCamelCase__ ):
"""simple docstring"""
def _UpperCamelCase( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]:
"""simple docstring"""
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self , a__ , a__ , a__ )
UpperCamelCase__ :List[str] = CustomOutputChecker
UpperCamelCase__ :Optional[int] = HfDoctestModule
UpperCamelCase__ :Any = HfDocTestParser
| 355
|
import argparse
import tensorflow as tf
import torch
from transformers import BertConfig, BertForMaskedLM
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertPooler,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
logging.set_verbosity_info()
def lowerCamelCase_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
def get_masked_lm_array(__UpperCamelCase ):
A_ = F"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
def get_encoder_array(__UpperCamelCase ):
A_ = F"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
def get_encoder_layer_array(__UpperCamelCase , __UpperCamelCase ):
A_ = F"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
def get_encoder_attention_layer_array(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
A_ = F"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE"
A_ = tf.train.load_variable(__UpperCamelCase , __UpperCamelCase )
A_ = array.reshape(__UpperCamelCase )
if "kernel" in name:
A_ = array.transpose()
return torch.from_numpy(__UpperCamelCase )
print(F"Loading model based on config from {config_path}..." )
A_ = BertConfig.from_json_file(__UpperCamelCase )
A_ = BertForMaskedLM(__UpperCamelCase )
# Layers
for layer_index in range(0 , config.num_hidden_layers ):
A_ = model.bert.encoder.layer[layer_index]
# Self-attention
A_ = layer.attention.self
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_query_dense/kernel''' , self_attn.query.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_query_dense/bias''' , self_attn.query.bias.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_key_dense/kernel''' , self_attn.key.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_key_dense/bias''' , self_attn.key.bias.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_value_dense/kernel''' , self_attn.value.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_value_dense/bias''' , self_attn.value.bias.data.shape )
# Self-attention Output
A_ = layer.attention.output
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_output_dense/kernel''' , self_output.dense.weight.data.shape )
A_ = get_encoder_attention_layer_array(
__UpperCamelCase , '''_output_dense/bias''' , self_output.dense.bias.data.shape )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_attention_layer_norm/gamma''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_attention_layer_norm/beta''' )
# Intermediate
A_ = layer.intermediate
A_ = get_encoder_layer_array(__UpperCamelCase , '''_intermediate_dense/kernel''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_intermediate_dense/bias''' )
# Output
A_ = layer.output
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_dense/kernel''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_dense/bias''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_layer_norm/gamma''' )
A_ = get_encoder_layer_array(__UpperCamelCase , '''_output_layer_norm/beta''' )
# Embeddings
A_ = get_encoder_array('''_position_embedding_layer/embeddings''' )
A_ = get_encoder_array('''_type_embedding_layer/embeddings''' )
A_ = get_encoder_array('''_embedding_norm_layer/gamma''' )
A_ = get_encoder_array('''_embedding_norm_layer/beta''' )
# LM Head
A_ = model.cls.predictions.transform
A_ = get_masked_lm_array('''dense/kernel''' )
A_ = get_masked_lm_array('''dense/bias''' )
A_ = get_masked_lm_array('''layer_norm/gamma''' )
A_ = get_masked_lm_array('''layer_norm/beta''' )
A_ = get_masked_lm_array('''embedding_table''' )
# Pooling
A_ = BertPooler(config=__UpperCamelCase )
A_ = get_encoder_array('''_pooler_layer/kernel''' )
A_ = get_encoder_array('''_pooler_layer/bias''' )
# Export final model
model.save_pretrained(__UpperCamelCase )
# Integration test - should load without any errors ;)
A_ = BertForMaskedLM.from_pretrained(__UpperCamelCase )
print(new_model.eval() )
print('''Model conversion was done sucessfully!''' )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser()
parser.add_argument(
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path."
)
parser.add_argument(
"--bert_config_file",
type=str,
required=True,
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path",
type=str,
required=True,
help="Path to the output PyTorch model.",
)
SCREAMING_SNAKE_CASE : str = parser.parse_args()
convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
| 141
| 0
|
from __future__ import annotations
def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ):
__SCREAMING_SNAKE_CASE = 0
__SCREAMING_SNAKE_CASE = len(UpperCamelCase_ ) - 1
while i < j:
if nums[i] + nums[j] == target:
return [i, j]
elif nums[i] + nums[j] < target:
__SCREAMING_SNAKE_CASE = i + 1
else:
__SCREAMING_SNAKE_CASE = j - 1
return []
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F"""{two_pointer([2, 7, 11, 15], 9) = }""")
| 713
|
"""simple docstring"""
from __future__ import annotations
from collections import namedtuple
from dataclasses import dataclass
@dataclass
class SCREAMING_SNAKE_CASE_ :
"""simple docstring"""
__lowercase : int
__lowercase : TreeNode | None = None
__lowercase : TreeNode | None = None
__magic_name__ = namedtuple("CoinsDistribResult", "moves excess")
def _lowerCAmelCase ( UpperCamelCase_ ):
if root is None:
return 0
# Validation
def count_nodes(UpperCamelCase_ ) -> int:
if node is None:
return 0
return count_nodes(node.left ) + count_nodes(node.right ) + 1
def count_coins(UpperCamelCase_ ) -> int:
if node is None:
return 0
return count_coins(node.left ) + count_coins(node.right ) + node.data
if count_nodes(UpperCamelCase_ ) != count_coins(UpperCamelCase_ ):
raise ValueError("""The nodes number should be same as the number of coins""" )
# Main calculation
def get_distrib(UpperCamelCase_ ) -> CoinsDistribResult:
if node is None:
return CoinsDistribResult(0 , 1 )
__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = get_distrib(node.left )
__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = get_distrib(node.right )
__SCREAMING_SNAKE_CASE = 1 - left_distrib_excess
__SCREAMING_SNAKE_CASE = 1 - right_distrib_excess
__SCREAMING_SNAKE_CASE = (
left_distrib_moves
+ right_distrib_moves
+ abs(UpperCamelCase_ )
+ abs(UpperCamelCase_ )
)
__SCREAMING_SNAKE_CASE = node.data - coins_to_left - coins_to_right
return CoinsDistribResult(UpperCamelCase_ , UpperCamelCase_ )
return get_distrib(UpperCamelCase_ )[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 248
| 0
|
"""simple docstring"""
from ....configuration_utils import PretrainedConfig
from ....utils import logging
__magic_name__ = logging.get_logger(__name__)
__magic_name__ = {
"Visual-Attention-Network/van-base": (
"https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json"
),
}
class _lowerCAmelCase ( lowerCAmelCase_ ):
lowercase_ : int = '''van'''
def __init__( self , a_=224 , a_=3 , a_=[7, 3, 3, 3] , a_=[4, 2, 2, 2] , a_=[64, 128, 320, 512] , a_=[3, 3, 12, 3] , a_=[8, 8, 4, 4] , a_="gelu" , a_=0.02 , a_=1e-6 , a_=1e-2 , a_=0.0 , a_=0.0 , **a_ , ) -> str:
super().__init__(**__snake_case )
_UpperCAmelCase = image_size
_UpperCAmelCase = num_channels
_UpperCAmelCase = patch_sizes
_UpperCAmelCase = strides
_UpperCAmelCase = hidden_sizes
_UpperCAmelCase = depths
_UpperCAmelCase = mlp_ratios
_UpperCAmelCase = hidden_act
_UpperCAmelCase = initializer_range
_UpperCAmelCase = layer_norm_eps
_UpperCAmelCase = layer_scale_init_value
_UpperCAmelCase = drop_path_rate
_UpperCAmelCase = dropout_rate
| 657
|
from __future__ import annotations
class __magic_name__ :
def __init__( self , __snake_case ) -> None:
'''simple docstring'''
__a =order
# a_{0} ... a_{k}
__a =[1.0] + [0.0] * order
# b_{0} ... b_{k}
__a =[1.0] + [0.0] * order
# x[n-1] ... x[n-k]
__a =[0.0] * self.order
# y[n-1] ... y[n-k]
__a =[0.0] * self.order
def __magic_name__ ( self , __snake_case , __snake_case ) -> None:
'''simple docstring'''
if len(__snake_case ) < self.order:
__a =[1.0, *a_coeffs]
if len(__snake_case ) != self.order + 1:
__a =(
f'Expected a_coeffs to have {self.order + 1} elements '
f'for {self.order}-order filter, got {len(__snake_case )}'
)
raise ValueError(__snake_case )
if len(__snake_case ) != self.order + 1:
__a =(
f'Expected b_coeffs to have {self.order + 1} elements '
f'for {self.order}-order filter, got {len(__snake_case )}'
)
raise ValueError(__snake_case )
__a =a_coeffs
__a =b_coeffs
def __magic_name__ ( self , __snake_case ) -> float:
'''simple docstring'''
__a =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]
)
__a =(result + self.b_coeffs[0] * sample) / self.a_coeffs[0]
__a =self.input_history[:-1]
__a =self.output_history[:-1]
__a =sample
__a =result
return result
| 242
| 0
|
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConformerConfig,
WavaVecaConformerForCTC,
WavaVecaConformerForPreTraining,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
__UpperCAmelCase : List[str] = logging.get_logger(__name__)
__UpperCAmelCase : Any = {
"post_extract_proj": "feature_projection.projection",
"encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
"self_attn.linear_k": "encoder.layers.*.self_attn.linear_k",
"self_attn.linear_v": "encoder.layers.*.self_attn.linear_v",
"self_attn.linear_q": "encoder.layers.*.self_attn.linear_q",
"self_attn.pos_bias_u": "encoder.layers.*.self_attn.pos_bias_u",
"self_attn.pos_bias_v": "encoder.layers.*.self_attn.pos_bias_v",
"self_attn.linear_out": "encoder.layers.*.self_attn.linear_out",
"self_attn.linear_pos": "encoder.layers.*.self_attn.linear_pos",
"self_attn.rotary_emb": "encoder.embed_positions",
"self_attn_layer_norm": "encoder.layers.*.self_attn_layer_norm",
"conv_module.pointwise_conv1": "encoder.layers.*.conv_module.pointwise_conv1",
"conv_module.pointwise_conv2": "encoder.layers.*.conv_module.pointwise_conv2",
"conv_module.depthwise_conv": "encoder.layers.*.conv_module.depthwise_conv",
"conv_module.batch_norm": "encoder.layers.*.conv_module.batch_norm",
"conv_module.layer_norm": "encoder.layers.*.conv_module.layer_norm",
"ffn1.w_1": "encoder.layers.*.ffn1.intermediate_dense",
"ffn1.w_2": "encoder.layers.*.ffn1.output_dense",
"ffn1.layer_norm": "encoder.layers.*.ffn1_layer_norm",
"ffn2.w_1": "encoder.layers.*.ffn2.intermediate_dense",
"ffn2.w_2": "encoder.layers.*.ffn2.output_dense",
"ffn2.layer_norm": "encoder.layers.*.ffn2_layer_norm",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"w2v_model.layer_norm": "feature_projection.layer_norm",
"quantizer.weight_proj": "quantizer.weight_proj",
"quantizer.vars": "quantizer.codevectors",
"project_q": "project_q",
"final_proj": "project_hid",
"w2v_encoder.proj": "lm_head",
"mask_emb": "masked_spec_embed",
}
__UpperCAmelCase : str = [
"lm_head",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
]
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> List[Any]:
for attribute in key.split("""."""):
__snake_case: Any = getattr(lowercase__ , lowercase__)
if weight_type is not None:
__snake_case: Optional[int] = getattr(lowercase__ , lowercase__).shape
else:
__snake_case: List[str] = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}''')
if weight_type == "weight":
__snake_case: List[str] = value
elif weight_type == "weight_g":
__snake_case: List[str] = value
elif weight_type == "weight_v":
__snake_case: List[Any] = value
elif weight_type == "bias":
__snake_case: Union[str, Any] = value
elif weight_type == "running_mean":
__snake_case: Dict = value
elif weight_type == "running_var":
__snake_case: int = value
elif weight_type == "num_batches_tracked":
__snake_case: List[str] = value
elif weight_type == "inv_freq":
__snake_case: List[str] = value
else:
__snake_case: Optional[Any] = value
logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''')
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> Optional[int]:
__snake_case: str = []
__snake_case: Union[str, Any] = fairseq_model.state_dict()
__snake_case: Any = hf_model.wavaveca_conformer.feature_extractor
for name, value in fairseq_dict.items():
__snake_case: int = False
if "conv_layers" in name:
load_conv_layer(
lowercase__ , lowercase__ , lowercase__ , lowercase__ , hf_model.config.feat_extract_norm == """group""" , )
__snake_case: Optional[int] = True
else:
for key, mapped_key in MAPPING.items():
__snake_case: Union[str, Any] = """wav2vec2_conformer.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split("""w2v_model.""")[-1] == name.split(""".""")[0]:
__snake_case: List[Any] = True
if "*" in mapped_key:
__snake_case: List[Any] = name.split(lowercase__)[0].split(""".""")[-2]
__snake_case: Union[str, Any] = mapped_key.replace("""*""" , lowercase__)
if "pos_bias_u" in name:
__snake_case: Optional[int] = None
elif "pos_bias_v" in name:
__snake_case: Any = None
elif "weight_g" in name:
__snake_case: str = """weight_g"""
elif "weight_v" in name:
__snake_case: List[Any] = """weight_v"""
elif "bias" in name:
__snake_case: Optional[int] = """bias"""
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
__snake_case: Tuple = """weight"""
elif "running_mean" in name:
__snake_case: Any = """running_mean"""
elif "inv_freq" in name:
__snake_case: Any = """inv_freq"""
elif "running_var" in name:
__snake_case: int = """running_var"""
elif "num_batches_tracked" in name:
__snake_case: Any = """num_batches_tracked"""
else:
__snake_case: Union[str, Any] = None
set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__)
continue
if not is_used:
unused_weights.append(lowercase__)
logger.warning(F'''Unused weights: {unused_weights}''')
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> Tuple:
__snake_case: Optional[Any] = full_name.split("""conv_layers.""")[-1]
__snake_case: Optional[Any] = name.split(""".""")
__snake_case: str = int(items[0])
__snake_case: List[Any] = int(items[1])
if type_id == 0:
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''')
__snake_case: Union[str, Any] = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''')
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''')
__snake_case: Union[str, Any] = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''')
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''')
__snake_case: Any = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''')
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''')
__snake_case: Optional[Any] = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''')
else:
unused_weights.append(lowercase__)
@torch.no_grad()
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=True) -> List[Any]:
if config_path is not None:
__snake_case: str = WavaVecaConformerConfig.from_pretrained(lowercase__ , hidden_act="""swish""")
else:
__snake_case: Union[str, Any] = WavaVecaConformerConfig()
if "rope" in checkpoint_path:
__snake_case: Union[str, Any] = """rotary"""
if is_finetuned:
if dict_path:
__snake_case: List[str] = Dictionary.load(lowercase__)
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__snake_case: Dict = target_dict.pad_index
__snake_case: str = target_dict.bos_index
__snake_case: int = target_dict.eos_index
__snake_case: Dict = len(target_dict.symbols)
__snake_case: List[str] = os.path.join(lowercase__ , """vocab.json""")
if not os.path.isdir(lowercase__):
logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowercase__))
return
os.makedirs(lowercase__ , exist_ok=lowercase__)
__snake_case: str = target_dict.indices
# fairseq has the <pad> and <s> switched
__snake_case: Union[str, Any] = 0
__snake_case: Any = 1
with open(lowercase__ , """w""" , encoding="""utf-8""") as vocab_handle:
json.dump(lowercase__ , lowercase__)
__snake_case: Any = WavaVecaCTCTokenizer(
lowercase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=lowercase__ , )
__snake_case: Dict = True if config.feat_extract_norm == """layer""" else False
__snake_case: Any = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowercase__ , return_attention_mask=lowercase__ , )
__snake_case: Any = WavaVecaProcessor(feature_extractor=lowercase__ , tokenizer=lowercase__)
processor.save_pretrained(lowercase__)
__snake_case: Union[str, Any] = WavaVecaConformerForCTC(lowercase__)
else:
__snake_case: Tuple = WavaVecaConformerForPreTraining(lowercase__)
if is_finetuned:
__snake_case , __snake_case , __snake_case: Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""")[:-1])})
else:
__snake_case: Optional[Any] = argparse.Namespace(task="""audio_pretraining""")
__snake_case: str = fairseq.tasks.setup_task(lowercase__)
__snake_case , __snake_case , __snake_case: List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase__)
__snake_case: Optional[int] = model[0].eval()
recursively_load_weights(lowercase__ , lowercase__ , not is_finetuned)
hf_wavavec.save_pretrained(lowercase__)
if __name__ == "__main__":
__UpperCAmelCase : Dict = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
)
__UpperCAmelCase : List[str] = parser.parse_args()
convert_wavaveca_conformer_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 702
|
def A__ ( SCREAMING_SNAKE_CASE__ = 1000) -> int:
__snake_case , __snake_case: Dict = 1, 1
__snake_case: int = 2
while True:
__snake_case: str = 0
__snake_case: Any = fa + fa
__snake_case , __snake_case: Tuple = fa, f
index += 1
for _ in str(SCREAMING_SNAKE_CASE__):
i += 1
if i == n:
break
return index
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 155
| 0
|
import torch
from diffusers import DDIMParallelScheduler
from .test_schedulers import SchedulerCommonTest
class __UpperCamelCase ( lowercase ):
SCREAMING_SNAKE_CASE__ = (DDIMParallelScheduler,)
SCREAMING_SNAKE_CASE__ = (('eta', 0.0), ('num_inference_steps', 50))
def __A ( self : Optional[Any] , **lowerCAmelCase : List[Any] ):
'''simple docstring'''
UpperCAmelCase_ = {
"num_train_timesteps": 1_000,
"beta_start": 0.0_001,
"beta_end": 0.02,
"beta_schedule": "linear",
"clip_sample": True,
}
config.update(**lowerCAmelCase )
return config
def __A ( self : Any , **lowerCAmelCase : Dict ):
'''simple docstring'''
UpperCAmelCase_ = self.scheduler_classes[0]
UpperCAmelCase_ = self.get_scheduler_config(**lowerCAmelCase )
UpperCAmelCase_ = scheduler_class(**lowerCAmelCase )
UpperCAmelCase_ , UpperCAmelCase_ = 10, 0.0
UpperCAmelCase_ = self.dummy_model()
UpperCAmelCase_ = self.dummy_sample_deter
scheduler.set_timesteps(lowerCAmelCase )
for t in scheduler.timesteps:
UpperCAmelCase_ = model(lowerCAmelCase , lowerCAmelCase )
UpperCAmelCase_ = scheduler.step(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).prev_sample
return sample
def __A ( self : Union[str, Any] ):
'''simple docstring'''
for timesteps in [100, 500, 1_000]:
self.check_over_configs(num_train_timesteps=lowerCAmelCase )
def __A ( self : int ):
'''simple docstring'''
for steps_offset in [0, 1]:
self.check_over_configs(steps_offset=lowerCAmelCase )
UpperCAmelCase_ = self.scheduler_classes[0]
UpperCAmelCase_ = self.get_scheduler_config(steps_offset=1 )
UpperCAmelCase_ = scheduler_class(**lowerCAmelCase )
scheduler.set_timesteps(5 )
assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) )
def __A ( self : Optional[int] ):
'''simple docstring'''
for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ):
self.check_over_configs(beta_start=lowerCAmelCase , beta_end=lowerCAmelCase )
def __A ( self : Optional[Any] ):
'''simple docstring'''
for schedule in ["linear", "squaredcos_cap_v2"]:
self.check_over_configs(beta_schedule=lowerCAmelCase )
def __A ( self : List[Any] ):
'''simple docstring'''
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=lowerCAmelCase )
def __A ( self : List[str] ):
'''simple docstring'''
for clip_sample in [True, False]:
self.check_over_configs(clip_sample=lowerCAmelCase )
def __A ( self : Tuple ):
'''simple docstring'''
for timestep_spacing in ["trailing", "leading"]:
self.check_over_configs(timestep_spacing=lowerCAmelCase )
def __A ( self : int ):
'''simple docstring'''
for rescale_betas_zero_snr in [True, False]:
self.check_over_configs(rescale_betas_zero_snr=lowerCAmelCase )
def __A ( self : Union[str, Any] ):
'''simple docstring'''
self.check_over_configs(thresholding=lowerCAmelCase )
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(
thresholding=lowerCAmelCase , prediction_type=lowerCAmelCase , sample_max_value=lowerCAmelCase , )
def __A ( self : List[str] ):
'''simple docstring'''
for t in [1, 10, 49]:
self.check_over_forward(time_step=lowerCAmelCase )
def __A ( self : Tuple ):
'''simple docstring'''
for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ):
self.check_over_forward(time_step=lowerCAmelCase , num_inference_steps=lowerCAmelCase )
def __A ( self : Dict ):
'''simple docstring'''
for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ):
self.check_over_forward(time_step=lowerCAmelCase , eta=lowerCAmelCase )
def __A ( self : str ):
'''simple docstring'''
UpperCAmelCase_ = self.scheduler_classes[0]
UpperCAmelCase_ = self.get_scheduler_config()
UpperCAmelCase_ = scheduler_class(**lowerCAmelCase )
assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1e-5
assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1e-5
def __A ( self : Dict ):
'''simple docstring'''
UpperCAmelCase_ = self.scheduler_classes[0]
UpperCAmelCase_ = self.get_scheduler_config()
UpperCAmelCase_ = scheduler_class(**lowerCAmelCase )
UpperCAmelCase_ , UpperCAmelCase_ = 10, 0.0
scheduler.set_timesteps(lowerCAmelCase )
UpperCAmelCase_ = self.dummy_model()
UpperCAmelCase_ = self.dummy_sample_deter
UpperCAmelCase_ = self.dummy_sample_deter + 0.1
UpperCAmelCase_ = self.dummy_sample_deter - 0.1
UpperCAmelCase_ = samplea.shape[0]
UpperCAmelCase_ = torch.stack([samplea, samplea, samplea] , dim=0 )
UpperCAmelCase_ = torch.arange(lowerCAmelCase )[0:3, None].repeat(1 , lowerCAmelCase )
UpperCAmelCase_ = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) )
UpperCAmelCase_ = scheduler.batch_step_no_noise(lowerCAmelCase , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , lowerCAmelCase )
UpperCAmelCase_ = torch.sum(torch.abs(lowerCAmelCase ) )
UpperCAmelCase_ = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2
assert abs(result_mean.item() - 0.4_982 ) < 1e-3
def __A ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.full_loop()
UpperCAmelCase_ = torch.sum(torch.abs(lowerCAmelCase ) )
UpperCAmelCase_ = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_sum.item() - 172.0_067 ) < 1e-2
assert abs(result_mean.item() - 0.223_967 ) < 1e-3
def __A ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ = self.full_loop(prediction_type="v_prediction" )
UpperCAmelCase_ = torch.sum(torch.abs(lowerCAmelCase ) )
UpperCAmelCase_ = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_sum.item() - 52.5_302 ) < 1e-2
assert abs(result_mean.item() - 0.0_684 ) < 1e-3
def __A ( self : Dict ):
'''simple docstring'''
UpperCAmelCase_ = self.full_loop(set_alpha_to_one=lowerCAmelCase , beta_start=0.01 )
UpperCAmelCase_ = torch.sum(torch.abs(lowerCAmelCase ) )
UpperCAmelCase_ = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_sum.item() - 149.8_295 ) < 1e-2
assert abs(result_mean.item() - 0.1_951 ) < 1e-3
def __A ( self : int ):
'''simple docstring'''
UpperCAmelCase_ = self.full_loop(set_alpha_to_one=lowerCAmelCase , beta_start=0.01 )
UpperCAmelCase_ = torch.sum(torch.abs(lowerCAmelCase ) )
UpperCAmelCase_ = torch.mean(torch.abs(lowerCAmelCase ) )
assert abs(result_sum.item() - 149.0_784 ) < 1e-2
assert abs(result_mean.item() - 0.1_941 ) < 1e-3
| 162
|
import argparse
import re
from flax.traverse_util import flatten_dict, unflatten_dict
from tax import checkpoints
from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration
from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model
from transformers.utils import logging
logging.set_verbosity_info()
# should not include what is already done by the `from_pt` argument
_a: List[Any] = {
"""/attention/""": """/0/SelfAttention/""",
"""/self_attention/""": """/0/SelfAttention/""",
"""/encoder_decoder_attention/""": """/1/EncDecAttention/""",
"""value""": """v""",
"""query""": """q""",
"""key""": """k""",
"""out""": """o""",
"""pre_self_attention_layer_norm""": """0/layer_norm""",
"""pre_cross_attention_layer_norm""": """1/layer_norm""",
"""pre_attention_layer_norm""": """0/layer_norm""", # previously 1, but seems wrong
"""token_embedder""": """shared""",
"""encoder_norm""": """final_layer_norm""",
"""decoder_norm""": """final_layer_norm""",
"""relpos_bias/rel_embedding""": """block/0/layer/0/SelfAttention/relative_attention_bias/weight""",
"""router/router_weights/w/""": """router/classifier/""",
"""roer/roer_weights/w/""": """router/classifier/""",
"""logits_dense""": """lm_head""",
}
def __lowerCAmelCase ( A ):
# 1. in HF T5, we have block.{x}.layer.{y}. which corresponds to layer.{x} in
# the original model
UpperCAmelCase_ = list(s_dict.keys() )
for key in keys:
UpperCAmelCase_ = r".*/layers_(\d+)"
UpperCAmelCase_ = key
if re.match(A , A ):
UpperCAmelCase_ = re.sub(r"layers_(\d+)" , r"block/\1/layer" , A )
UpperCAmelCase_ = r"(encoder|decoder)\/"
if re.match(A , A ):
UpperCAmelCase_ = re.match(A , A ).groups()
if groups[0] == "encoder":
UpperCAmelCase_ = re.sub(r"/mlp/" , r"/1/mlp/" , A )
UpperCAmelCase_ = re.sub(r"/pre_mlp_layer_norm/" , r"/1/layer_norm/" , A )
elif groups[0] == "decoder":
UpperCAmelCase_ = re.sub(r"/mlp/" , r"/2/mlp/" , A )
UpperCAmelCase_ = re.sub(r"/pre_mlp_layer_norm/" , r"/2/layer_norm/" , A )
# 2. Convert other classic mappings
for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items():
if old_key in new_key:
UpperCAmelCase_ = new_key.replace(A , A )
print(F"{key} -> {new_key}" )
UpperCAmelCase_ = s_dict.pop(A )
if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
UpperCAmelCase_ = s_dict[
"encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"
].T
if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
UpperCAmelCase_ = s_dict[
"decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"
].T
# 3. Take extra care of the EXPERTS layer
for key in list(s_dict.keys() ):
if "expert" in key:
UpperCAmelCase_ = s_dict[key].shape[0]
UpperCAmelCase_ = s_dict[key]
for idx in range(A ):
UpperCAmelCase_ = expert_weihts[idx]
print(F"{key} -> {key.replace('expert/' , 'nested fstring' )}" )
s_dict.pop(A )
return s_dict
_a: Any = {
"""NUM_ENCODER_LAYERS""": """num_layers""",
"""NUM_DECODER_LAYERS""": """num_decoder_layers""",
"""NUM_HEADS""": """num_heads""",
"""HEAD_DIM""": """d_kv""",
"""EMBED_DIM""": """d_model""",
"""MLP_DIM""": """d_ff""",
"""NUM_SELECTED_EXPERTS""": """num_selected_experts""",
"""NUM_ENCODER_SPARSE_LAYERS""": """num_sparse_encoder_layers""",
"""NUM_DECODER_SPARSE_LAYERS""": """num_sparse_decoder_layers""",
"""dense.MlpBlock.activations""": """feed_forward_proj""",
}
def __lowerCAmelCase ( A , A ):
# Convert a google style config to the hugging face fromat
import regex as re
with open(A , "r" ) as f:
UpperCAmelCase_ = f.read()
UpperCAmelCase_ = re.findall(r"(.*) = ([0-9.]*)" , A )
UpperCAmelCase_ = {}
for param, value in regex_match:
if param in GIN_TO_CONFIG_MAPPING and value != "":
UpperCAmelCase_ = float(A ) if "." in value else int(A )
UpperCAmelCase_ = re.findall(r"(.*activations) = \(\'(.*)\',\)" , A )[0]
UpperCAmelCase_ = str(activation[1] )
UpperCAmelCase_ = num_experts
UpperCAmelCase_ = SwitchTransformersConfig(**A )
return config
def __lowerCAmelCase ( A , A , A=None , A="./" , A=8 ):
# Initialise PyTorch model
print(F"Loading flax weights from : {flax_checkpoint_path}" )
UpperCAmelCase_ = checkpoints.load_tax_checkpoint(A )
if gin_file is not None:
UpperCAmelCase_ = convert_gin_to_config(A , A )
else:
UpperCAmelCase_ = SwitchTransformersConfig.from_pretrained(A )
UpperCAmelCase_ = SwitchTransformersForConditionalGeneration(A )
UpperCAmelCase_ = flax_params["target"]
UpperCAmelCase_ = flatten_dict(A , sep="/" )
UpperCAmelCase_ = rename_keys(A )
UpperCAmelCase_ = unflatten_dict(A , sep="/" )
# Load the flax params in the PT model
load_flax_weights_in_pytorch_model(A , A )
print(F"Save PyTorch model to {pytorch_dump_path}" )
pt_model.save_pretrained(A )
if __name__ == "__main__":
_a: Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--switch_t5x_checkpoint_path""",
default=None,
type=str,
required=True,
help=(
"""The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the"""
""" model architecture. If not provided, a `gin_file` has to be provided."""
),
)
parser.add_argument(
"""--gin_file""",
default=None,
type=str,
required=False,
help="""Path to the gin config file. If not provided, a `config_file` has to be passed """,
)
parser.add_argument(
"""--config_name""", default=None, type=str, required=False, help="""Config name of SwitchTransformers model."""
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output pytorch model."""
)
parser.add_argument("""--num_experts""", default=8, type=int, required=False, help="""Number of experts""")
_a: List[Any] = parser.parse_args()
convert_flax_checkpoint_to_pytorch(
args.switch_tax_checkpoint_path,
args.config_name,
args.gin_file,
args.pytorch_dump_folder_path,
args.num_experts,
)
| 162
| 1
|
import argparse
import json
import torch
from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel
def a__ ( snake_case , snake_case=1 ):
"""simple docstring"""
if n_shave_prefix_segments >= 0:
return ".".join(path.split('''.''' )[n_shave_prefix_segments:] )
else:
return ".".join(path.split('''.''' )[:n_shave_prefix_segments] )
def a__ ( snake_case , snake_case=0 ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : List[str] = []
for old_item in old_list:
__SCREAMING_SNAKE_CASE : int = old_item.replace('''in_layers.0''' , '''norm1''' )
__SCREAMING_SNAKE_CASE : Optional[int] = new_item.replace('''in_layers.2''' , '''conv1''' )
__SCREAMING_SNAKE_CASE : int = new_item.replace('''out_layers.0''' , '''norm2''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = new_item.replace('''out_layers.3''' , '''conv2''' )
__SCREAMING_SNAKE_CASE : Optional[int] = new_item.replace('''emb_layers.1''' , '''time_emb_proj''' )
__SCREAMING_SNAKE_CASE : List[str] = new_item.replace('''skip_connection''' , '''conv_shortcut''' )
__SCREAMING_SNAKE_CASE : List[Any] = shave_segments(snake_case , n_shave_prefix_segments=snake_case )
mapping.append({'''old''': old_item, '''new''': new_item} )
return mapping
def a__ ( snake_case , snake_case=0 ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Any = []
for old_item in old_list:
__SCREAMING_SNAKE_CASE : Tuple = old_item
__SCREAMING_SNAKE_CASE : Optional[int] = new_item.replace('''norm.weight''' , '''group_norm.weight''' )
__SCREAMING_SNAKE_CASE : int = new_item.replace('''norm.bias''' , '''group_norm.bias''' )
__SCREAMING_SNAKE_CASE : Any = new_item.replace('''proj_out.weight''' , '''proj_attn.weight''' )
__SCREAMING_SNAKE_CASE : List[Any] = new_item.replace('''proj_out.bias''' , '''proj_attn.bias''' )
__SCREAMING_SNAKE_CASE : Any = shave_segments(snake_case , n_shave_prefix_segments=snake_case )
mapping.append({'''old''': old_item, '''new''': new_item} )
return mapping
def a__ ( snake_case , snake_case , snake_case , snake_case=None , snake_case=None , snake_case=None ):
"""simple docstring"""
assert isinstance(snake_case , snake_case ), "Paths should be a list of dicts containing 'old' and 'new' keys."
# Splits the attention layers into three variables.
if attention_paths_to_split is not None:
for path, path_map in attention_paths_to_split.items():
__SCREAMING_SNAKE_CASE : Dict = old_checkpoint[path]
__SCREAMING_SNAKE_CASE : List[Any] = old_tensor.shape[0] // 3
__SCREAMING_SNAKE_CASE : Dict = (-1, channels) if len(old_tensor.shape ) == 3 else (-1)
__SCREAMING_SNAKE_CASE : Tuple = old_tensor.shape[0] // config['''num_head_channels'''] // 3
__SCREAMING_SNAKE_CASE : Any = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] )
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = old_tensor.split(channels // num_heads , dim=1 )
__SCREAMING_SNAKE_CASE : Optional[Any] = query.reshape(snake_case )
__SCREAMING_SNAKE_CASE : Union[str, Any] = key.reshape(snake_case )
__SCREAMING_SNAKE_CASE : Any = value.reshape(snake_case )
for path in paths:
__SCREAMING_SNAKE_CASE : Any = path['''new''']
# These have already been assigned
if attention_paths_to_split is not None and new_path in attention_paths_to_split:
continue
# Global renaming happens here
__SCREAMING_SNAKE_CASE : Optional[Any] = new_path.replace('''middle_block.0''' , '''mid_block.resnets.0''' )
__SCREAMING_SNAKE_CASE : Any = new_path.replace('''middle_block.1''' , '''mid_block.attentions.0''' )
__SCREAMING_SNAKE_CASE : Dict = new_path.replace('''middle_block.2''' , '''mid_block.resnets.1''' )
if additional_replacements is not None:
for replacement in additional_replacements:
__SCREAMING_SNAKE_CASE : List[str] = new_path.replace(replacement['''old'''] , replacement['''new'''] )
# proj_attn.weight has to be converted from conv 1D to linear
if "proj_attn.weight" in new_path:
__SCREAMING_SNAKE_CASE : Union[str, Any] = old_checkpoint[path['''old''']][:, :, 0]
else:
__SCREAMING_SNAKE_CASE : str = old_checkpoint[path['''old''']]
def a__ ( snake_case , snake_case ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : List[Any] = {}
__SCREAMING_SNAKE_CASE : Optional[int] = checkpoint['''time_embed.0.weight''']
__SCREAMING_SNAKE_CASE : str = checkpoint['''time_embed.0.bias''']
__SCREAMING_SNAKE_CASE : Tuple = checkpoint['''time_embed.2.weight''']
__SCREAMING_SNAKE_CASE : Tuple = checkpoint['''time_embed.2.bias''']
__SCREAMING_SNAKE_CASE : Optional[Any] = checkpoint['''input_blocks.0.0.weight''']
__SCREAMING_SNAKE_CASE : str = checkpoint['''input_blocks.0.0.bias''']
__SCREAMING_SNAKE_CASE : Union[str, Any] = checkpoint['''out.0.weight''']
__SCREAMING_SNAKE_CASE : Tuple = checkpoint['''out.0.bias''']
__SCREAMING_SNAKE_CASE : List[Any] = checkpoint['''out.2.weight''']
__SCREAMING_SNAKE_CASE : Union[str, Any] = checkpoint['''out.2.bias''']
# Retrieves the keys for the input blocks only
__SCREAMING_SNAKE_CASE : List[Any] = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''input_blocks''' in layer} )
__SCREAMING_SNAKE_CASE : int = {
layer_id: [key for key in checkpoint if F'''input_blocks.{layer_id}''' in key]
for layer_id in range(snake_case )
}
# Retrieves the keys for the middle blocks only
__SCREAMING_SNAKE_CASE : Any = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''middle_block''' in layer} )
__SCREAMING_SNAKE_CASE : int = {
layer_id: [key for key in checkpoint if F'''middle_block.{layer_id}''' in key]
for layer_id in range(snake_case )
}
# Retrieves the keys for the output blocks only
__SCREAMING_SNAKE_CASE : Union[str, Any] = len({'''.'''.join(layer.split('''.''' )[:2] ) for layer in checkpoint if '''output_blocks''' in layer} )
__SCREAMING_SNAKE_CASE : Union[str, Any] = {
layer_id: [key for key in checkpoint if F'''output_blocks.{layer_id}''' in key]
for layer_id in range(snake_case )
}
for i in range(1 , snake_case ):
__SCREAMING_SNAKE_CASE : Tuple = (i - 1) // (config['''num_res_blocks'''] + 1)
__SCREAMING_SNAKE_CASE : Optional[Any] = (i - 1) % (config['''num_res_blocks'''] + 1)
__SCREAMING_SNAKE_CASE : Union[str, Any] = [key for key in input_blocks[i] if F'''input_blocks.{i}.0''' in key]
__SCREAMING_SNAKE_CASE : List[str] = [key for key in input_blocks[i] if F'''input_blocks.{i}.1''' in key]
if F'''input_blocks.{i}.0.op.weight''' in checkpoint:
__SCREAMING_SNAKE_CASE : List[str] = checkpoint[
F'''input_blocks.{i}.0.op.weight'''
]
__SCREAMING_SNAKE_CASE : List[str] = checkpoint[
F'''input_blocks.{i}.0.op.bias'''
]
continue
__SCREAMING_SNAKE_CASE : Tuple = renew_resnet_paths(snake_case )
__SCREAMING_SNAKE_CASE : Tuple = {'''old''': F'''input_blocks.{i}.0''', '''new''': F'''down_blocks.{block_id}.resnets.{layer_in_block_id}'''}
__SCREAMING_SNAKE_CASE : Tuple = {'''old''': '''resnets.2.op''', '''new''': '''downsamplers.0.op'''}
assign_to_checkpoint(
snake_case , snake_case , snake_case , additional_replacements=[meta_path, resnet_op] , config=snake_case )
if len(snake_case ):
__SCREAMING_SNAKE_CASE : Dict = renew_attention_paths(snake_case )
__SCREAMING_SNAKE_CASE : List[Any] = {
'''old''': F'''input_blocks.{i}.1''',
'''new''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}''',
}
__SCREAMING_SNAKE_CASE : int = {
F'''input_blocks.{i}.1.qkv.bias''': {
'''key''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''',
'''query''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''',
'''value''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''',
},
F'''input_blocks.{i}.1.qkv.weight''': {
'''key''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''',
'''query''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''',
'''value''': F'''down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''',
},
}
assign_to_checkpoint(
snake_case , snake_case , snake_case , additional_replacements=[meta_path] , attention_paths_to_split=snake_case , config=snake_case , )
__SCREAMING_SNAKE_CASE : str = middle_blocks[0]
__SCREAMING_SNAKE_CASE : str = middle_blocks[1]
__SCREAMING_SNAKE_CASE : Optional[int] = middle_blocks[2]
__SCREAMING_SNAKE_CASE : Union[str, Any] = renew_resnet_paths(snake_case )
assign_to_checkpoint(snake_case , snake_case , snake_case , config=snake_case )
__SCREAMING_SNAKE_CASE : Optional[int] = renew_resnet_paths(snake_case )
assign_to_checkpoint(snake_case , snake_case , snake_case , config=snake_case )
__SCREAMING_SNAKE_CASE : Dict = renew_attention_paths(snake_case )
__SCREAMING_SNAKE_CASE : Any = {
'''middle_block.1.qkv.bias''': {
'''key''': '''mid_block.attentions.0.key.bias''',
'''query''': '''mid_block.attentions.0.query.bias''',
'''value''': '''mid_block.attentions.0.value.bias''',
},
'''middle_block.1.qkv.weight''': {
'''key''': '''mid_block.attentions.0.key.weight''',
'''query''': '''mid_block.attentions.0.query.weight''',
'''value''': '''mid_block.attentions.0.value.weight''',
},
}
assign_to_checkpoint(
snake_case , snake_case , snake_case , attention_paths_to_split=snake_case , config=snake_case )
for i in range(snake_case ):
__SCREAMING_SNAKE_CASE : List[Any] = i // (config['''num_res_blocks'''] + 1)
__SCREAMING_SNAKE_CASE : List[str] = i % (config['''num_res_blocks'''] + 1)
__SCREAMING_SNAKE_CASE : Dict = [shave_segments(snake_case , 2 ) for name in output_blocks[i]]
__SCREAMING_SNAKE_CASE : Any = {}
for layer in output_block_layers:
__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = layer.split('''.''' )[0], shave_segments(snake_case , 1 )
if layer_id in output_block_list:
output_block_list[layer_id].append(snake_case )
else:
__SCREAMING_SNAKE_CASE : str = [layer_name]
if len(snake_case ) > 1:
__SCREAMING_SNAKE_CASE : int = [key for key in output_blocks[i] if F'''output_blocks.{i}.0''' in key]
__SCREAMING_SNAKE_CASE : List[Any] = [key for key in output_blocks[i] if F'''output_blocks.{i}.1''' in key]
__SCREAMING_SNAKE_CASE : Optional[int] = renew_resnet_paths(snake_case )
__SCREAMING_SNAKE_CASE : List[str] = renew_resnet_paths(snake_case )
__SCREAMING_SNAKE_CASE : Any = {'''old''': F'''output_blocks.{i}.0''', '''new''': F'''up_blocks.{block_id}.resnets.{layer_in_block_id}'''}
assign_to_checkpoint(snake_case , snake_case , snake_case , additional_replacements=[meta_path] , config=snake_case )
if ["conv.weight", "conv.bias"] in output_block_list.values():
__SCREAMING_SNAKE_CASE : Any = list(output_block_list.values() ).index(['''conv.weight''', '''conv.bias'''] )
__SCREAMING_SNAKE_CASE : int = checkpoint[
F'''output_blocks.{i}.{index}.conv.weight'''
]
__SCREAMING_SNAKE_CASE : Dict = checkpoint[
F'''output_blocks.{i}.{index}.conv.bias'''
]
# Clear attentions as they have been attributed above.
if len(snake_case ) == 2:
__SCREAMING_SNAKE_CASE : List[str] = []
if len(snake_case ):
__SCREAMING_SNAKE_CASE : List[Any] = renew_attention_paths(snake_case )
__SCREAMING_SNAKE_CASE : str = {
'''old''': F'''output_blocks.{i}.1''',
'''new''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}''',
}
__SCREAMING_SNAKE_CASE : Optional[int] = {
F'''output_blocks.{i}.1.qkv.bias''': {
'''key''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias''',
'''query''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias''',
'''value''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias''',
},
F'''output_blocks.{i}.1.qkv.weight''': {
'''key''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight''',
'''query''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight''',
'''value''': F'''up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight''',
},
}
assign_to_checkpoint(
snake_case , snake_case , snake_case , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('''qkv''' in key for key in attentions ) else None , config=snake_case , )
else:
__SCREAMING_SNAKE_CASE : Optional[int] = renew_resnet_paths(snake_case , n_shave_prefix_segments=1 )
for path in resnet_0_paths:
__SCREAMING_SNAKE_CASE : List[Any] = '''.'''.join(['''output_blocks''', str(snake_case ), path['''old''']] )
__SCREAMING_SNAKE_CASE : List[Any] = '''.'''.join(['''up_blocks''', str(snake_case ), '''resnets''', str(snake_case ), path['''new''']] )
__SCREAMING_SNAKE_CASE : Any = checkpoint[old_path]
return new_checkpoint
if __name__ == "__main__":
lowercase_ = argparse.ArgumentParser()
parser.add_argument(
"""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert."""
)
parser.add_argument(
"""--config_file""",
default=None,
type=str,
required=True,
help="""The config json file corresponding to the architecture.""",
)
parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""")
lowercase_ = parser.parse_args()
lowercase_ = torch.load(args.checkpoint_path)
with open(args.config_file) as f:
lowercase_ = json.loads(f.read())
lowercase_ = convert_ldm_checkpoint(checkpoint, config)
if "ldm" in config:
del config["ldm"]
lowercase_ = UNetaDModel(**config)
model.load_state_dict(converted_checkpoint)
try:
lowercase_ = DDPMScheduler.from_config("""/""".join(args.checkpoint_path.split("""/""")[:-1]))
lowercase_ = VQModel.from_pretrained("""/""".join(args.checkpoint_path.split("""/""")[:-1]))
lowercase_ = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae)
pipe.save_pretrained(args.dump_path)
except: # noqa: E722
model.save_pretrained(args.dump_path)
| 131
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
lowercase_ = {"""configuration_deit""": ["""DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DeiTConfig""", """DeiTOnnxConfig"""]}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = ["""DeiTFeatureExtractor"""]
lowercase_ = ["""DeiTImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = [
"""DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""DeiTForImageClassification""",
"""DeiTForImageClassificationWithTeacher""",
"""DeiTForMaskedImageModeling""",
"""DeiTModel""",
"""DeiTPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase_ = [
"""TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFDeiTForImageClassification""",
"""TFDeiTForImageClassificationWithTeacher""",
"""TFDeiTForMaskedImageModeling""",
"""TFDeiTModel""",
"""TFDeiTPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_deit import DeiTFeatureExtractor
from .image_processing_deit import DeiTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deit import (
DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
DeiTModel,
DeiTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deit import (
TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDeiTForImageClassification,
TFDeiTForImageClassificationWithTeacher,
TFDeiTForMaskedImageModeling,
TFDeiTModel,
TFDeiTPreTrainedModel,
)
else:
import sys
lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 131
| 1
|
"""simple docstring"""
from ...processing_utils import ProcessorMixin
class UpperCAmelCase_ ( snake_case ):
UpperCamelCase ="WhisperFeatureExtractor"
UpperCamelCase ="WhisperTokenizer"
def __init__( self , UpperCamelCase_ , UpperCamelCase_ ) -> Dict:
super().__init__(UpperCamelCase_ , UpperCamelCase_ )
__lowercase : Union[str, Any] = self.feature_extractor
__lowercase : Tuple = False
def _lowerCamelCase ( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True ) -> Any:
return self.tokenizer.get_decoder_prompt_ids(task=UpperCamelCase_ , language=UpperCamelCase_ , no_timestamps=UpperCamelCase_ )
def __call__( self , *UpperCamelCase_ , **UpperCamelCase_ ) -> Optional[int]:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*UpperCamelCase_ , **UpperCamelCase_ )
__lowercase : Optional[int] = kwargs.pop('''audio''' , UpperCamelCase_ )
__lowercase : Optional[Any] = kwargs.pop('''sampling_rate''' , UpperCamelCase_ )
__lowercase : str = kwargs.pop('''text''' , UpperCamelCase_ )
if len(UpperCamelCase_ ) > 0:
__lowercase : Union[str, Any] = args[0]
__lowercase : List[str] = 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:
__lowercase : Tuple = self.feature_extractor(UpperCamelCase_ , *UpperCamelCase_ , sampling_rate=UpperCamelCase_ , **UpperCamelCase_ )
if text is not None:
__lowercase : List[Any] = self.tokenizer(UpperCamelCase_ , **UpperCamelCase_ )
if text is None:
return inputs
elif audio is None:
return encodings
else:
__lowercase : int = encodings['''input_ids''']
return inputs
def _lowerCamelCase ( self , *UpperCamelCase_ , **UpperCamelCase_ ) -> List[Any]:
return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ )
def _lowerCamelCase ( self , *UpperCamelCase_ , **UpperCamelCase_ ) -> List[Any]:
return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ )
def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_="np" ) -> int:
return self.tokenizer.get_prompt_ids(UpperCamelCase_ , return_tensors=UpperCamelCase_ )
| 76
|
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
a : Dict = {
'configuration_lxmert': ['LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LxmertConfig'],
'tokenization_lxmert': ['LxmertTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Any = ['LxmertTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : str = [
'LxmertEncoder',
'LxmertForPreTraining',
'LxmertForQuestionAnswering',
'LxmertModel',
'LxmertPreTrainedModel',
'LxmertVisualFeatureEncoder',
'LxmertXLayer',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : str = [
'TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFLxmertForPreTraining',
'TFLxmertMainLayer',
'TFLxmertModel',
'TFLxmertPreTrainedModel',
'TFLxmertVisualFeatureEncoder',
]
if TYPE_CHECKING:
from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig
from .tokenization_lxmert import LxmertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_lxmert_fast import LxmertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_lxmert import (
LxmertEncoder,
LxmertForPreTraining,
LxmertForQuestionAnswering,
LxmertModel,
LxmertPreTrainedModel,
LxmertVisualFeatureEncoder,
LxmertXLayer,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_lxmert import (
TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLxmertForPreTraining,
TFLxmertMainLayer,
TFLxmertModel,
TFLxmertPreTrainedModel,
TFLxmertVisualFeatureEncoder,
)
else:
import sys
a : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 556
| 0
|
'''simple docstring'''
import numpy as np
def _lowerCAmelCase ( __magic_name__ : np.ndarray ) -> np.ndarray:
return 1 / (1 + np.exp(-vector ))
def _lowerCAmelCase ( __magic_name__ : np.ndarray ) -> np.ndarray:
return vector * sigmoid(__magic_name__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 702
|
'''simple docstring'''
from collections import defaultdict
def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> bool:
lowercase : Optional[int] =first_str.lower().strip()
lowercase : Union[str, Any] =second_str.lower().strip()
# Remove whitespace
lowercase : Optional[int] =first_str.replace(''' ''' , '''''' )
lowercase : Optional[Any] =second_str.replace(''' ''' , '''''' )
# Strings of different lengths are not anagrams
if len(__magic_name__ ) != len(__magic_name__ ):
return False
# Default values for count should be 0
lowercase : defaultdict[str, int] =defaultdict(__magic_name__ )
# For each character in input strings,
# increment count in the corresponding
for i in range(len(__magic_name__ ) ):
count[first_str[i]] += 1
count[second_str[i]] -= 1
return all(_count == 0 for _count in count.values() )
if __name__ == "__main__":
from doctest import testmod
testmod()
UpperCamelCase_ = input("""Enter the first string """).strip()
UpperCamelCase_ = input("""Enter the second string """).strip()
UpperCamelCase_ = check_anagrams(input_a, input_b)
print(f'''{input_a} and {input_b} are {'' if status else 'not '}anagrams.''')
| 88
| 0
|
"""simple docstring"""
import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union
import datasets
import numpy as np
import torch
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForMultipleChoice,
AutoTokenizer,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')
__SCREAMING_SNAKE_CASE = logging.getLogger(__name__)
@dataclass
class __UpperCamelCase :
lowercase_ : str = field(
metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
lowercase_ : Optional[str] = field(
default=UpperCamelCase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
lowercase_ : Optional[str] = field(
default=UpperCamelCase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
lowercase_ : Optional[str] = field(
default=UpperCamelCase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
lowercase_ : bool = field(
default=UpperCamelCase , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , )
lowercase_ : str = field(
default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , )
lowercase_ : bool = field(
default=UpperCamelCase , metadata={
"""help""": (
"""Will use the token generated when running `huggingface-cli login` (necessary to use this script """
"""with private models)."""
)
} , )
@dataclass
class __UpperCamelCase :
lowercase_ : Optional[str] = field(default=UpperCamelCase , metadata={"""help""": """The input training data file (a text file)."""} )
lowercase_ : Optional[str] = field(
default=UpperCamelCase , metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""} , )
lowercase_ : bool = field(
default=UpperCamelCase , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} )
lowercase_ : Optional[int] = field(
default=UpperCamelCase , metadata={"""help""": """The number of processes to use for the preprocessing."""} , )
lowercase_ : Optional[int] = field(
default=UpperCamelCase , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. If passed, sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
lowercase_ : bool = field(
default=UpperCamelCase , metadata={
"""help""": (
"""Whether to pad all samples to the maximum sentence length. """
"""If False, will pad the samples dynamically when batching to the maximum length in the batch. More """
"""efficient on GPU but very bad for TPU."""
)
} , )
lowercase_ : Optional[int] = field(
default=UpperCamelCase , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of training examples to this """
"""value if set."""
)
} , )
lowercase_ : Optional[int] = field(
default=UpperCamelCase , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of evaluation examples to this """
"""value if set."""
)
} , )
def UpperCAmelCase__ ( self : Tuple ) -> List[Any]:
if self.train_file is not None:
lowerCAmelCase :int = self.train_file.split('.' )[-1]
assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
if self.validation_file is not None:
lowerCAmelCase :int = self.validation_file.split('.' )[-1]
assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
@dataclass
class __UpperCamelCase :
lowercase_ : PreTrainedTokenizerBase
lowercase_ : Union[bool, str, PaddingStrategy] = True
lowercase_ : Optional[int] = None
lowercase_ : Optional[int] = None
def __call__( self : List[Any] , UpperCAmelCase : Union[str, Any] ) -> Optional[int]:
lowerCAmelCase :Dict = 'label' if 'label' in features[0].keys() else 'labels'
lowerCAmelCase :Any = [feature.pop(UpperCAmelCase ) for feature in features]
lowerCAmelCase :int = len(UpperCAmelCase )
lowerCAmelCase :int = len(features[0]['input_ids'] )
lowerCAmelCase :Optional[Any] = [
[{k: v[i] for k, v in feature.items()} for i in range(UpperCAmelCase )] for feature in features
]
lowerCAmelCase :Optional[Any] = list(chain(*UpperCAmelCase ) )
lowerCAmelCase :Any = self.tokenizer.pad(
UpperCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , )
# Un-flatten
lowerCAmelCase :Optional[int] = {k: v.view(UpperCAmelCase , UpperCAmelCase , -1 ) for k, v in batch.items()}
# Add back labels
lowerCAmelCase :List[Any] = torch.tensor(UpperCAmelCase , dtype=torch.intaa )
return batch
def UpperCAmelCase ( ):
'''simple docstring'''
lowerCAmelCase :Union[str, Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase :Dict = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase :Optional[int] = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry('run_swag' , a__ , a__ )
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , )
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
lowerCAmelCase :str = training_args.get_process_log_level()
logger.setLevel(a__ )
datasets.utils.logging.set_verbosity(a__ )
transformers.utils.logging.set_verbosity(a__ )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
+ F"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" )
logger.info(F"""Training/evaluation parameters {training_args}""" )
# Detecting last checkpoint.
lowerCAmelCase :Dict = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
lowerCAmelCase :Dict = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
'Use --overwrite_output_dir to overcome.' )
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' )
# Set seed before initializing model.
set_seed(training_args.seed )
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.train_file is not None or data_args.validation_file is not None:
lowerCAmelCase :Union[str, Any] = {}
if data_args.train_file is not None:
lowerCAmelCase :Optional[Any] = data_args.train_file
if data_args.validation_file is not None:
lowerCAmelCase :str = data_args.validation_file
lowerCAmelCase :List[str] = data_args.train_file.split('.' )[-1]
lowerCAmelCase :Optional[int] = load_dataset(
a__ , data_files=a__ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
else:
# Downloading and loading the swag dataset from the hub.
lowerCAmelCase :Dict = load_dataset(
'swag' , 'regular' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Load pretrained model and tokenizer
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCAmelCase :Union[str, Any] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase :Union[str, Any] = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
lowerCAmelCase :List[str] = AutoModelForMultipleChoice.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=a__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
# When using your own dataset or a different dataset from swag, you will probably need to change this.
lowerCAmelCase :Any = [F"""ending{i}""" for i in range(4 )]
lowerCAmelCase :str = 'sent1'
lowerCAmelCase :Optional[int] = 'sent2'
if data_args.max_seq_length is None:
lowerCAmelCase :Union[str, Any] = tokenizer.model_max_length
if max_seq_length > 10_24:
logger.warning(
'The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value'
' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can'
' override this default with `--block_size xxx`.' )
lowerCAmelCase :Tuple = 10_24
else:
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warning(
F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" )
lowerCAmelCase :str = min(data_args.max_seq_length , tokenizer.model_max_length )
# Preprocessing the datasets.
def preprocess_function(a__ ):
lowerCAmelCase :int = [[context] * 4 for context in examples[context_name]]
lowerCAmelCase :List[str] = examples[question_header_name]
lowerCAmelCase :Tuple = [
[F"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(a__ )
]
# Flatten out
lowerCAmelCase :Any = list(chain(*a__ ) )
lowerCAmelCase :Dict = list(chain(*a__ ) )
# Tokenize
lowerCAmelCase :str = tokenizer(
a__ , a__ , truncation=a__ , max_length=a__ , padding='max_length' if data_args.pad_to_max_length else False , )
# Un-flatten
return {k: [v[i : i + 4] for i in range(0 , len(a__ ) , 4 )] for k, v in tokenized_examples.items()}
if training_args.do_train:
if "train" not in raw_datasets:
raise ValueError('--do_train requires a train dataset' )
lowerCAmelCase :Optional[int] = raw_datasets['train']
if data_args.max_train_samples is not None:
lowerCAmelCase :int = min(len(a__ ) , data_args.max_train_samples )
lowerCAmelCase :int = train_dataset.select(range(a__ ) )
with training_args.main_process_first(desc='train dataset map pre-processing' ):
lowerCAmelCase :Dict = train_dataset.map(
a__ , batched=a__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , )
if training_args.do_eval:
if "validation" not in raw_datasets:
raise ValueError('--do_eval requires a validation dataset' )
lowerCAmelCase :Tuple = raw_datasets['validation']
if data_args.max_eval_samples is not None:
lowerCAmelCase :Any = min(len(a__ ) , data_args.max_eval_samples )
lowerCAmelCase :str = eval_dataset.select(range(a__ ) )
with training_args.main_process_first(desc='validation dataset map pre-processing' ):
lowerCAmelCase :List[str] = eval_dataset.map(
a__ , batched=a__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , )
# Data collator
lowerCAmelCase :List[str] = (
default_data_collator
if data_args.pad_to_max_length
else DataCollatorForMultipleChoice(tokenizer=a__ , pad_to_multiple_of=8 if training_args.fpaa else None )
)
# Metric
def compute_metrics(a__ ):
lowerCAmelCase , lowerCAmelCase :List[str] = eval_predictions
lowerCAmelCase :Tuple = np.argmax(a__ , axis=1 )
return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()}
# Initialize our Trainer
lowerCAmelCase :List[str] = Trainer(
model=a__ , args=a__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=a__ , data_collator=a__ , compute_metrics=a__ , )
# Training
if training_args.do_train:
lowerCAmelCase :Optional[Any] = None
if training_args.resume_from_checkpoint is not None:
lowerCAmelCase :Tuple = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
lowerCAmelCase :Union[str, Any] = last_checkpoint
lowerCAmelCase :Optional[int] = trainer.train(resume_from_checkpoint=a__ )
trainer.save_model() # Saves the tokenizer too for easy upload
lowerCAmelCase :Tuple = train_result.metrics
lowerCAmelCase :Union[str, Any] = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(a__ )
)
lowerCAmelCase :List[Any] = min(a__ , len(a__ ) )
trainer.log_metrics('train' , a__ )
trainer.save_metrics('train' , a__ )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info('*** Evaluate ***' )
lowerCAmelCase :Dict = trainer.evaluate()
lowerCAmelCase :Any = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(a__ )
lowerCAmelCase :Tuple = min(a__ , len(a__ ) )
trainer.log_metrics('eval' , a__ )
trainer.save_metrics('eval' , a__ )
lowerCAmelCase :List[str] = {
'finetuned_from': model_args.model_name_or_path,
'tasks': 'multiple-choice',
'dataset_tags': 'swag',
'dataset_args': 'regular',
'dataset': 'SWAG',
'language': 'en',
}
if training_args.push_to_hub:
trainer.push_to_hub(**a__ )
else:
trainer.create_model_card(**a__ )
def UpperCAmelCase ( a__ ):
'''simple docstring'''
main()
if __name__ == "__main__":
main()
| 553
|
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
__SCREAMING_SNAKE_CASE = {
'configuration_transfo_xl': ['TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TransfoXLConfig'],
'tokenization_transfo_xl': ['TransfoXLCorpus', 'TransfoXLTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE = [
'TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST',
'AdaptiveEmbedding',
'TransfoXLForSequenceClassification',
'TransfoXLLMHeadModel',
'TransfoXLModel',
'TransfoXLPreTrainedModel',
'load_tf_weights_in_transfo_xl',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE = [
'TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFAdaptiveEmbedding',
'TFTransfoXLForSequenceClassification',
'TFTransfoXLLMHeadModel',
'TFTransfoXLMainLayer',
'TFTransfoXLModel',
'TFTransfoXLPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig
from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_transfo_xl import (
TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
AdaptiveEmbedding,
TransfoXLForSequenceClassification,
TransfoXLLMHeadModel,
TransfoXLModel,
TransfoXLPreTrainedModel,
load_tf_weights_in_transfo_xl,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_transfo_xl import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAdaptiveEmbedding,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLMainLayer,
TFTransfoXLModel,
TFTransfoXLPreTrainedModel,
)
else:
import sys
__SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 553
| 1
|
from math import log
from scipy.constants import Boltzmann, physical_constants
lowercase_ = 3_0_0 # TEMPERATURE (unit = K)
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ):
if donor_conc <= 0:
raise ValueError('Donor concentration should be positive' )
elif acceptor_conc <= 0:
raise ValueError('Acceptor concentration should be positive' )
elif intrinsic_conc <= 0:
raise ValueError('Intrinsic concentration should be positive' )
elif donor_conc <= intrinsic_conc:
raise ValueError(
'Donor concentration should be greater than intrinsic concentration' )
elif acceptor_conc <= intrinsic_conc:
raise ValueError(
'Acceptor concentration should be greater than intrinsic concentration' )
else:
return (
Boltzmann
* T
* log((donor_conc * acceptor_conc) / intrinsic_conc**2 )
/ physical_constants["electron volt"][0]
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 230
|
from operator import delitem, getitem, setitem
import pytest
from data_structures.hashing.hash_map import HashMap
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ):
return getitem, k
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
return setitem, k, v
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ):
return delitem, k
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ):
try:
return fun(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ), None
except Exception as e:
return None, e
lowercase_ = (
_set('key_a', 'val_a'),
_set('key_b', 'val_b'),
)
lowercase_ = [
_set('key_a', 'val_a'),
_set('key_a', 'val_b'),
]
lowercase_ = [
_set('key_a', 'val_a'),
_set('key_b', 'val_b'),
_del('key_a'),
_del('key_b'),
_set('key_a', 'val_a'),
_del('key_a'),
]
lowercase_ = [
_get('key_a'),
_del('key_a'),
_set('key_a', 'val_a'),
_del('key_a'),
_del('key_a'),
_get('key_a'),
]
lowercase_ = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
]
lowercase_ = [
*[_set(x, x) for x in range(5)], # guaranteed upsize
*[_del(x) for x in range(5)],
_set('key_a', 'val_b'),
]
@pytest.mark.parametrize(
'operations' , (
pytest.param(_add_items , id='add items' ),
pytest.param(_overwrite_items , id='overwrite items' ),
pytest.param(_delete_items , id='delete items' ),
pytest.param(_access_absent_items , id='access absent items' ),
pytest.param(_add_with_resize_up , id='add with resize up' ),
pytest.param(_add_with_resize_down , id='add with resize down' ),
) , )
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase : int = HashMap(initial_block_size=4 )
__lowerCamelCase : Dict = {}
for _, (fun, *args) in enumerate(SCREAMING_SNAKE_CASE__ ):
__lowerCamelCase , __lowerCamelCase : Union[str, Any] = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ )
__lowerCamelCase , __lowerCamelCase : str = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ )
assert my_res == py_res
assert str(SCREAMING_SNAKE_CASE__ ) == str(SCREAMING_SNAKE_CASE__ )
assert set(SCREAMING_SNAKE_CASE__ ) == set(SCREAMING_SNAKE_CASE__ )
assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ )
assert set(my.items() ) == set(py.items() )
def UpperCamelCase__ ( ):
def is_public(SCREAMING_SNAKE_CASE__ ) -> bool:
return not name.startswith('_' )
__lowerCamelCase : Optional[Any] = {name for name in dir({} ) if is_public(SCREAMING_SNAKE_CASE__ )}
__lowerCamelCase : Dict = {name for name in dir(HashMap() ) if is_public(SCREAMING_SNAKE_CASE__ )}
assert dict_public_names > hash_public_names
| 230
| 1
|
'''simple docstring'''
import os
import tempfile
import unittest
from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
FlaubertForMultipleChoice,
FlaubertForQuestionAnswering,
FlaubertForQuestionAnsweringSimple,
FlaubertForSequenceClassification,
FlaubertForTokenClassification,
FlaubertModel,
FlaubertWithLMHeadModel,
)
from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class __lowercase ( lowerCAmelCase__ ):
'''simple docstring'''
def __init__(self ,_lowerCamelCase ,_lowerCamelCase=13 ,_lowerCamelCase=7 ,_lowerCamelCase=True ,_lowerCamelCase=True ,_lowerCamelCase=True ,_lowerCamelCase=True ,_lowerCamelCase=True ,_lowerCamelCase=False ,_lowerCamelCase=False ,_lowerCamelCase=False ,_lowerCamelCase=2 ,_lowerCamelCase=99 ,_lowerCamelCase=0 ,_lowerCamelCase=32 ,_lowerCamelCase=5 ,_lowerCamelCase=4 ,_lowerCamelCase=0.1 ,_lowerCamelCase=0.1 ,_lowerCamelCase=512 ,_lowerCamelCase=12 ,_lowerCamelCase=2 ,_lowerCamelCase=0.0_2 ,_lowerCamelCase=3 ,_lowerCamelCase=4 ,_lowerCamelCase="last" ,_lowerCamelCase=None ,_lowerCamelCase=None ,) -> Tuple:
'''simple docstring'''
__lowercase = parent
__lowercase = batch_size
__lowercase = seq_length
__lowercase = is_training
__lowercase = use_input_lengths
__lowercase = use_token_type_ids
__lowercase = use_labels
__lowercase = gelu_activation
__lowercase = sinusoidal_embeddings
__lowercase = causal
__lowercase = asm
__lowercase = n_langs
__lowercase = vocab_size
__lowercase = n_special
__lowercase = hidden_size
__lowercase = num_hidden_layers
__lowercase = num_attention_heads
__lowercase = hidden_dropout_prob
__lowercase = attention_probs_dropout_prob
__lowercase = max_position_embeddings
__lowercase = type_vocab_size
__lowercase = type_sequence_label_size
__lowercase = initializer_range
__lowercase = num_labels
__lowercase = num_choices
__lowercase = summary_type
__lowercase = use_proj
__lowercase = scope
def _UpperCAmelCase (self ) -> Tuple:
'''simple docstring'''
__lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size )
__lowercase = random_attention_mask([self.batch_size, self.seq_length] )
__lowercase = None
if self.use_input_lengths:
__lowercase = (
ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2
) # small variation of seq_length
__lowercase = None
if self.use_token_type_ids:
__lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs )
__lowercase = None
__lowercase = None
__lowercase = None
if self.use_labels:
__lowercase = ids_tensor([self.batch_size] ,self.type_sequence_label_size )
__lowercase = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels )
__lowercase = ids_tensor([self.batch_size] ,2 ).float()
__lowercase = ids_tensor([self.batch_size] ,self.num_choices )
__lowercase = self.get_config()
return (
config,
input_ids,
token_type_ids,
input_lengths,
sequence_labels,
token_labels,
is_impossible_labels,
choice_labels,
input_mask,
)
def _UpperCAmelCase (self ) -> int:
'''simple docstring'''
return FlaubertConfig(
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 ,)
def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Union[str, Any]:
'''simple docstring'''
__lowercase = FlaubertModel(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = model(_lowerCamelCase ,lengths=_lowerCamelCase ,langs=_lowerCamelCase )
__lowercase = model(_lowerCamelCase ,langs=_lowerCamelCase )
__lowercase = model(_lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) )
def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Optional[int]:
'''simple docstring'''
__lowercase = FlaubertWithLMHeadModel(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = model(_lowerCamelCase ,token_type_ids=_lowerCamelCase ,labels=_lowerCamelCase )
self.parent.assertEqual(result.loss.shape ,() )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) )
def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Union[str, Any]:
'''simple docstring'''
__lowercase = FlaubertForQuestionAnsweringSimple(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = model(_lowerCamelCase )
__lowercase = model(_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 _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Optional[int]:
'''simple docstring'''
__lowercase = FlaubertForQuestionAnswering(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = model(_lowerCamelCase )
__lowercase = model(
_lowerCamelCase ,start_positions=_lowerCamelCase ,end_positions=_lowerCamelCase ,cls_index=_lowerCamelCase ,is_impossible=_lowerCamelCase ,p_mask=_lowerCamelCase ,)
__lowercase = model(
_lowerCamelCase ,start_positions=_lowerCamelCase ,end_positions=_lowerCamelCase ,cls_index=_lowerCamelCase ,is_impossible=_lowerCamelCase ,)
((__lowercase) , ) = result_with_labels.to_tuple()
__lowercase = model(_lowerCamelCase ,start_positions=_lowerCamelCase ,end_positions=_lowerCamelCase )
((__lowercase) , ) = 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 _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Optional[int]:
'''simple docstring'''
__lowercase = FlaubertForSequenceClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = model(_lowerCamelCase )
__lowercase = model(_lowerCamelCase ,labels=_lowerCamelCase )
self.parent.assertEqual(result.loss.shape ,() )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) )
def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Tuple:
'''simple docstring'''
__lowercase = self.num_labels
__lowercase = FlaubertForTokenClassification(_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = model(_lowerCamelCase ,attention_mask=_lowerCamelCase ,labels=_lowerCamelCase )
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) )
def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,) -> Optional[int]:
'''simple docstring'''
__lowercase = self.num_choices
__lowercase = FlaubertForMultipleChoice(config=_lowerCamelCase )
model.to(_lowerCamelCase )
model.eval()
__lowercase = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
__lowercase = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
__lowercase = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous()
__lowercase = model(
_lowerCamelCase ,attention_mask=_lowerCamelCase ,token_type_ids=_lowerCamelCase ,labels=_lowerCamelCase ,)
self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) )
def _UpperCAmelCase (self ) -> Dict:
'''simple docstring'''
__lowercase = self.prepare_config_and_inputs()
(
(
__lowercase
) , (
__lowercase
) , (
__lowercase
) , (
__lowercase
) , (
__lowercase
) , (
__lowercase
) , (
__lowercase
) , (
__lowercase
) , (
__lowercase
) ,
) = config_and_inputs
__lowercase = {
'''input_ids''': input_ids,
'''token_type_ids''': token_type_ids,
'''lengths''': input_lengths,
'''attention_mask''': input_mask,
}
return config, inputs_dict
@require_torch
class __lowercase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
a : int = (
(
FlaubertModel,
FlaubertWithLMHeadModel,
FlaubertForQuestionAnswering,
FlaubertForQuestionAnsweringSimple,
FlaubertForSequenceClassification,
FlaubertForTokenClassification,
FlaubertForMultipleChoice,
)
if is_torch_available()
else ()
)
a : List[str] = (
{
"feature-extraction": FlaubertModel,
"fill-mask": FlaubertWithLMHeadModel,
"question-answering": FlaubertForQuestionAnsweringSimple,
"text-classification": FlaubertForSequenceClassification,
"token-classification": FlaubertForTokenClassification,
"zero-shot": FlaubertForSequenceClassification,
}
if is_torch_available()
else {}
)
def _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) -> Union[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 _UpperCAmelCase (self ,_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase=False ) -> List[str]:
'''simple docstring'''
__lowercase = super()._prepare_for_class(_lowerCamelCase ,_lowerCamelCase ,return_labels=_lowerCamelCase )
if return_labels:
if model_class.__name__ == "FlaubertForQuestionAnswering":
__lowercase = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=_lowerCamelCase )
__lowercase = torch.zeros(
self.model_tester.batch_size ,dtype=torch.long ,device=_lowerCamelCase )
return inputs_dict
def _UpperCAmelCase (self ) -> Any:
'''simple docstring'''
__lowercase = FlaubertModelTester(self )
__lowercase = ConfigTester(self ,config_class=_lowerCamelCase ,emb_dim=37 )
def _UpperCAmelCase (self ) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def _UpperCAmelCase (self ) -> str:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_model(*_lowerCamelCase )
def _UpperCAmelCase (self ) -> Any:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_lm_head(*_lowerCamelCase )
def _UpperCAmelCase (self ) -> List[Any]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_simple_qa(*_lowerCamelCase )
def _UpperCAmelCase (self ) -> Any:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_qa(*_lowerCamelCase )
def _UpperCAmelCase (self ) -> List[Any]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_sequence_classif(*_lowerCamelCase )
def _UpperCAmelCase (self ) -> Union[str, Any]:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_token_classif(*_lowerCamelCase )
def _UpperCAmelCase (self ) -> Any:
'''simple docstring'''
__lowercase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_flaubert_multiple_choice(*_lowerCamelCase )
@slow
def _UpperCAmelCase (self ) -> Dict:
'''simple docstring'''
for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__lowercase = FlaubertModel.from_pretrained(_lowerCamelCase )
self.assertIsNotNone(_lowerCamelCase )
@slow
@require_torch_gpu
def _UpperCAmelCase (self ) -> List[Any]:
'''simple docstring'''
__lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
# FlauBertForMultipleChoice behaves incorrectly in JIT environments.
if model_class == FlaubertForMultipleChoice:
return
__lowercase = True
__lowercase = model_class(config=_lowerCamelCase )
__lowercase = self._prepare_for_class(_lowerCamelCase ,_lowerCamelCase )
__lowercase = torch.jit.trace(
_lowerCamelCase ,(inputs_dict['''input_ids'''].to('''cpu''' ), inputs_dict['''attention_mask'''].to('''cpu''' )) )
with tempfile.TemporaryDirectory() as tmp:
torch.jit.save(_lowerCamelCase ,os.path.join(_lowerCamelCase ,'''traced_model.pt''' ) )
__lowercase = torch.jit.load(os.path.join(_lowerCamelCase ,'''traced_model.pt''' ) ,map_location=_lowerCamelCase )
loaded(inputs_dict['''input_ids'''].to(_lowerCamelCase ) ,inputs_dict['''attention_mask'''].to(_lowerCamelCase ) )
@require_torch
class __lowercase ( unittest.TestCase ):
'''simple docstring'''
@slow
def _UpperCAmelCase (self ) -> List[Any]:
'''simple docstring'''
__lowercase = FlaubertModel.from_pretrained('''flaubert/flaubert_base_cased''' )
__lowercase = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
with torch.no_grad():
__lowercase = model(_lowerCamelCase )[0]
__lowercase = torch.Size((1, 11, 768) )
self.assertEqual(output.shape ,_lowerCamelCase )
__lowercase = torch.tensor(
[[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] ,_lowerCamelCase ,atol=1E-4 ) )
| 502
|
'''simple docstring'''
import string
def _lowerCAmelCase ( lowerCamelCase_ : str ):
__lowercase = ''''''
for i in sequence:
__lowercase = ord(lowerCamelCase_ )
if 6_5 <= extract <= 9_0:
output += chr(1_5_5 - extract )
elif 9_7 <= extract <= 1_2_2:
output += chr(2_1_9 - extract )
else:
output += i
return output
def _lowerCAmelCase ( lowerCamelCase_ : str ):
__lowercase = string.ascii_letters
__lowercase = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(lowerCamelCase_ )] if c in letters else c for c in sequence )
def _lowerCAmelCase ( ):
from timeit import timeit
print('''Running performance benchmarks...''' )
__lowercase = '''from string import printable ; from __main__ import atbash, atbash_slow'''
print(f"> atbash_slow(): {timeit('atbash_slow(printable)' , setup=lowerCamelCase_ )} seconds" )
print(f"> atbash(): {timeit('atbash(printable)' , setup=lowerCamelCase_ )} seconds" )
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f'''{example} encrypted in atbash: {atbash(example)}''')
benchmark()
| 502
| 1
|
'''simple docstring'''
import argparse
import os
import torch
from diffusers import (
CMStochasticIterativeScheduler,
ConsistencyModelPipeline,
UNetaDModel,
)
_a : Tuple = {
"sample_size": 32,
"in_channels": 3,
"out_channels": 3,
"layers_per_block": 2,
"num_class_embeds": 1000,
"block_out_channels": [32, 64],
"attention_head_dim": 8,
"down_block_types": [
"ResnetDownsampleBlock2D",
"AttnDownBlock2D",
],
"up_block_types": [
"AttnUpBlock2D",
"ResnetUpsampleBlock2D",
],
"resnet_time_scale_shift": "scale_shift",
"upsample_type": "resnet",
"downsample_type": "resnet",
}
_a : Optional[Any] = {
"sample_size": 64,
"in_channels": 3,
"out_channels": 3,
"layers_per_block": 3,
"num_class_embeds": 1000,
"block_out_channels": [192, 192 * 2, 192 * 3, 192 * 4],
"attention_head_dim": 64,
"down_block_types": [
"ResnetDownsampleBlock2D",
"AttnDownBlock2D",
"AttnDownBlock2D",
"AttnDownBlock2D",
],
"up_block_types": [
"AttnUpBlock2D",
"AttnUpBlock2D",
"AttnUpBlock2D",
"ResnetUpsampleBlock2D",
],
"resnet_time_scale_shift": "scale_shift",
"upsample_type": "resnet",
"downsample_type": "resnet",
}
_a : Optional[Any] = {
"sample_size": 256,
"in_channels": 3,
"out_channels": 3,
"layers_per_block": 2,
"num_class_embeds": None,
"block_out_channels": [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4],
"attention_head_dim": 64,
"down_block_types": [
"ResnetDownsampleBlock2D",
"ResnetDownsampleBlock2D",
"ResnetDownsampleBlock2D",
"AttnDownBlock2D",
"AttnDownBlock2D",
"AttnDownBlock2D",
],
"up_block_types": [
"AttnUpBlock2D",
"AttnUpBlock2D",
"AttnUpBlock2D",
"ResnetUpsampleBlock2D",
"ResnetUpsampleBlock2D",
"ResnetUpsampleBlock2D",
],
"resnet_time_scale_shift": "default",
"upsample_type": "resnet",
"downsample_type": "resnet",
}
_a : Optional[Any] = {
"num_train_timesteps": 40,
"sigma_min": 0.002,
"sigma_max": 80.0,
}
_a : List[str] = {
"num_train_timesteps": 201,
"sigma_min": 0.002,
"sigma_max": 80.0,
}
_a : str = {
"num_train_timesteps": 151,
"sigma_min": 0.002,
"sigma_max": 80.0,
}
def _lowercase ( lowerCamelCase__ ) -> Tuple:
"""simple docstring"""
if isinstance(lowerCamelCase__ , lowerCamelCase__ ):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("boolean value expected" )
def _lowercase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ) -> int:
"""simple docstring"""
__UpperCAmelCase : Union[str, Any] = checkpoint[f"""{old_prefix}.in_layers.0.weight"""]
__UpperCAmelCase : Any = checkpoint[f"""{old_prefix}.in_layers.0.bias"""]
__UpperCAmelCase : Optional[Any] = checkpoint[f"""{old_prefix}.in_layers.2.weight"""]
__UpperCAmelCase : List[Any] = checkpoint[f"""{old_prefix}.in_layers.2.bias"""]
__UpperCAmelCase : Dict = checkpoint[f"""{old_prefix}.emb_layers.1.weight"""]
__UpperCAmelCase : List[str] = checkpoint[f"""{old_prefix}.emb_layers.1.bias"""]
__UpperCAmelCase : List[str] = checkpoint[f"""{old_prefix}.out_layers.0.weight"""]
__UpperCAmelCase : Optional[int] = checkpoint[f"""{old_prefix}.out_layers.0.bias"""]
__UpperCAmelCase : Optional[int] = checkpoint[f"""{old_prefix}.out_layers.3.weight"""]
__UpperCAmelCase : Union[str, Any] = checkpoint[f"""{old_prefix}.out_layers.3.bias"""]
if has_skip:
__UpperCAmelCase : List[str] = checkpoint[f"""{old_prefix}.skip_connection.weight"""]
__UpperCAmelCase : int = checkpoint[f"""{old_prefix}.skip_connection.bias"""]
return new_checkpoint
def _lowercase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> Optional[Any]:
"""simple docstring"""
__UpperCAmelCase : int = checkpoint[f"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 )
__UpperCAmelCase : List[str] = checkpoint[f"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 )
__UpperCAmelCase : Any = checkpoint[f"""{old_prefix}.norm.weight"""]
__UpperCAmelCase : int = checkpoint[f"""{old_prefix}.norm.bias"""]
__UpperCAmelCase : Union[str, Any] = weight_q.squeeze(-1 ).squeeze(-1 )
__UpperCAmelCase : int = bias_q.squeeze(-1 ).squeeze(-1 )
__UpperCAmelCase : List[Any] = weight_k.squeeze(-1 ).squeeze(-1 )
__UpperCAmelCase : Any = bias_k.squeeze(-1 ).squeeze(-1 )
__UpperCAmelCase : List[str] = weight_v.squeeze(-1 ).squeeze(-1 )
__UpperCAmelCase : Any = bias_v.squeeze(-1 ).squeeze(-1 )
__UpperCAmelCase : Dict = (
checkpoint[f"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 )
)
__UpperCAmelCase : List[str] = checkpoint[f"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 )
return new_checkpoint
def _lowercase ( lowerCamelCase__ , lowerCamelCase__ ) -> Dict:
"""simple docstring"""
__UpperCAmelCase : int = torch.load(lowerCamelCase__ , map_location="cpu" )
__UpperCAmelCase : Union[str, Any] = {}
__UpperCAmelCase : Tuple = checkpoint["time_embed.0.weight"]
__UpperCAmelCase : Any = checkpoint["time_embed.0.bias"]
__UpperCAmelCase : Union[str, Any] = checkpoint["time_embed.2.weight"]
__UpperCAmelCase : List[Any] = checkpoint["time_embed.2.bias"]
if unet_config["num_class_embeds"] is not None:
__UpperCAmelCase : str = checkpoint["label_emb.weight"]
__UpperCAmelCase : Union[str, Any] = checkpoint["input_blocks.0.0.weight"]
__UpperCAmelCase : Optional[int] = checkpoint["input_blocks.0.0.bias"]
__UpperCAmelCase : Tuple = unet_config["down_block_types"]
__UpperCAmelCase : Optional[Any] = unet_config["layers_per_block"]
__UpperCAmelCase : Optional[Any] = unet_config["attention_head_dim"]
__UpperCAmelCase : int = unet_config["block_out_channels"]
__UpperCAmelCase : int = 1
__UpperCAmelCase : List[Any] = channels_list[0]
for i, layer_type in enumerate(lowerCamelCase__ ):
__UpperCAmelCase : Tuple = channels_list[i]
__UpperCAmelCase : Tuple = current_channels != prev_channels
if layer_type == "ResnetDownsampleBlock2D":
for j in range(lowerCamelCase__ ):
__UpperCAmelCase : Dict = f"""down_blocks.{i}.resnets.{j}"""
__UpperCAmelCase : Dict = f"""input_blocks.{current_layer}.0"""
__UpperCAmelCase : Optional[Any] = True if j == 0 and downsample_block_has_skip else False
__UpperCAmelCase : Dict = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ )
current_layer += 1
elif layer_type == "AttnDownBlock2D":
for j in range(lowerCamelCase__ ):
__UpperCAmelCase : str = f"""down_blocks.{i}.resnets.{j}"""
__UpperCAmelCase : Any = f"""input_blocks.{current_layer}.0"""
__UpperCAmelCase : str = True if j == 0 and downsample_block_has_skip else False
__UpperCAmelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ )
__UpperCAmelCase : List[str] = f"""down_blocks.{i}.attentions.{j}"""
__UpperCAmelCase : Dict = f"""input_blocks.{current_layer}.1"""
__UpperCAmelCase : Union[str, Any] = convert_attention(
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
current_layer += 1
if i != len(lowerCamelCase__ ) - 1:
__UpperCAmelCase : Dict = f"""down_blocks.{i}.downsamplers.0"""
__UpperCAmelCase : int = f"""input_blocks.{current_layer}.0"""
__UpperCAmelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
current_layer += 1
__UpperCAmelCase : Union[str, Any] = current_channels
# hardcoded the mid-block for now
__UpperCAmelCase : str = "mid_block.resnets.0"
__UpperCAmelCase : Optional[Any] = "middle_block.0"
__UpperCAmelCase : Optional[int] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
__UpperCAmelCase : str = "mid_block.attentions.0"
__UpperCAmelCase : int = "middle_block.1"
__UpperCAmelCase : Union[str, Any] = convert_attention(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
__UpperCAmelCase : List[str] = "mid_block.resnets.1"
__UpperCAmelCase : int = "middle_block.2"
__UpperCAmelCase : Any = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
__UpperCAmelCase : Dict = 0
__UpperCAmelCase : List[str] = unet_config["up_block_types"]
for i, layer_type in enumerate(lowerCamelCase__ ):
if layer_type == "ResnetUpsampleBlock2D":
for j in range(layers_per_block + 1 ):
__UpperCAmelCase : Union[str, Any] = f"""up_blocks.{i}.resnets.{j}"""
__UpperCAmelCase : Optional[int] = f"""output_blocks.{current_layer}.0"""
__UpperCAmelCase : Union[str, Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ )
current_layer += 1
if i != len(lowerCamelCase__ ) - 1:
__UpperCAmelCase : List[Any] = f"""up_blocks.{i}.upsamplers.0"""
__UpperCAmelCase : List[Any] = f"""output_blocks.{current_layer-1}.1"""
__UpperCAmelCase : List[Any] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
elif layer_type == "AttnUpBlock2D":
for j in range(layers_per_block + 1 ):
__UpperCAmelCase : int = f"""up_blocks.{i}.resnets.{j}"""
__UpperCAmelCase : Union[str, Any] = f"""output_blocks.{current_layer}.0"""
__UpperCAmelCase : Dict = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , has_skip=lowerCamelCase__ )
__UpperCAmelCase : Union[str, Any] = f"""up_blocks.{i}.attentions.{j}"""
__UpperCAmelCase : str = f"""output_blocks.{current_layer}.1"""
__UpperCAmelCase : Tuple = convert_attention(
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
current_layer += 1
if i != len(lowerCamelCase__ ) - 1:
__UpperCAmelCase : Any = f"""up_blocks.{i}.upsamplers.0"""
__UpperCAmelCase : List[Any] = f"""output_blocks.{current_layer-1}.2"""
__UpperCAmelCase : Optional[int] = convert_resnet(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ )
__UpperCAmelCase : Union[str, Any] = checkpoint["out.0.weight"]
__UpperCAmelCase : Optional[int] = checkpoint["out.0.bias"]
__UpperCAmelCase : Optional[int] = checkpoint["out.2.weight"]
__UpperCAmelCase : List[Any] = checkpoint["out.2.bias"]
return new_checkpoint
if __name__ == "__main__":
_a : Optional[int] = argparse.ArgumentParser()
parser.add_argument("--unet_path", default=None, type=str, required=True, help="Path to the unet.pt to convert.")
parser.add_argument(
"--dump_path", default=None, type=str, required=True, help="Path to output the converted UNet model."
)
parser.add_argument("--class_cond", default=True, type=str, help="Whether the model is class-conditional.")
_a : Any = parser.parse_args()
_a : Optional[Any] = strabool(args.class_cond)
_a : Any = os.path.basename(args.unet_path)
print(f"""Checkpoint: {ckpt_name}""")
# Get U-Net config
if "imagenet64" in ckpt_name:
_a : Optional[int] = IMAGENET_64_UNET_CONFIG
elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
_a : str = LSUN_256_UNET_CONFIG
elif "test" in ckpt_name:
_a : List[Any] = TEST_UNET_CONFIG
else:
raise ValueError(f"""Checkpoint type {ckpt_name} is not currently supported.""")
if not args.class_cond:
_a : List[str] = None
_a : str = con_pt_to_diffuser(args.unet_path, unet_config)
_a : str = UNetaDModel(**unet_config)
image_unet.load_state_dict(converted_unet_ckpt)
# Get scheduler config
if "cd" in ckpt_name or "test" in ckpt_name:
_a : Union[str, Any] = CD_SCHEDULER_CONFIG
elif "ct" in ckpt_name and "imagenet64" in ckpt_name:
_a : List[Any] = CT_IMAGENET_64_SCHEDULER_CONFIG
elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
_a : List[str] = CT_LSUN_256_SCHEDULER_CONFIG
else:
raise ValueError(f"""Checkpoint type {ckpt_name} is not currently supported.""")
_a : Optional[int] = CMStochasticIterativeScheduler(**scheduler_config)
_a : Optional[Any] = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler)
consistency_model.save_pretrained(args.dump_path)
| 705
|
'''simple docstring'''
import time
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers.generation import (
MaxLengthCriteria,
MaxNewTokensCriteria,
MaxTimeCriteria,
StoppingCriteriaList,
validate_stopping_criteria,
)
@require_torch
class __A (unittest.TestCase ):
def _snake_case ( self , UpperCamelCase_ ):
__UpperCAmelCase : List[str] = 3
__UpperCAmelCase : Tuple = 2_50
__UpperCAmelCase : str = ids_tensor((batch_size, length) , UpperCamelCase_ )
__UpperCAmelCase : Any = torch.ones((batch_size, length) , device=UpperCamelCase_ , dtype=torch.float ) / length
return input_ids, scores
def _snake_case ( self ):
__UpperCAmelCase , __UpperCAmelCase : Tuple = self._get_tensors(5 )
__UpperCAmelCase : Tuple = StoppingCriteriaList(
[
MaxLengthCriteria(max_length=10 ),
MaxTimeCriteria(max_time=0.1 ),
] )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase , __UpperCAmelCase : int = self._get_tensors(9 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = self._get_tensors(10 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
def _snake_case ( self ):
__UpperCAmelCase : int = MaxLengthCriteria(max_length=10 )
__UpperCAmelCase , __UpperCAmelCase : Tuple = self._get_tensors(5 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase , __UpperCAmelCase : Dict = self._get_tensors(9 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = self._get_tensors(10 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
def _snake_case ( self ):
__UpperCAmelCase : Optional[Any] = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 )
__UpperCAmelCase , __UpperCAmelCase : List[str] = self._get_tensors(5 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase , __UpperCAmelCase : Dict = self._get_tensors(9 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase , __UpperCAmelCase : Optional[Any] = self._get_tensors(10 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase : Union[str, Any] = StoppingCriteriaList([criteria] )
self.assertEqual(criteria_list.max_length , 10 )
def _snake_case ( self ):
__UpperCAmelCase , __UpperCAmelCase : Optional[Any] = self._get_tensors(5 )
__UpperCAmelCase : str = MaxTimeCriteria(max_time=0.1 )
self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
__UpperCAmelCase : str = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 )
self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) )
def _snake_case ( self ):
validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 )
with self.assertWarns(UpperCamelCase_ ):
validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 )
__UpperCAmelCase : Optional[int] = validate_stopping_criteria(StoppingCriteriaList() , 11 )
self.assertEqual(len(UpperCamelCase_ ) , 1 )
| 10
| 0
|
def lowerCAmelCase_ ( lowercase: str , lowercase: int ) -> list[str]:
'''simple docstring'''
return [sentence[i : i + ngram_size] for i in range(len(lowercase__ ) - ngram_size + 1 )]
if __name__ == "__main__":
from doctest import testmod
testmod()
| 271
|
'''simple docstring'''
from __future__ import annotations
from functools import lru_cache
from math import ceil
_a : Optional[Any] = 100
_a : Dict = set(range(3, NUM_PRIMES, 2))
primes.add(2)
_a : int
for prime in range(3, ceil(NUM_PRIMES**0.5), 2):
if prime not in primes:
continue
primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime)))
@lru_cache(maxsize=1_0_0 )
def _a (lowercase__ : int ) -> set[int]:
"""simple docstring"""
if number_to_partition < 0:
return set()
elif number_to_partition == 0:
return {1}
__snake_case = set()
__snake_case = 42
__snake_case = 42
for prime in primes:
if prime > number_to_partition:
continue
for sub in partition(number_to_partition - prime ):
ret.add(sub * prime )
return ret
def _a (lowercase__ : int = 5_0_0_0 ) -> int | None:
"""simple docstring"""
for number_to_partition in range(1 , lowercase__ ):
if len(partition(lowercase__ ) ) > number_unique_partitions:
return number_to_partition
return None
if __name__ == "__main__":
print(f'''{solution() = }''')
| 56
| 0
|
UpperCAmelCase_ = '''Input must be a string of 8 numbers plus letter'''
UpperCAmelCase_ = '''TRWAGMYFPDXBNJZSQVHLCKE'''
def UpperCAmelCase ( A__ ) -> bool:
if not isinstance(A__ , A__ ):
_snake_case : Union[str, Any] = f'''Expected string as input, found {type(A__ ).__name__}'''
raise TypeError(A__ )
_snake_case : Optional[Any] = spanish_id.replace("""-""" , """""" ).upper()
if len(A__ ) != 9:
raise ValueError(A__ )
try:
_snake_case : int = int(spanish_id_clean[0:8] )
_snake_case : Any = spanish_id_clean[8]
except ValueError as ex:
raise ValueError(A__ ) from ex
if letter.isdigit():
raise ValueError(A__ )
return letter == LOOKUP_LETTERS[number % 23]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 519
|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCAmelCase_ = {
'''configuration_blip_2''': [
'''BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''Blip2Config''',
'''Blip2QFormerConfig''',
'''Blip2VisionConfig''',
],
'''processing_blip_2''': ['''Blip2Processor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ = [
'''BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''Blip2Model''',
'''Blip2QFormerModel''',
'''Blip2PreTrainedModel''',
'''Blip2ForConditionalGeneration''',
'''Blip2VisionModel''',
]
if TYPE_CHECKING:
from .configuration_blip_a import (
BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlipaConfig,
BlipaQFormerConfig,
BlipaVisionConfig,
)
from .processing_blip_a import BlipaProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blip_a import (
BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST,
BlipaForConditionalGeneration,
BlipaModel,
BlipaPreTrainedModel,
BlipaQFormerModel,
BlipaVisionModel,
)
else:
import sys
UpperCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 519
| 1
|
import itertools
import random
import unittest
import numpy as np
from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available
from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin
lowerCAmelCase = random.Random()
if is_torch_available():
import torch
def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=1.0 , lowercase_=None , lowercase_=None ) -> Dict:
'''simple docstring'''
if rng is None:
__UpperCAmelCase : Optional[int] = global_rng
__UpperCAmelCase : Tuple = []
for batch_idx in range(shape[0] ):
values.append([] )
for _ in range(shape[1] ):
values[-1].append(rng.random() * scale )
return values
class lowerCamelCase ( unittest.TestCase ):
def __init__( self , lowercase__ , lowercase__=7 , lowercase__=4_0_0 , lowercase__=2_0_0_0 , lowercase__=1 , lowercase__=0.0 , lowercase__=1_6_0_0_0 , lowercase__=True , lowercase__=True , ):
__UpperCAmelCase : Any = parent
__UpperCAmelCase : Dict = batch_size
__UpperCAmelCase : Tuple = min_seq_length
__UpperCAmelCase : Any = max_seq_length
__UpperCAmelCase : Optional[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
__UpperCAmelCase : Optional[int] = feature_size
__UpperCAmelCase : Optional[int] = padding_value
__UpperCAmelCase : List[str] = sampling_rate
__UpperCAmelCase : List[Any] = return_attention_mask
__UpperCAmelCase : Any = do_normalize
def A( self):
return {
"feature_size": self.feature_size,
"padding_value": self.padding_value,
"sampling_rate": self.sampling_rate,
"return_attention_mask": self.return_attention_mask,
"do_normalize": self.do_normalize,
}
def A( self , lowercase__=False , lowercase__=False):
def _flatten(lowercase__):
return list(itertools.chain(*lowercase__))
if equal_length:
__UpperCAmelCase : List[Any] = floats_list((self.batch_size, self.max_seq_length))
else:
# make sure that inputs increase in size
__UpperCAmelCase : Any = [
_flatten(floats_list((x, self.feature_size)))
for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff)
]
if numpify:
__UpperCAmelCase : Optional[Any] = [np.asarray(lowercase__) for x in speech_inputs]
return speech_inputs
@require_torch
@require_torchaudio
class lowerCamelCase ( _UpperCamelCase , unittest.TestCase ):
_lowerCAmelCase : List[str] = ASTFeatureExtractor
def A( self):
__UpperCAmelCase : Any = ASTFeatureExtractionTester(self)
def A( self):
# Tests that all call wrap to encode_plus and batch_encode_plus
__UpperCAmelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
# create three inputs of length 800, 1000, and 1200
__UpperCAmelCase : List[Any] = [floats_list((1, x))[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0)]
__UpperCAmelCase : int = [np.asarray(lowercase__) for speech_input in speech_inputs]
# Test not batched input
__UpperCAmelCase : List[str] = feat_extract(speech_inputs[0] , return_tensors='''np''').input_values
__UpperCAmelCase : Dict = feat_extract(np_speech_inputs[0] , return_tensors='''np''').input_values
self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3))
# Test batched
__UpperCAmelCase : List[Any] = feat_extract(lowercase__ , padding=lowercase__ , return_tensors='''np''').input_values
__UpperCAmelCase : List[Any] = feat_extract(lowercase__ , padding=lowercase__ , return_tensors='''np''').input_values
for enc_seq_a, enc_seq_a in zip(lowercase__ , lowercase__):
self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3))
# Test 2-D numpy arrays are batched.
__UpperCAmelCase : Dict = [floats_list((1, x))[0] for x in (8_0_0, 8_0_0, 8_0_0)]
__UpperCAmelCase : Any = np.asarray(lowercase__)
__UpperCAmelCase : Union[str, Any] = feat_extract(lowercase__ , return_tensors='''np''').input_values
__UpperCAmelCase : Optional[Any] = feat_extract(lowercase__ , return_tensors='''np''').input_values
for enc_seq_a, enc_seq_a in zip(lowercase__ , lowercase__):
self.assertTrue(np.allclose(lowercase__ , lowercase__ , atol=1e-3))
@require_torch
def A( self):
import torch
__UpperCAmelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
__UpperCAmelCase : Tuple = np.random.rand(1_0_0).astype(np.floataa)
__UpperCAmelCase : Optional[Any] = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
__UpperCAmelCase : Dict = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''np''')
self.assertTrue(np_processed.input_values.dtype == np.floataa)
__UpperCAmelCase : Union[str, Any] = feature_extractor.pad([{'''input_values''': inputs}] , return_tensors='''pt''')
self.assertTrue(pt_processed.input_values.dtype == torch.floataa)
def A( self , lowercase__):
from datasets import load_dataset
__UpperCAmelCase : Dict = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''')
# automatic decoding with librispeech
__UpperCAmelCase : Any = ds.sort('''id''').select(range(lowercase__))[:num_samples]['''audio''']
return [x["array"] for x in speech_samples]
@require_torch
def A( self):
# fmt: off
__UpperCAmelCase : Optional[Any] = torch.tensor(
[-0.9_8_9_4, -1.2_7_7_6, -0.9_0_6_6, -1.2_7_7_6, -0.9_3_4_9, -1.2_6_0_9, -1.0_3_8_6, -1.2_7_7_6,
-1.1_5_6_1, -1.2_7_7_6, -1.2_0_5_2, -1.2_7_2_3, -1.2_1_9_0, -1.2_1_3_2, -1.2_7_7_6, -1.1_1_3_3,
-1.1_9_5_3, -1.1_3_4_3, -1.1_5_8_4, -1.2_2_0_3, -1.1_7_7_0, -1.2_4_7_4, -1.2_3_8_1, -1.1_9_3_6,
-0.9_2_7_0, -0.8_3_1_7, -0.8_0_4_9, -0.7_7_0_6, -0.7_5_6_5, -0.7_8_6_9])
# fmt: on
__UpperCAmelCase : Tuple = self._load_datasamples(1)
__UpperCAmelCase : int = ASTFeatureExtractor()
__UpperCAmelCase : Optional[Any] = feature_extractor(lowercase__ , return_tensors='''pt''').input_values
self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8))
self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , lowercase__ , atol=1e-4))
| 462
|
import tempfile
import unittest
import numpy as np
from diffusers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionPipeline,
PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class lowerCamelCase ( _UpperCamelCase , unittest.TestCase ):
_lowerCAmelCase : int = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''
def A( self , lowercase__=0):
__UpperCAmelCase : str = np.random.RandomState(lowercase__)
__UpperCAmelCase : Dict = {
'''prompt''': '''A painting of a squirrel eating a burger''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 7.5,
'''output_type''': '''numpy''',
}
return inputs
def A( self):
__UpperCAmelCase : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Tuple = self.get_dummy_inputs()
__UpperCAmelCase : int = pipe(**lowercase__).images
__UpperCAmelCase : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
__UpperCAmelCase : Optional[Any] = np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
def A( self):
__UpperCAmelCase : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
__UpperCAmelCase : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowercase__)
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs()
__UpperCAmelCase : int = pipe(**lowercase__).images
__UpperCAmelCase : Optional[int] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
__UpperCAmelCase : List[str] = np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
def A( self):
__UpperCAmelCase : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
__UpperCAmelCase : List[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config)
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs()
__UpperCAmelCase : Union[str, Any] = pipe(**lowercase__).images
__UpperCAmelCase : Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
__UpperCAmelCase : Union[str, Any] = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
def A( self):
__UpperCAmelCase : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
__UpperCAmelCase : Optional[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs()
__UpperCAmelCase : Optional[Any] = pipe(**lowercase__).images
__UpperCAmelCase : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
__UpperCAmelCase : int = np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
def A( self):
__UpperCAmelCase : List[str] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
__UpperCAmelCase : List[str] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Dict = self.get_dummy_inputs()
__UpperCAmelCase : Optional[int] = pipe(**lowercase__).images
__UpperCAmelCase : Optional[Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
__UpperCAmelCase : Dict = np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
def A( self):
__UpperCAmelCase : Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
__UpperCAmelCase : List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Optional[int] = self.get_dummy_inputs()
__UpperCAmelCase : Optional[Any] = pipe(**lowercase__).images
__UpperCAmelCase : List[str] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
__UpperCAmelCase : Dict = np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
def A( self):
__UpperCAmelCase : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Any = self.get_dummy_inputs()
__UpperCAmelCase : List[Any] = 3 * [inputs['''prompt''']]
# forward
__UpperCAmelCase : Dict = pipe(**lowercase__)
__UpperCAmelCase : List[Any] = output.images[0, -3:, -3:, -1]
__UpperCAmelCase : Union[str, Any] = self.get_dummy_inputs()
__UpperCAmelCase : Dict = 3 * [inputs.pop('''prompt''')]
__UpperCAmelCase : Tuple = pipe.tokenizer(
lowercase__ , padding='''max_length''' , max_length=pipe.tokenizer.model_max_length , truncation=lowercase__ , return_tensors='''np''' , )
__UpperCAmelCase : Optional[Any] = text_inputs['''input_ids''']
__UpperCAmelCase : Union[str, Any] = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0]
__UpperCAmelCase : Union[str, Any] = prompt_embeds
# forward
__UpperCAmelCase : Union[str, Any] = pipe(**lowercase__)
__UpperCAmelCase : Union[str, Any] = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1e-4
def A( self):
__UpperCAmelCase : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''')
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : int = self.get_dummy_inputs()
__UpperCAmelCase : Any = 3 * ['''this is a negative prompt''']
__UpperCAmelCase : Optional[int] = negative_prompt
__UpperCAmelCase : List[Any] = 3 * [inputs['''prompt''']]
# forward
__UpperCAmelCase : Any = pipe(**lowercase__)
__UpperCAmelCase : str = output.images[0, -3:, -3:, -1]
__UpperCAmelCase : Optional[int] = self.get_dummy_inputs()
__UpperCAmelCase : Any = 3 * [inputs.pop('''prompt''')]
__UpperCAmelCase : Optional[int] = []
for p in [prompt, negative_prompt]:
__UpperCAmelCase : str = pipe.tokenizer(
lowercase__ , padding='''max_length''' , max_length=pipe.tokenizer.model_max_length , truncation=lowercase__ , return_tensors='''np''' , )
__UpperCAmelCase : List[Any] = text_inputs['''input_ids''']
embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0])
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = embeds
# forward
__UpperCAmelCase : Union[str, Any] = pipe(**lowercase__)
__UpperCAmelCase : str = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1e-4
@nightly
@require_onnxruntime
@require_torch_gpu
class lowerCamelCase ( unittest.TestCase ):
@property
def A( self):
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def A( self):
__UpperCAmelCase : Optional[Any] = ort.SessionOptions()
__UpperCAmelCase : List[Any] = False
return options
def A( self):
# using the PNDM scheduler by default
__UpperCAmelCase : Tuple = OnnxStableDiffusionPipeline.from_pretrained(
'''CompVis/stable-diffusion-v1-4''' , revision='''onnx''' , safety_checker=lowercase__ , feature_extractor=lowercase__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : int = '''A painting of a squirrel eating a burger'''
np.random.seed(0)
__UpperCAmelCase : Dict = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=1_0 , output_type='''np''')
__UpperCAmelCase : Dict = output.images
__UpperCAmelCase : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__UpperCAmelCase : List[str] = np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
def A( self):
__UpperCAmelCase : Optional[Any] = DDIMScheduler.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''')
__UpperCAmelCase : Dict = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=lowercase__ , safety_checker=lowercase__ , feature_extractor=lowercase__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Any = '''open neural network exchange'''
__UpperCAmelCase : Any = np.random.RandomState(0)
__UpperCAmelCase : List[Any] = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=1_0 , generator=lowercase__ , output_type='''np''')
__UpperCAmelCase : List[str] = output.images
__UpperCAmelCase : Optional[int] = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__UpperCAmelCase : int = np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
def A( self):
__UpperCAmelCase : Union[str, Any] = LMSDiscreteScheduler.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , subfolder='''scheduler''' , revision='''onnx''')
__UpperCAmelCase : Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , scheduler=lowercase__ , safety_checker=lowercase__ , feature_extractor=lowercase__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Optional[Any] = '''open neural network exchange'''
__UpperCAmelCase : Optional[int] = np.random.RandomState(0)
__UpperCAmelCase : Dict = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=1_0 , generator=lowercase__ , output_type='''np''')
__UpperCAmelCase : Union[str, Any] = output.images
__UpperCAmelCase : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_1_2, 5_1_2, 3)
__UpperCAmelCase : Optional[int] = np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
def A( self):
__UpperCAmelCase : Tuple = 0
def test_callback_fn(lowercase__ , lowercase__ , lowercase__) -> None:
__UpperCAmelCase : Optional[Any] = True
nonlocal number_of_steps
number_of_steps += 1
if step == 0:
assert latents.shape == (1, 4, 6_4, 6_4)
__UpperCAmelCase : Union[str, Any] = latents[0, -3:, -3:, -1]
__UpperCAmelCase : Optional[Any] = np.array(
[-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7])
assert np.abs(latents_slice.flatten() - expected_slice).max() < 1e-3
elif step == 5:
assert latents.shape == (1, 4, 6_4, 6_4)
__UpperCAmelCase : Union[str, Any] = latents[0, -3:, -3:, -1]
__UpperCAmelCase : Dict = np.array(
[-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5])
assert np.abs(latents_slice.flatten() - expected_slice).max() < 1e-3
__UpperCAmelCase : str = False
__UpperCAmelCase : List[str] = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , safety_checker=lowercase__ , feature_extractor=lowercase__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=lowercase__)
__UpperCAmelCase : Union[str, Any] = '''Andromeda galaxy in a bottle'''
__UpperCAmelCase : List[Any] = np.random.RandomState(0)
pipe(
prompt=lowercase__ , num_inference_steps=5 , guidance_scale=7.5 , generator=lowercase__ , callback=lowercase__ , callback_steps=1 , )
assert test_callback_fn.has_been_called
assert number_of_steps == 6
def A( self):
__UpperCAmelCase : Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , revision='''onnx''' , safety_checker=lowercase__ , feature_extractor=lowercase__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
assert isinstance(lowercase__ , lowercase__)
assert pipe.safety_checker is None
__UpperCAmelCase : Union[str, Any] = pipe('''example prompt''' , num_inference_steps=2).images[0]
assert image is not None
# check that there's no error when saving a pipeline with one of the models being None
with tempfile.TemporaryDirectory() as tmpdirname:
pipe.save_pretrained(lowercase__)
__UpperCAmelCase : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(lowercase__)
# sanity check that the pipeline still works
assert pipe.safety_checker is None
__UpperCAmelCase : Optional[int] = pipe('''example prompt''' , num_inference_steps=2).images[0]
assert image is not None
| 462
| 1
|
'''simple docstring'''
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from transformers import (
VisualBertConfig,
VisualBertForMultipleChoice,
VisualBertForPreTraining,
VisualBertForQuestionAnswering,
VisualBertForVisualReasoning,
)
from transformers.utils import logging
logging.set_verbosity_info()
A: Optional[Any] = logging.get_logger(__name__)
A: List[str] = [
("bert.bert", "visual_bert"),
("bert.cls", "cls"),
("bert.classifier", "cls"),
("token_type_embeddings_visual", "visual_token_type_embeddings"),
("position_embeddings_visual", "visual_position_embeddings"),
("projection", "visual_projection"),
]
A: Dict = [
"nlvr2_coco_pre_trained.th",
"nlvr2_fine_tuned.th",
"nlvr2_pre_trained.th",
"vcr_coco_pre_train.th",
"vcr_fine_tune.th",
"vcr_pre_train.th",
"vqa_coco_pre_trained.th",
"vqa_fine_tuned.th",
"vqa_pre_trained.th",
]
def _UpperCAmelCase ( a : Dict ) -> Optional[int]:
"""simple docstring"""
lowercase_ : int = torch.load(a , map_location='cpu' )
return sd
def _UpperCAmelCase ( a : List[Any] , a : Tuple , a : Tuple=rename_keys_prefix ) -> List[str]:
"""simple docstring"""
lowercase_ : Dict = OrderedDict()
lowercase_ : Tuple = torch.arange(config.max_position_embeddings ).expand((1, -1) )
# detector_d = OrderedDict()
for key in d:
if "detector" in key:
# detector_d[key.replace('detector.','')] = d[key]
continue
lowercase_ : Optional[Any] = key
for name_pair in rename_keys_prefix:
lowercase_ : Optional[Any] = new_key.replace(name_pair[0] , name_pair[1] )
lowercase_ : int = d[key]
if key == "bert.cls.predictions.decoder.weight":
# Old bert code didn't have `decoder.bias`, but was added separately
lowercase_ : List[Any] = new_d['cls.predictions.bias']
return new_d
@torch.no_grad()
def _UpperCAmelCase ( a : Optional[Any] , a : Any ) -> Any:
"""simple docstring"""
assert (
checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS
), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}."
# Get Config
if "pre" in checkpoint_path:
lowercase_ : Any = 'pretraining'
if "vcr" in checkpoint_path:
lowercase_ : Dict = {'visual_embedding_dim': 5_1_2}
elif "vqa_advanced" in checkpoint_path:
lowercase_ : Tuple = {'visual_embedding_dim': 2_0_4_8}
elif "vqa" in checkpoint_path:
lowercase_ : List[Any] = {'visual_embedding_dim': 2_0_4_8}
elif "nlvr" in checkpoint_path:
lowercase_ : Optional[int] = {'visual_embedding_dim': 1_0_2_4}
else:
raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." )
else:
if "vcr" in checkpoint_path:
lowercase_ : Tuple = {'visual_embedding_dim': 5_1_2}
lowercase_ : List[Any] = 'multichoice'
elif "vqa_advanced" in checkpoint_path:
lowercase_ : Tuple = {'visual_embedding_dim': 2_0_4_8}
lowercase_ : str = 'vqa_advanced'
elif "vqa" in checkpoint_path:
lowercase_ : List[str] = {'visual_embedding_dim': 2_0_4_8, 'num_labels': 3_1_2_9}
lowercase_ : Optional[Any] = 'vqa'
elif "nlvr" in checkpoint_path:
lowercase_ : int = {
'visual_embedding_dim': 1_0_2_4,
'num_labels': 2,
}
lowercase_ : List[Any] = 'nlvr'
lowercase_ : Any = VisualBertConfig(**a )
# Load State Dict
lowercase_ : Any = load_state_dict(a )
lowercase_ : Optional[Any] = get_new_dict(a , a )
if model_type == "pretraining":
lowercase_ : Union[str, Any] = VisualBertForPreTraining(a )
elif model_type == "vqa":
lowercase_ : int = VisualBertForQuestionAnswering(a )
elif model_type == "nlvr":
lowercase_ : Union[str, Any] = VisualBertForVisualReasoning(a )
elif model_type == "multichoice":
lowercase_ : List[Any] = VisualBertForMultipleChoice(a )
model.load_state_dict(a )
# Save Checkpoints
Path(a ).mkdir(exist_ok=a )
model.save_pretrained(a )
if __name__ == "__main__":
A: List[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.")
parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.")
A: Union[str, Any] = parser.parse_args()
convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
| 7
|
'''simple docstring'''
def _UpperCAmelCase ( a : list ) -> list:
"""simple docstring"""
for i in range(len(a ) - 1 , 0 , -1 ):
lowercase_ : Any = False
for j in range(a , 0 , -1 ):
if unsorted[j] < unsorted[j - 1]:
lowercase_ , lowercase_ : Any = unsorted[j - 1], unsorted[j]
lowercase_ : int = True
for j in range(a ):
if unsorted[j] > unsorted[j + 1]:
lowercase_ , lowercase_ : Union[str, Any] = unsorted[j + 1], unsorted[j]
lowercase_ : Optional[Any] = True
if not swapped:
break
return unsorted
if __name__ == "__main__":
import doctest
doctest.testmod()
A: Union[str, Any] = input("Enter numbers separated by a comma:\n").strip()
A: Tuple = [int(item) for item in user_input.split(",")]
print(f"""{cocktail_shaker_sort(unsorted) = }""")
| 7
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.