code
stringlengths 82
53.2k
| code_codestyle
int64 0
721
| style_context
stringlengths 91
41.9k
| style_context_codestyle
int64 0
699
| label
int64 0
1
|
---|---|---|---|---|
"""simple docstring"""
from __future__ import annotations
from typing import Any
def __snake_case ( UpperCamelCase__ ) -> int:
"""simple docstring"""
if not postfix_notation:
return 0
A = {'+', '-', '*', '/'}
A = []
for token in postfix_notation:
if token in operations:
A , A = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b )
elif token == "-":
stack.append(a - b )
elif token == "*":
stack.append(a * b )
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1 )
else:
stack.append(a // b )
else:
stack.append(int(UpperCamelCase__ ) )
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| 690 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DonutImageProcessor
class lowerCamelCase__ ( unittest.TestCase ):
def __init__( self : List[str] , _lowercase : Optional[Any] , _lowercase : int=7 , _lowercase : List[str]=3 , _lowercase : Tuple=18 , _lowercase : Dict=30 , _lowercase : Any=400 , _lowercase : int=True , _lowercase : List[Any]=None , _lowercase : Tuple=True , _lowercase : List[Any]=False , _lowercase : str=True , _lowercase : List[str]=True , _lowercase : int=[0.5, 0.5, 0.5] , _lowercase : Optional[int]=[0.5, 0.5, 0.5] , ):
A = parent
A = batch_size
A = num_channels
A = image_size
A = min_resolution
A = max_resolution
A = do_resize
A = size if size is not None else {'height': 18, 'width': 20}
A = do_thumbnail
A = do_align_axis
A = do_pad
A = do_normalize
A = image_mean
A = image_std
def __a ( self : Any ):
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__ ( UpperCAmelCase_ , unittest.TestCase ):
lowerCAmelCase = DonutImageProcessor if is_vision_available() else None
def __a ( self : List[str] ):
A = DonutImageProcessingTester(self )
@property
def __a ( self : int ):
return self.image_processor_tester.prepare_image_processor_dict()
def __a ( self : Union[str, Any] ):
A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowercase , 'do_resize' ) )
self.assertTrue(hasattr(_lowercase , 'size' ) )
self.assertTrue(hasattr(_lowercase , 'do_thumbnail' ) )
self.assertTrue(hasattr(_lowercase , 'do_align_long_axis' ) )
self.assertTrue(hasattr(_lowercase , 'do_pad' ) )
self.assertTrue(hasattr(_lowercase , 'do_normalize' ) )
self.assertTrue(hasattr(_lowercase , 'image_mean' ) )
self.assertTrue(hasattr(_lowercase , 'image_std' ) )
def __a ( self : int ):
A = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'height': 18, 'width': 20} )
A = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {'height': 42, 'width': 42} )
# Previous config had dimensions in (width, height) order
A = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) )
self.assertEqual(image_processor.size , {'height': 84, 'width': 42} )
def __a ( self : Any ):
pass
@is_flaky()
def __a ( self : int ):
# Initialize image_processing
A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase )
for image in image_inputs:
self.assertIsInstance(_lowercase , Image.Image )
# Test not batched input
A = 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
A = image_processing(_lowercase , 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 : List[str] ):
# Initialize image_processing
A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase , numpify=_lowercase )
for image in image_inputs:
self.assertIsInstance(_lowercase , np.ndarray )
# Test not batched input
A = 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
A = image_processing(_lowercase , 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 : List[Any] ):
# Initialize image_processing
A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowercase , torchify=_lowercase )
for image in image_inputs:
self.assertIsInstance(_lowercase , torch.Tensor )
# Test not batched input
A = 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
A = image_processing(_lowercase , 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'],
) , )
| 690 | 1 |
'''simple docstring'''
import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def lowerCAmelCase (__A):
"""simple docstring"""
_a = fname.split(os.path.sep)[-1]
return re.search(r'''^(.*)_\d+\.jpg$''' , lowerCAmelCase__).groups()[0]
class __A ( A ):
'''simple docstring'''
def __init__(self , A , A=None , A=None ) -> Optional[Any]:
"""simple docstring"""
_a = file_names
_a = image_transform
_a = label_to_id
def __len__(self ) -> int:
"""simple docstring"""
return len(self.file_names )
def __getitem__(self , A ) -> Tuple:
"""simple docstring"""
_a = self.file_names[idx]
_a = PIL.Image.open(_UpperCAmelCase )
_a = raw_image.convert('''RGB''' )
if self.image_transform is not None:
_a = self.image_transform(_UpperCAmelCase )
_a = extract_label(_UpperCAmelCase )
if self.label_to_id is not None:
_a = self.label_to_id[label]
return {"image": image, "label": label}
def lowerCAmelCase (__A , __A):
"""simple docstring"""
if args.with_tracking:
_a = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir)
else:
_a = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
_a = config['''lr''']
_a = int(config['''num_epochs'''])
_a = int(config['''seed'''])
_a = int(config['''batch_size'''])
_a = config['''image_size''']
if not isinstance(lowerCAmelCase__ , (list, tuple)):
_a = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps , '''isdigit'''):
if args.checkpointing_steps == "epoch":
_a = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
_a = int(args.checkpointing_steps)
else:
raise ValueError(
F'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''')
else:
_a = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
_a = os.path.split(lowerCAmelCase__)[-1].split('''.''')[0]
accelerator.init_trackers(lowerCAmelCase__ , lowerCAmelCase__)
# Grab all the image filenames
_a = [os.path.join(args.data_dir , lowerCAmelCase__) for fname in os.listdir(args.data_dir) if fname.endswith('''.jpg''')]
# Build the label correspondences
_a = [extract_label(lowerCAmelCase__) for fname in file_names]
_a = list(set(lowerCAmelCase__))
id_to_label.sort()
_a = {lbl: i for i, lbl in enumerate(lowerCAmelCase__)}
# Set the seed before splitting the data.
np.random.seed(lowerCAmelCase__)
torch.manual_seed(lowerCAmelCase__)
torch.cuda.manual_seed_all(lowerCAmelCase__)
# Split our filenames between train and validation
_a = np.random.permutation(len(lowerCAmelCase__))
_a = int(0.8 * len(lowerCAmelCase__))
_a = random_perm[:cut]
_a = random_perm[cut:]
# For training we use a simple RandomResizedCrop
_a = Compose([RandomResizedCrop(lowerCAmelCase__ , scale=(0.5, 1.0)), ToTensor()])
_a = PetsDataset(
[file_names[i] for i in train_split] , image_transform=lowerCAmelCase__ , label_to_id=lowerCAmelCase__)
# For evaluation, we use a deterministic Resize
_a = Compose([Resize(lowerCAmelCase__), ToTensor()])
_a = PetsDataset([file_names[i] for i in eval_split] , image_transform=lowerCAmelCase__ , label_to_id=lowerCAmelCase__)
# Instantiate dataloaders.
_a = DataLoader(lowerCAmelCase__ , shuffle=lowerCAmelCase__ , batch_size=lowerCAmelCase__ , num_workers=4)
_a = DataLoader(lowerCAmelCase__ , shuffle=lowerCAmelCase__ , batch_size=lowerCAmelCase__ , num_workers=4)
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
_a = create_model('''resnet50d''' , pretrained=lowerCAmelCase__ , num_classes=len(lowerCAmelCase__))
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
_a = model.to(accelerator.device)
# Freezing the base model
for param in model.parameters():
_a = False
for param in model.get_classifier().parameters():
_a = True
# We normalize the batches of images to be a bit faster.
_a = torch.tensor(model.default_cfg['''mean'''])[None, :, None, None].to(accelerator.device)
_a = torch.tensor(model.default_cfg['''std'''])[None, :, None, None].to(accelerator.device)
# Instantiate optimizer
_a = torch.optim.Adam(params=model.parameters() , lr=lr / 25)
# Instantiate learning rate scheduler
_a = OneCycleLR(optimizer=lowerCAmelCase__ , max_lr=lowerCAmelCase__ , epochs=lowerCAmelCase__ , steps_per_epoch=len(lowerCAmelCase__))
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
_a , _a , _a , _a , _a = accelerator.prepare(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__)
# We need to keep track of how many total steps we have iterated over
_a = 0
# We also need to keep track of the starting epoch so files are named properly
_a = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(F'''Resumed from checkpoint: {args.resume_from_checkpoint}''')
accelerator.load_state(args.resume_from_checkpoint)
_a = os.path.basename(args.resume_from_checkpoint)
else:
# Get the most recent checkpoint
_a = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
dirs.sort(key=os.path.getctime)
_a = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
_a = os.path.splitext(lowerCAmelCase__)[0]
if "epoch" in training_difference:
_a = int(training_difference.replace('''epoch_''' , '''''')) + 1
_a = None
else:
_a = int(training_difference.replace('''step_''' , ''''''))
_a = resume_step // len(lowerCAmelCase__)
resume_step -= starting_epoch * len(lowerCAmelCase__)
# Now we train the model
for epoch in range(lowerCAmelCase__ , lowerCAmelCase__):
model.train()
if args.with_tracking:
_a = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
_a = accelerator.skip_first_batches(lowerCAmelCase__ , lowerCAmelCase__)
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
_a = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
_a = {k: v.to(accelerator.device) for k, v in batch.items()}
_a = (batch['''image'''] - mean) / std
_a = model(lowerCAmelCase__)
_a = torch.nn.functional.cross_entropy(lowerCAmelCase__ , batch['''label'''])
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(lowerCAmelCase__)
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(lowerCAmelCase__ , lowerCAmelCase__):
_a = F'''step_{overall_step}'''
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
_a = os.path.join(args.output_dir , lowerCAmelCase__)
accelerator.save_state(lowerCAmelCase__)
model.eval()
_a = 0
_a = 0
for step, batch in enumerate(lowerCAmelCase__):
# We could avoid this line since we set the accelerator with `device_placement=True`.
_a = {k: v.to(accelerator.device) for k, v in batch.items()}
_a = (batch['''image'''] - mean) / std
with torch.no_grad():
_a = model(lowerCAmelCase__)
_a = outputs.argmax(dim=-1)
_a , _a = accelerator.gather_for_metrics((predictions, batch['''label''']))
_a = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
_a = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}: {100 * eval_metric:.2f}''')
if args.with_tracking:
accelerator.log(
{
'''accuracy''': 100 * eval_metric,
'''train_loss''': total_loss.item() / len(lowerCAmelCase__),
'''epoch''': epoch,
} , step=lowerCAmelCase__ , )
if checkpointing_steps == "epoch":
_a = F'''epoch_{epoch}'''
if args.output_dir is not None:
_a = os.path.join(args.output_dir , lowerCAmelCase__)
accelerator.save_state(lowerCAmelCase__)
if args.with_tracking:
accelerator.end_training()
def lowerCAmelCase ():
"""simple docstring"""
_a = argparse.ArgumentParser(description='''Simple example of training script.''')
parser.add_argument('''--data_dir''' , required=lowerCAmelCase__ , help='''The data folder on disk.''')
parser.add_argument('''--fp16''' , action='''store_true''' , help='''If passed, will use FP16 training.''')
parser.add_argument(
'''--mixed_precision''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''')
parser.add_argument(
'''--checkpointing_steps''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.''' , )
parser.add_argument(
'''--output_dir''' , type=lowerCAmelCase__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , )
parser.add_argument(
'''--resume_from_checkpoint''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''If the training should continue from a checkpoint folder.''' , )
parser.add_argument(
'''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , )
parser.add_argument(
'''--project_dir''' , type=lowerCAmelCase__ , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , )
_a = parser.parse_args()
_a = {'''lr''': 3e-2, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 64, '''image_size''': 224}
training_function(lowerCAmelCase__ , lowerCAmelCase__)
if __name__ == "__main__":
main()
| 714 |
'''simple docstring'''
# This is the module that test_patching.py uses to test patch_submodule()
import os # noqa: this is just for tests
import os as renamed_os # noqa: this is just for tests
from os import path # noqa: this is just for tests
from os import path as renamed_path # noqa: this is just for tests
from os.path import join # noqa: this is just for tests
from os.path import join as renamed_join # noqa: this is just for tests
lowercase_ = open # noqa: we just need to have a builtin inside this module to test it properly
| 352 | 0 |
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
__UpperCamelCase: Tuple = logging.get_logger(__name__)
def SCREAMING_SNAKE_CASE__ ( _lowercase : str , _lowercase : Optional[Any]=False ) -> List[Any]:
'''simple docstring'''
lowercase__ : Optional[int] = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""deit.encoder.layer.{i}.layernorm_before.weight""") )
rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""deit.encoder.layer.{i}.layernorm_before.bias""") )
rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""deit.encoder.layer.{i}.attention.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""deit.encoder.layer.{i}.attention.output.dense.bias""") )
rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""deit.encoder.layer.{i}.layernorm_after.weight""") )
rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""deit.encoder.layer.{i}.layernorm_after.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""deit.encoder.layer.{i}.intermediate.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""deit.encoder.layer.{i}.intermediate.dense.bias""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""deit.encoder.layer.{i}.output.dense.weight""") )
rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""deit.encoder.layer.{i}.output.dense.bias""") )
# projection layer + position embeddings
rename_keys.extend(
[
('cls_token', 'deit.embeddings.cls_token'),
('dist_token', 'deit.embeddings.distillation_token'),
('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'),
('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'),
('pos_embed', 'deit.embeddings.position_embeddings'),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
('norm.weight', 'layernorm.weight'),
('norm.bias', 'layernorm.bias'),
('pre_logits.fc.weight', 'pooler.dense.weight'),
('pre_logits.fc.bias', 'pooler.dense.bias'),
] )
# if just the base model, we should remove "deit" from all keys that start with "deit"
lowercase__ : Any = [(pair[0], pair[1][4:]) if pair[1].startswith('deit' ) else pair for pair in rename_keys]
else:
# layernorm + classification heads
rename_keys.extend(
[
('norm.weight', 'deit.layernorm.weight'),
('norm.bias', 'deit.layernorm.bias'),
('head.weight', 'cls_classifier.weight'),
('head.bias', 'cls_classifier.bias'),
('head_dist.weight', 'distillation_classifier.weight'),
('head_dist.bias', 'distillation_classifier.bias'),
] )
return rename_keys
def SCREAMING_SNAKE_CASE__ ( _lowercase : List[Any] , _lowercase : int , _lowercase : Any=False ) -> List[Any]:
'''simple docstring'''
for i in range(config.num_hidden_layers ):
if base_model:
lowercase__ : List[Any] = ""
else:
lowercase__ : Optional[int] = "deit."
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
lowercase__ : int = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" )
lowercase__ : List[Any] = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
lowercase__ : Tuple = in_proj_weight[
: config.hidden_size, :
]
lowercase__ : Dict = in_proj_bias[: config.hidden_size]
lowercase__ : Optional[int] = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
lowercase__ : List[Any] = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
lowercase__ : Union[str, Any] = in_proj_weight[
-config.hidden_size :, :
]
lowercase__ : List[Any] = in_proj_bias[-config.hidden_size :]
def SCREAMING_SNAKE_CASE__ ( _lowercase : Optional[Any] , _lowercase : Any , _lowercase : int ) -> List[str]:
'''simple docstring'''
lowercase__ : int = dct.pop(__UpperCamelCase )
lowercase__ : Dict = val
def SCREAMING_SNAKE_CASE__ ( ) -> Any:
'''simple docstring'''
lowercase__ : List[Any] = "http://images.cocodataset.org/val2017/000000039769.jpg"
lowercase__ : Optional[int] = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw )
return im
@torch.no_grad()
def SCREAMING_SNAKE_CASE__ ( _lowercase : List[Any] , _lowercase : int ) -> Union[str, Any]:
'''simple docstring'''
lowercase__ : List[Any] = DeiTConfig()
# all deit models have fine-tuned heads
lowercase__ : Optional[int] = False
# dataset (fine-tuned on ImageNet 2012), patch_size and image_size
lowercase__ : Optional[int] = 1_000
lowercase__ : Union[str, Any] = "huggingface/label-files"
lowercase__ : Tuple = "imagenet-1k-id2label.json"
lowercase__ : List[Any] = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type='dataset' ) , 'r' ) )
lowercase__ : Any = {int(__UpperCamelCase ): v for k, v in idalabel.items()}
lowercase__ : List[str] = idalabel
lowercase__ : List[Any] = {v: k for k, v in idalabel.items()}
lowercase__ : Dict = int(deit_name[-6:-4] )
lowercase__ : str = int(deit_name[-3:] )
# size of the architecture
if deit_name[9:].startswith('tiny' ):
lowercase__ : Optional[int] = 192
lowercase__ : Dict = 768
lowercase__ : List[Any] = 12
lowercase__ : List[str] = 3
elif deit_name[9:].startswith('small' ):
lowercase__ : int = 384
lowercase__ : Any = 1_536
lowercase__ : Any = 12
lowercase__ : List[Any] = 6
if deit_name[9:].startswith('base' ):
pass
elif deit_name[4:].startswith('large' ):
lowercase__ : Optional[Any] = 1_024
lowercase__ : str = 4_096
lowercase__ : Tuple = 24
lowercase__ : Optional[Any] = 16
# load original model from timm
lowercase__ : List[Any] = timm.create_model(__UpperCamelCase , pretrained=__UpperCamelCase )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
lowercase__ : Union[str, Any] = timm_model.state_dict()
lowercase__ : List[Any] = create_rename_keys(__UpperCamelCase , __UpperCamelCase )
for src, dest in rename_keys:
rename_key(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
read_in_q_k_v(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# load HuggingFace model
lowercase__ : Optional[Any] = DeiTForImageClassificationWithTeacher(__UpperCamelCase ).eval()
model.load_state_dict(__UpperCamelCase )
# Check outputs on an image, prepared by DeiTImageProcessor
lowercase__ : Any = int(
(256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103
lowercase__ : Optional[int] = DeiTImageProcessor(size=__UpperCamelCase , crop_size=config.image_size )
lowercase__ : List[Any] = image_processor(images=prepare_img() , return_tensors='pt' )
lowercase__ : Dict = encoding["pixel_values"]
lowercase__ : Optional[Any] = model(__UpperCamelCase )
lowercase__ : str = timm_model(__UpperCamelCase )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__UpperCamelCase , outputs.logits , atol=1e-3 )
Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase )
print(f"""Saving model {deit_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 __name__ == "__main__":
__UpperCamelCase: Optional[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--deit_name""",
default="""vit_deit_base_distilled_patch16_224""",
type=str,
help="""Name of the DeiT timm model you'd like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
__UpperCamelCase: Optional[int] = parser.parse_args()
convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
| 266 |
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import evaluate
import numpy as np
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")
require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/text-classification/requirements.txt""")
lowerCamelCase = logging.getLogger(__name__)
@dataclass
class _a :
'''simple docstring'''
A :Optional[int] = 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."
)
} , )
A :bool = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
A :bool = field(
default=SCREAMING_SNAKE_CASE , metadata={
"help": (
"Whether to pad all samples to `max_seq_length`. "
"If False, will pad the samples dynamically when batching to the maximum length in the batch."
)
} , )
A :Optional[int] = field(
default=SCREAMING_SNAKE_CASE , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of training examples to this "
"value if set."
)
} , )
A :Optional[int] = field(
default=SCREAMING_SNAKE_CASE , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of evaluation examples to this "
"value if set."
)
} , )
A :Optional[int] = field(
default=SCREAMING_SNAKE_CASE , metadata={
"help": (
"For debugging purposes or quicker training, truncate the number of prediction examples to this "
"value if set."
)
} , )
@dataclass
class _a :
'''simple docstring'''
A :str = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
A :str = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} )
A :Optional[str] = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Train language if it is different from the evaluation language."} )
A :Optional[str] = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Pretrained config name or path if not the same as model_name"} )
A :Optional[str] = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
A :Optional[str] = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , )
A :Optional[bool] = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , )
A :bool = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , )
A :str = field(
default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , )
A :bool = field(
default=SCREAMING_SNAKE_CASE , metadata={
"help": (
"Will use the token generated when running `huggingface-cli login` (necessary to use this script "
"with private models)."
)
} , )
A :bool = field(
default=SCREAMING_SNAKE_CASE , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , )
def SCREAMING_SNAKE_CASE( ) -> int:
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
a__ : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
a__ , a__ , a__ : 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_xnli" , __UpperCamelCase )
# 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()
a__ : int = training_args.get_process_log_level()
logger.setLevel(__UpperCamelCase )
datasets.utils.logging.set_verbosity(__UpperCamelCase )
transformers.utils.logging.set_verbosity(__UpperCamelCase )
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.
a__ : Union[str, Any] = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
a__ : Dict = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F'Output directory ({training_args.output_dir}) already exists and is not empty. '
"Use --overwrite_output_dir to overcome." )
elif last_checkpoint is not None:
logger.info(
F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
"the `--output_dir` or add `--overwrite_output_dir` to train from scratch." )
# Set seed before initializing model.
set_seed(training_args.seed )
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
# download the dataset.
# Downloading and loading xnli dataset from the hub.
if training_args.do_train:
if model_args.train_language is None:
a__ : Any = load_dataset(
"xnli" , model_args.language , split="train" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
else:
a__ : List[str] = load_dataset(
"xnli" , model_args.train_language , split="train" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
a__ : List[Any] = train_dataset.features["label"].names
if training_args.do_eval:
a__ : Tuple = load_dataset(
"xnli" , model_args.language , split="validation" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
a__ : int = eval_dataset.features["label"].names
if training_args.do_predict:
a__ : Dict = load_dataset(
"xnli" , model_args.language , split="test" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
a__ : Optional[Any] = predict_dataset.features["label"].names
# Labels
a__ : List[Any] = len(__UpperCamelCase )
# Load pretrained model and tokenizer
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
a__ : List[Any] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__UpperCamelCase , idalabel={str(__UpperCamelCase ): label for i, label in enumerate(__UpperCamelCase )} , labelaid={label: i for i, label in enumerate(__UpperCamelCase )} , finetuning_task="xnli" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
a__ : Union[str, Any] = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
a__ : Optional[int] = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=__UpperCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , )
# Preprocessing the datasets
# Padding strategy
if data_args.pad_to_max_length:
a__ : Dict = "max_length"
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
a__ : Optional[Any] = False
def preprocess_function(__UpperCamelCase ):
# Tokenize the texts
return tokenizer(
examples["premise"] , examples["hypothesis"] , padding=__UpperCamelCase , max_length=data_args.max_seq_length , truncation=__UpperCamelCase , )
if training_args.do_train:
if data_args.max_train_samples is not None:
a__ : int = min(len(__UpperCamelCase ) , data_args.max_train_samples )
a__ : Tuple = train_dataset.select(range(__UpperCamelCase ) )
with training_args.main_process_first(desc="train dataset map pre-processing" ):
a__ : Optional[int] = train_dataset.map(
__UpperCamelCase , batched=__UpperCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on train dataset" , )
# Log a few random samples from the training set:
for index in random.sample(range(len(__UpperCamelCase ) ) , 3 ):
logger.info(F'Sample {index} of the training set: {train_dataset[index]}.' )
if training_args.do_eval:
if data_args.max_eval_samples is not None:
a__ : Optional[int] = min(len(__UpperCamelCase ) , data_args.max_eval_samples )
a__ : Optional[Any] = eval_dataset.select(range(__UpperCamelCase ) )
with training_args.main_process_first(desc="validation dataset map pre-processing" ):
a__ : List[Any] = eval_dataset.map(
__UpperCamelCase , batched=__UpperCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on validation dataset" , )
if training_args.do_predict:
if data_args.max_predict_samples is not None:
a__ : int = min(len(__UpperCamelCase ) , data_args.max_predict_samples )
a__ : List[str] = predict_dataset.select(range(__UpperCamelCase ) )
with training_args.main_process_first(desc="prediction dataset map pre-processing" ):
a__ : Union[str, Any] = predict_dataset.map(
__UpperCamelCase , batched=__UpperCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc="Running tokenizer on prediction dataset" , )
# Get the metric function
a__ : List[Any] = evaluate.load("xnli" )
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(__UpperCamelCase ):
a__ : Dict = p.predictions[0] if isinstance(p.predictions , __UpperCamelCase ) else p.predictions
a__ : Any = np.argmax(__UpperCamelCase , axis=1 )
return metric.compute(predictions=__UpperCamelCase , references=p.label_ids )
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
a__ : List[Any] = default_data_collator
elif training_args.fpaa:
a__ : List[Any] = DataCollatorWithPadding(__UpperCamelCase , pad_to_multiple_of=8 )
else:
a__ : Tuple = None
# Initialize our Trainer
a__ : List[str] = Trainer(
model=__UpperCamelCase , args=__UpperCamelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__UpperCamelCase , tokenizer=__UpperCamelCase , data_collator=__UpperCamelCase , )
# Training
if training_args.do_train:
a__ : str = None
if training_args.resume_from_checkpoint is not None:
a__ : int = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
a__ : Optional[int] = last_checkpoint
a__ : Any = trainer.train(resume_from_checkpoint=__UpperCamelCase )
a__ : Tuple = train_result.metrics
a__ : Union[str, Any] = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(__UpperCamelCase )
)
a__ : Optional[int] = min(__UpperCamelCase , len(__UpperCamelCase ) )
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics("train" , __UpperCamelCase )
trainer.save_metrics("train" , __UpperCamelCase )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***" )
a__ : Optional[int] = trainer.evaluate(eval_dataset=__UpperCamelCase )
a__ : Tuple = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__UpperCamelCase )
a__ : List[Any] = min(__UpperCamelCase , len(__UpperCamelCase ) )
trainer.log_metrics("eval" , __UpperCamelCase )
trainer.save_metrics("eval" , __UpperCamelCase )
# Prediction
if training_args.do_predict:
logger.info("*** Predict ***" )
a__ , a__ , a__ : int = trainer.predict(__UpperCamelCase , metric_key_prefix="predict" )
a__ : int = (
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__UpperCamelCase )
)
a__ : Union[str, Any] = min(__UpperCamelCase , len(__UpperCamelCase ) )
trainer.log_metrics("predict" , __UpperCamelCase )
trainer.save_metrics("predict" , __UpperCamelCase )
a__ : Dict = np.argmax(__UpperCamelCase , axis=1 )
a__ : str = os.path.join(training_args.output_dir , "predictions.txt" )
if trainer.is_world_process_zero():
with open(__UpperCamelCase , "w" ) as writer:
writer.write("index\tprediction\n" )
for index, item in enumerate(__UpperCamelCase ):
a__ : int = label_list[item]
writer.write(F'{index}\t{item}\n' )
if __name__ == "__main__":
main()
| 191 | 0 |
def snake_case_ ( __lowercase ):
if num <= 0:
raise ValueError('''Input must be a positive integer''' )
UpperCAmelCase_ : Any = [True] * (num + 1)
UpperCAmelCase_ : Any = 2
while p * p <= num:
if primes[p]:
for i in range(p * p , num + 1 , __lowercase ):
UpperCAmelCase_ : Optional[Any] = False
p += 1
return [prime for prime in range(2 , num + 1 ) if primes[prime]]
if __name__ == "__main__":
import doctest
doctest.testmod()
__UpperCamelCase : Optional[Any] = int(input('Enter a positive integer: ').strip())
print(prime_sieve_eratosthenes(user_num)) | 701 |
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments
def snake_case_ ( ):
UpperCAmelCase_ : str = HfArgumentParser(__lowercase )
UpperCAmelCase_ : Optional[Any] = parser.parse_args_into_dataclasses()[0]
UpperCAmelCase_ : Optional[int] = TensorFlowBenchmark(args=__lowercase )
try:
UpperCAmelCase_ : List[Any] = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
UpperCAmelCase_ : List[Any] = '''Arg --no_{0} is no longer used, please use --no-{0} instead.'''
UpperCAmelCase_ : List[str] = ''' '''.join(str(__lowercase ).split(''' ''' )[:-1] )
UpperCAmelCase_ : Optional[int] = ''''''
UpperCAmelCase_ : Dict = eval(str(__lowercase ).split(''' ''' )[-1] )
UpperCAmelCase_ : int = []
for arg in depreciated_args:
# arg[2:] removes '--'
if arg[2:] in TensorFlowBenchmark.deprecated_args:
# arg[5:] removes '--no_'
full_error_msg += arg_error_msg.format(arg[5:] )
else:
wrong_args.append(__lowercase )
if len(__lowercase ) > 0:
UpperCAmelCase_ : Tuple = full_error_msg + begin_error_msg + str(__lowercase )
raise ValueError(__lowercase )
benchmark.run()
if __name__ == "__main__":
main() | 641 | 0 |
'''simple docstring'''
import argparse
import json
from collections import OrderedDict
import torch
from huggingface_hub import cached_download, hf_hub_url
from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification
def __A ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Tuple = []
embed.append(
(
f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight',
f'stage{idx}.patch_embed.proj.weight',
) )
embed.append(
(
f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias',
f'stage{idx}.patch_embed.proj.bias',
) )
embed.append(
(
f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight',
f'stage{idx}.patch_embed.norm.weight',
) )
embed.append(
(
f'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias',
f'stage{idx}.patch_embed.norm.bias',
) )
return embed
def __A ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Any = []
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked',
f'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight',
f'stage{idx}.blocks.{cnt}.attn.proj_q.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias',
f'stage{idx}.blocks.{cnt}.attn.proj_q.bias',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight',
f'stage{idx}.blocks.{cnt}.attn.proj_k.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias',
f'stage{idx}.blocks.{cnt}.attn.proj_k.bias',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight',
f'stage{idx}.blocks.{cnt}.attn.proj_v.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias',
f'stage{idx}.blocks.{cnt}.attn.proj_v.bias',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight',
f'stage{idx}.blocks.{cnt}.attn.proj.weight',
) )
attention_weights.append(
(
f'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias',
f'stage{idx}.blocks.{cnt}.attn.proj.bias',
) )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight', f'stage{idx}.blocks.{cnt}.mlp.fc1.weight') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias', f'stage{idx}.blocks.{cnt}.mlp.fc1.bias') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight', f'stage{idx}.blocks.{cnt}.mlp.fc2.weight') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias', f'stage{idx}.blocks.{cnt}.mlp.fc2.bias') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight', f'stage{idx}.blocks.{cnt}.norm1.weight') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias', f'stage{idx}.blocks.{cnt}.norm1.bias') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight', f'stage{idx}.blocks.{cnt}.norm2.weight') )
attention_weights.append(
(f'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias', f'stage{idx}.blocks.{cnt}.norm2.bias') )
return attention_weights
def __A ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Optional[int] = []
token.append((f'cvt.encoder.stages.{idx}.cls_token', "stage2.cls_token") )
return token
def __A ( ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Union[str, Any] = []
head.append(("layernorm.weight", "norm.weight") )
head.append(("layernorm.bias", "norm.bias") )
head.append(("classifier.weight", "head.weight") )
head.append(("classifier.bias", "head.bias") )
return head
def __A ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : Dict = "imagenet-1k-id2label.json"
__SCREAMING_SNAKE_CASE : Dict = 1_0_0_0
__SCREAMING_SNAKE_CASE : List[Any] = "huggingface/label-files"
__SCREAMING_SNAKE_CASE : Optional[Any] = num_labels
__SCREAMING_SNAKE_CASE : int = json.load(open(cached_download(hf_hub_url(__lowerCamelCase , __lowerCamelCase , repo_type="dataset" ) ) , "r" ) )
__SCREAMING_SNAKE_CASE : Dict = {int(__lowerCamelCase ): v for k, v in idalabel.items()}
__SCREAMING_SNAKE_CASE : List[Any] = idalabel
__SCREAMING_SNAKE_CASE : int = {v: k for k, v in idalabel.items()}
__SCREAMING_SNAKE_CASE : Union[str, Any] = CvtConfig(num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase )
# For depth size 13 (13 = 1+2+10)
if cvt_model.rsplit("/" , 1 )[-1][4:6] == "13":
__SCREAMING_SNAKE_CASE : Any = [1, 2, 1_0]
# For depth size 21 (21 = 1+4+16)
elif cvt_model.rsplit("/" , 1 )[-1][4:6] == "21":
__SCREAMING_SNAKE_CASE : str = [1, 4, 1_6]
# For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20)
else:
__SCREAMING_SNAKE_CASE : Optional[int] = [2, 2, 2_0]
__SCREAMING_SNAKE_CASE : str = [3, 1_2, 1_6]
__SCREAMING_SNAKE_CASE : List[str] = [1_9_2, 7_6_8, 1_0_2_4]
__SCREAMING_SNAKE_CASE : Dict = CvtForImageClassification(__lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" )
__SCREAMING_SNAKE_CASE : int = image_size
__SCREAMING_SNAKE_CASE : List[Any] = torch.load(__lowerCamelCase , map_location=torch.device("cpu" ) )
__SCREAMING_SNAKE_CASE : Dict = OrderedDict()
__SCREAMING_SNAKE_CASE : Any = []
for idx in range(len(config.depth ) ):
if config.cls_token[idx]:
__SCREAMING_SNAKE_CASE : List[Any] = list_of_state_dict + cls_token(__lowerCamelCase )
__SCREAMING_SNAKE_CASE : str = list_of_state_dict + embeddings(__lowerCamelCase )
for cnt in range(config.depth[idx] ):
__SCREAMING_SNAKE_CASE : Dict = list_of_state_dict + attention(__lowerCamelCase , __lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = list_of_state_dict + final()
for gg in list_of_state_dict:
print(__lowerCamelCase )
for i in range(len(__lowerCamelCase ) ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = original_weights[list_of_state_dict[i][1]]
model.load_state_dict(__lowerCamelCase )
model.save_pretrained(__lowerCamelCase )
image_processor.save_pretrained(__lowerCamelCase )
# Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al
if __name__ == "__main__":
lowercase = argparse.ArgumentParser()
parser.add_argument(
'''--cvt_model''',
default='''cvt-w24''',
type=str,
help='''Name of the cvt model you\'d like to convert.''',
)
parser.add_argument(
'''--image_size''',
default=384,
type=int,
help='''Input Image Size''',
)
parser.add_argument(
'''--cvt_file_name''',
default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''',
type=str,
help='''Input Image Size''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.'''
)
lowercase = parser.parse_args()
convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
| 211 |
'''simple docstring'''
from typing import List, Optional, Union
import numpy as np
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
_lowercase = logging.get_logger(__name__)
class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ):
'''simple docstring'''
_lowercase : List[str] = ['''input_values''', '''padding_mask''']
def __init__( self , _lowercase = 1 , _lowercase = 24_000 , _lowercase = 0.0 , _lowercase = None , _lowercase = None , **_lowercase , ):
"""simple docstring"""
super().__init__(feature_size=_lowercase , sampling_rate=_lowercase , padding_value=_lowercase , **_lowercase )
_lowerCAmelCase = chunk_length_s
_lowerCAmelCase = overlap
@property
def _lowercase ( self ):
"""simple docstring"""
if self.chunk_length_s is None:
return None
else:
return int(self.chunk_length_s * self.sampling_rate )
@property
def _lowercase ( self ):
"""simple docstring"""
if self.chunk_length_s is None or self.overlap is None:
return None
else:
return max(1 , int((1.0 - self.overlap) * self.chunk_length ) )
def __call__( self , _lowercase , _lowercase = None , _lowercase = False , _lowercase = None , _lowercase = None , _lowercase = None , ):
"""simple docstring"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
F' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'
F' {self.sampling_rate} and not {sampling_rate}.' )
else:
logger.warning(
"""It is strongly recommended to pass the `sampling_rate` argument to this function. """
"""Failing to do so can result in silent errors that might be hard to debug.""" )
if padding and truncation:
raise ValueError("""Both padding and truncation were set. Make sure you only set one.""" )
elif padding is None:
# by default let's pad the inputs
_lowerCAmelCase = True
_lowerCAmelCase = bool(
isinstance(_lowercase , (list, tuple) ) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list) )) )
if is_batched:
_lowerCAmelCase = [np.asarray(_lowercase , dtype=np.floataa ).T for audio in raw_audio]
elif not is_batched and not isinstance(_lowercase , np.ndarray ):
_lowerCAmelCase = np.asarray(_lowercase , dtype=np.floataa )
elif isinstance(_lowercase , np.ndarray ) and raw_audio.dtype is np.dtype(np.floataa ):
_lowerCAmelCase = raw_audio.astype(np.floataa )
# always return batch
if not is_batched:
_lowerCAmelCase = [np.asarray(_lowercase ).T]
# verify inputs are valid
for idx, example in enumerate(_lowercase ):
if example.ndim > 2:
raise ValueError(F'Expected input shape (channels, length) but got shape {example.shape}' )
if self.feature_size == 1 and example.ndim != 1:
raise ValueError(F'Expected mono audio but example has {example.shape[-1]} channels' )
if self.feature_size == 2 and example.shape[-1] != 2:
raise ValueError(F'Expected stereo audio but example has {example.shape[-1]} channels' )
_lowerCAmelCase = None
_lowerCAmelCase = BatchFeature({"""input_values""": raw_audio} )
if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
if truncation:
_lowerCAmelCase = min(array.shape[0] for array in raw_audio )
_lowerCAmelCase = int(np.floor(max_length / self.chunk_stride ) )
_lowerCAmelCase = (nb_step - 1) * self.chunk_stride + self.chunk_length
elif padding:
_lowerCAmelCase = max(array.shape[0] for array in raw_audio )
_lowerCAmelCase = int(np.ceil(max_length / self.chunk_stride ) )
_lowerCAmelCase = (nb_step - 1) * self.chunk_stride + self.chunk_length
_lowerCAmelCase = """max_length"""
else:
_lowerCAmelCase = input_values
# normal padding on batch
if padded_inputs is None:
_lowerCAmelCase = self.pad(
_lowercase , max_length=_lowercase , truncation=_lowercase , padding=_lowercase , return_attention_mask=_lowercase , )
if padding:
_lowerCAmelCase = padded_inputs.pop("""attention_mask""" )
_lowerCAmelCase = []
for example in padded_inputs.pop("""input_values""" ):
if self.feature_size == 1:
_lowerCAmelCase = example[..., None]
input_values.append(example.T )
_lowerCAmelCase = input_values
if return_tensors is not None:
_lowerCAmelCase = padded_inputs.convert_to_tensors(_lowercase )
return padded_inputs
| 5 | 0 |
import argparse
import json
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification
def a__ ( snake_case ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : List[Any] = SwinConfig()
__SCREAMING_SNAKE_CASE : Tuple = swin_name.split('''_''' )
__SCREAMING_SNAKE_CASE : List[str] = name_split[1]
__SCREAMING_SNAKE_CASE : List[str] = int(name_split[4] )
__SCREAMING_SNAKE_CASE : Optional[int] = int(name_split[3][-1] )
if model_size == "tiny":
__SCREAMING_SNAKE_CASE : List[str] = 96
__SCREAMING_SNAKE_CASE : Optional[int] = (2, 2, 6, 2)
__SCREAMING_SNAKE_CASE : Optional[int] = (3, 6, 12, 24)
elif model_size == "small":
__SCREAMING_SNAKE_CASE : Optional[Any] = 96
__SCREAMING_SNAKE_CASE : List[Any] = (2, 2, 18, 2)
__SCREAMING_SNAKE_CASE : Optional[int] = (3, 6, 12, 24)
elif model_size == "base":
__SCREAMING_SNAKE_CASE : Dict = 128
__SCREAMING_SNAKE_CASE : List[str] = (2, 2, 18, 2)
__SCREAMING_SNAKE_CASE : Optional[int] = (4, 8, 16, 32)
else:
__SCREAMING_SNAKE_CASE : str = 192
__SCREAMING_SNAKE_CASE : Optional[int] = (2, 2, 18, 2)
__SCREAMING_SNAKE_CASE : Optional[Any] = (6, 12, 24, 48)
if "in22k" in swin_name:
__SCREAMING_SNAKE_CASE : int = 21_841
else:
__SCREAMING_SNAKE_CASE : List[Any] = 1_000
__SCREAMING_SNAKE_CASE : int = '''huggingface/label-files'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''imagenet-1k-id2label.json'''
__SCREAMING_SNAKE_CASE : int = json.load(open(hf_hub_download(lowerCamelCase__ , lowerCamelCase__ , repo_type='''dataset''' ) , '''r''' ) )
__SCREAMING_SNAKE_CASE : List[str] = {int(lowerCamelCase__ ): v for k, v in idalabel.items()}
__SCREAMING_SNAKE_CASE : str = idalabel
__SCREAMING_SNAKE_CASE : Optional[Any] = {v: k for k, v in idalabel.items()}
__SCREAMING_SNAKE_CASE : Union[str, Any] = img_size
__SCREAMING_SNAKE_CASE : Optional[Any] = num_classes
__SCREAMING_SNAKE_CASE : Optional[int] = embed_dim
__SCREAMING_SNAKE_CASE : List[str] = depths
__SCREAMING_SNAKE_CASE : str = num_heads
__SCREAMING_SNAKE_CASE : Tuple = window_size
return config
def a__ ( snake_case ):
"""simple docstring"""
if "patch_embed.proj" in name:
__SCREAMING_SNAKE_CASE : Dict = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
if "patch_embed.norm" in name:
__SCREAMING_SNAKE_CASE : Dict = name.replace('''patch_embed.norm''' , '''embeddings.norm''' )
if "layers" in name:
__SCREAMING_SNAKE_CASE : Any = '''encoder.''' + name
if "attn.proj" in name:
__SCREAMING_SNAKE_CASE : Any = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name:
__SCREAMING_SNAKE_CASE : str = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
__SCREAMING_SNAKE_CASE : List[Any] = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
__SCREAMING_SNAKE_CASE : Any = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
__SCREAMING_SNAKE_CASE : int = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
__SCREAMING_SNAKE_CASE : Optional[Any] = name.replace('''mlp.fc2''' , '''output.dense''' )
if name == "norm.weight":
__SCREAMING_SNAKE_CASE : List[Any] = '''layernorm.weight'''
if name == "norm.bias":
__SCREAMING_SNAKE_CASE : Dict = '''layernorm.bias'''
if "head" in name:
__SCREAMING_SNAKE_CASE : Dict = name.replace('''head''' , '''classifier''' )
else:
__SCREAMING_SNAKE_CASE : Optional[int] = '''swin.''' + name
return name
def a__ ( snake_case , snake_case ):
"""simple docstring"""
for key in orig_state_dict.copy().keys():
__SCREAMING_SNAKE_CASE : Any = orig_state_dict.pop(lowerCamelCase__ )
if "mask" in key:
continue
elif "qkv" in key:
__SCREAMING_SNAKE_CASE : Optional[int] = key.split('''.''' )
__SCREAMING_SNAKE_CASE : List[str] = int(key_split[1] )
__SCREAMING_SNAKE_CASE : int = int(key_split[3] )
__SCREAMING_SNAKE_CASE : int = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
__SCREAMING_SNAKE_CASE : List[str] = val[:dim, :]
__SCREAMING_SNAKE_CASE : List[str] = val[
dim : dim * 2, :
]
__SCREAMING_SNAKE_CASE : List[str] = val[-dim:, :]
else:
__SCREAMING_SNAKE_CASE : Optional[int] = val[
:dim
]
__SCREAMING_SNAKE_CASE : List[str] = val[
dim : dim * 2
]
__SCREAMING_SNAKE_CASE : List[str] = val[
-dim:
]
else:
__SCREAMING_SNAKE_CASE : int = val
return orig_state_dict
def a__ ( snake_case , snake_case ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE : List[Any] = timm.create_model(lowerCamelCase__ , pretrained=lowerCamelCase__ )
timm_model.eval()
__SCREAMING_SNAKE_CASE : Union[str, Any] = get_swin_config(lowerCamelCase__ )
__SCREAMING_SNAKE_CASE : int = SwinForImageClassification(lowerCamelCase__ )
model.eval()
__SCREAMING_SNAKE_CASE : Any = convert_state_dict(timm_model.state_dict() , lowerCamelCase__ )
model.load_state_dict(lowerCamelCase__ )
__SCREAMING_SNAKE_CASE : Optional[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
__SCREAMING_SNAKE_CASE : List[Any] = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swin_name.replace('''_''' , '''-''' ) ) )
__SCREAMING_SNAKE_CASE : Tuple = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw )
__SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(images=lowerCamelCase__ , return_tensors='''pt''' )
__SCREAMING_SNAKE_CASE : Dict = timm_model(inputs['''pixel_values'''] )
__SCREAMING_SNAKE_CASE : Dict = model(**lowerCamelCase__ ).logits
assert torch.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-3 )
print(F'''Saving model {swin_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(lowerCamelCase__ )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(lowerCamelCase__ )
if __name__ == "__main__":
lowercase_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--swin_name""",
default="""swin_tiny_patch4_window7_224""",
type=str,
help="""Name of the Swin timm model you\'d like to convert.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
)
lowercase_ = parser.parse_args()
convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
| 721 |
from typing import List
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowercase_ = logging.get_logger(__name__)
lowercase_ = {
"""snap-research/efficientformer-l1-300""": (
"""https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"""
),
}
class __UpperCamelCase ( lowerCAmelCase__ ):
"""simple docstring"""
lowerCAmelCase_ = '''efficientformer'''
def __init__( self : Dict , _A : List[int] = [3, 2, 6, 4] , _A : List[int] = [48, 96, 224, 448] , _A : List[bool] = [True, True, True, True] , _A : int = 448 , _A : int = 32 , _A : int = 4 , _A : int = 7 , _A : int = 5 , _A : int = 8 , _A : int = 4 , _A : float = 0.0 , _A : int = 16 , _A : int = 3 , _A : int = 3 , _A : int = 3 , _A : int = 2 , _A : int = 1 , _A : float = 0.0 , _A : int = 1 , _A : bool = True , _A : bool = True , _A : float = 1e-5 , _A : str = "gelu" , _A : float = 0.02 , _A : float = 1e-12 , _A : int = 224 , _A : float = 1e-05 , **_A : Tuple , ):
"""simple docstring"""
super().__init__(**_A )
__SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
__SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob
__SCREAMING_SNAKE_CASE : List[str] = hidden_sizes
__SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers
__SCREAMING_SNAKE_CASE : List[str] = num_attention_heads
__SCREAMING_SNAKE_CASE : str = initializer_range
__SCREAMING_SNAKE_CASE : Any = layer_norm_eps
__SCREAMING_SNAKE_CASE : Dict = patch_size
__SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels
__SCREAMING_SNAKE_CASE : List[Any] = depths
__SCREAMING_SNAKE_CASE : Optional[Any] = mlp_expansion_ratio
__SCREAMING_SNAKE_CASE : List[str] = downsamples
__SCREAMING_SNAKE_CASE : str = dim
__SCREAMING_SNAKE_CASE : Any = key_dim
__SCREAMING_SNAKE_CASE : Tuple = attention_ratio
__SCREAMING_SNAKE_CASE : Dict = resolution
__SCREAMING_SNAKE_CASE : Dict = pool_size
__SCREAMING_SNAKE_CASE : List[str] = downsample_patch_size
__SCREAMING_SNAKE_CASE : int = downsample_stride
__SCREAMING_SNAKE_CASE : Optional[Any] = downsample_pad
__SCREAMING_SNAKE_CASE : Optional[int] = drop_path_rate
__SCREAMING_SNAKE_CASE : Optional[Any] = num_metaad_blocks
__SCREAMING_SNAKE_CASE : int = distillation
__SCREAMING_SNAKE_CASE : List[Any] = use_layer_scale
__SCREAMING_SNAKE_CASE : Optional[int] = layer_scale_init_value
__SCREAMING_SNAKE_CASE : Dict = image_size
__SCREAMING_SNAKE_CASE : List[str] = batch_norm_eps
| 131 | 0 |
'''simple docstring'''
import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple
import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs
from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging
logging.set_verbosity_info()
_SCREAMING_SNAKE_CASE = logging.get_logger()
@dataclass
class _lowerCAmelCase :
"""simple docstring"""
snake_case_ = 42
snake_case_ = field(default_factory=A__ )
snake_case_ = field(default_factory=A__ )
def lowerCAmelCase ( self : List[Any] , __snake_case : Optional[Any] , __snake_case : Tensor , __snake_case : Tensor )-> Dict:
snake_case = len(list(m.modules() ) ) == 1 or isinstance(__snake_case , nn.Convad ) or isinstance(__snake_case , nn.BatchNormad )
if has_not_submodules:
self.traced.append(__snake_case )
def __call__( self : int , __snake_case : Tensor )-> Optional[int]:
for m in self.module.modules():
self.handles.append(m.register_forward_hook(self._forward_hook ) )
self.module(__snake_case )
[x.remove() for x in self.handles]
return self
@property
def lowerCAmelCase ( self : Tuple )-> int:
# check the len of the state_dict keys to see if we have learnable params
return list(filter(lambda __snake_case : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) )
@dataclass
class _lowerCAmelCase :
"""simple docstring"""
snake_case_ = 42
snake_case_ = 42
snake_case_ = 1
snake_case_ = field(default_factory=A__ )
snake_case_ = field(default_factory=A__ )
snake_case_ = True
def __call__( self : Optional[int] , __snake_case : Tensor )-> Tuple:
snake_case = Tracker(self.dest )(__snake_case ).parametrized
snake_case = Tracker(self.src )(__snake_case ).parametrized
snake_case = list(filter(lambda __snake_case : type(__snake_case ) not in self.src_skip , __snake_case ) )
snake_case = list(filter(lambda __snake_case : type(__snake_case ) not in self.dest_skip , __snake_case ) )
if len(__snake_case ) != len(__snake_case ) and self.raise_if_mismatch:
raise Exception(
f'''Numbers of operations are different. Source module has {len(__snake_case )} operations while'''
f''' destination module has {len(__snake_case )}.''' )
for dest_m, src_m in zip(__snake_case , __snake_case ):
dest_m.load_state_dict(src_m.state_dict() )
if self.verbose == 1:
print(f'''Transfered from={src_m} to={dest_m}''' )
class _lowerCAmelCase ( nn.Module ):
"""simple docstring"""
def __init__( self : Optional[Any] , __snake_case : nn.Module )-> str:
super().__init__()
snake_case = []
# - get the stem
feature_blocks.append(("""conv1""", model.stem) )
# - get all the feature blocks
for k, v in model.trunk_output.named_children():
assert k.startswith("""block""" ), f'''Unexpected layer name {k}'''
snake_case = len(__snake_case ) + 1
feature_blocks.append((f'''res{block_index}''', v) )
snake_case = nn.ModuleDict(__snake_case )
def lowerCAmelCase ( self : List[str] , __snake_case : Tensor )-> Dict:
return get_trunk_forward_outputs(
__snake_case , out_feat_keys=__snake_case , feature_blocks=self._feature_blocks , )
class _lowerCAmelCase ( A__ ):
"""simple docstring"""
def lowerCAmelCase ( self : List[Any] , __snake_case : str )-> str:
snake_case = x.split("""-""" )
return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] )
def __getitem__( self : Optional[int] , __snake_case : str )-> Callable[[], Tuple[nn.Module, Dict]]:
# default to timm!
if x not in self:
snake_case = self.convert_name_to_timm(__snake_case )
snake_case = partial(lambda: (timm.create_model(__snake_case , pretrained=__snake_case ).eval(), None) )
else:
snake_case = super().__getitem__(__snake_case )
return val
class _lowerCAmelCase ( A__ ):
"""simple docstring"""
def __getitem__( self : int , __snake_case : str )-> Callable[[], nn.Module]:
if "seer" in x and "in1k" not in x:
snake_case = RegNetModel
else:
snake_case = RegNetForImageClassification
return val
def __lowerCamelCase ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : List[Tuple[str, str]] ) -> str:
for from_key, to_key in keys:
snake_case = from_state_dict[from_key].clone()
print(F'''Copied key={from_key} to={to_key}''' )
return to_state_dict
def __lowerCamelCase ( __lowerCAmelCase : str , __lowerCAmelCase : Callable[[], nn.Module] , __lowerCAmelCase : Callable[[], nn.Module] , __lowerCAmelCase : RegNetConfig , __lowerCAmelCase : Path , __lowerCAmelCase : bool = True , ) -> Union[str, Any]:
print(F'''Converting {name}...''' )
with torch.no_grad():
snake_case , snake_case = from_model_func()
snake_case = our_model_func(__lowerCAmelCase ).eval()
snake_case = ModuleTransfer(src=__lowerCAmelCase , dest=__lowerCAmelCase , raise_if_mismatch=__lowerCAmelCase )
snake_case = torch.randn((1, 3, 2_24, 2_24) )
module_transfer(__lowerCAmelCase )
if from_state_dict is not None:
snake_case = []
# for seer - in1k finetuned we have to manually copy the head
if "seer" in name and "in1k" in name:
snake_case = [("""0.clf.0.weight""", """classifier.1.weight"""), ("""0.clf.0.bias""", """classifier.1.bias""")]
snake_case = manually_copy_vissl_head(__lowerCAmelCase , our_model.state_dict() , __lowerCAmelCase )
our_model.load_state_dict(__lowerCAmelCase )
snake_case = our_model(__lowerCAmelCase , output_hidden_states=__lowerCAmelCase )
snake_case = (
our_outputs.logits if isinstance(__lowerCAmelCase , __lowerCAmelCase ) else our_outputs.last_hidden_state
)
snake_case = from_model(__lowerCAmelCase )
snake_case = from_output[-1] if type(__lowerCAmelCase ) is list else from_output
# now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
if "seer" in name and "in1k" in name:
snake_case = our_outputs.hidden_states[-1]
assert torch.allclose(__lowerCAmelCase , __lowerCAmelCase ), "The model logits don't match the original one."
if push_to_hub:
our_model.push_to_hub(
repo_path_or_name=save_directory / name , commit_message="""Add model""" , use_temp_dir=__lowerCAmelCase , )
snake_case = 2_24 if """seer""" not in name else 3_84
# we can use the convnext one
snake_case = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" , size=__lowerCAmelCase )
image_processor.push_to_hub(
repo_path_or_name=save_directory / name , commit_message="""Add image processor""" , use_temp_dir=__lowerCAmelCase , )
print(F'''Pushed {name}''' )
def __lowerCamelCase ( __lowerCAmelCase : Path , __lowerCAmelCase : str = None , __lowerCAmelCase : bool = True ) -> Optional[int]:
snake_case = """imagenet-1k-id2label.json"""
snake_case = 10_00
snake_case = (1, num_labels)
snake_case = """huggingface/label-files"""
snake_case = num_labels
snake_case = json.load(open(cached_download(hf_hub_url(__lowerCAmelCase , __lowerCAmelCase , repo_type="""dataset""" ) ) , """r""" ) )
snake_case = {int(__lowerCAmelCase ): v for k, v in idalabel.items()}
snake_case = idalabel
snake_case = {v: k for k, v in idalabel.items()}
snake_case = partial(__lowerCAmelCase , num_labels=__lowerCAmelCase , idalabel=__lowerCAmelCase , labelaid=__lowerCAmelCase )
snake_case = {
"""regnet-x-002""": ImageNetPreTrainedConfig(
depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type="""x""" ),
"""regnet-x-004""": ImageNetPreTrainedConfig(
depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type="""x""" ),
"""regnet-x-006""": ImageNetPreTrainedConfig(
depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type="""x""" ),
"""regnet-x-008""": ImageNetPreTrainedConfig(
depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type="""x""" ),
"""regnet-x-016""": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type="""x""" ),
"""regnet-x-032""": ImageNetPreTrainedConfig(
depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type="""x""" ),
"""regnet-x-040""": ImageNetPreTrainedConfig(
depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type="""x""" ),
"""regnet-x-064""": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type="""x""" ),
"""regnet-x-080""": ImageNetPreTrainedConfig(
depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type="""x""" ),
"""regnet-x-120""": ImageNetPreTrainedConfig(
depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type="""x""" ),
"""regnet-x-160""": ImageNetPreTrainedConfig(
depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type="""x""" ),
"""regnet-x-320""": ImageNetPreTrainedConfig(
depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type="""x""" ),
# y variant
"""regnet-y-002""": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ),
"""regnet-y-004""": ImageNetPreTrainedConfig(
depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ),
"""regnet-y-006""": ImageNetPreTrainedConfig(
depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ),
"""regnet-y-008""": ImageNetPreTrainedConfig(
depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ),
"""regnet-y-016""": ImageNetPreTrainedConfig(
depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ),
"""regnet-y-032""": ImageNetPreTrainedConfig(
depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ),
"""regnet-y-040""": ImageNetPreTrainedConfig(
depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ),
"""regnet-y-064""": ImageNetPreTrainedConfig(
depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ),
"""regnet-y-080""": ImageNetPreTrainedConfig(
depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ),
"""regnet-y-120""": ImageNetPreTrainedConfig(
depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ),
"""regnet-y-160""": ImageNetPreTrainedConfig(
depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ),
"""regnet-y-320""": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ),
# models created by SEER -> https://arxiv.org/abs/2202.08360
"""regnet-y-320-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ),
"""regnet-y-640-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ),
"""regnet-y-1280-seer""": RegNetConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ),
"""regnet-y-2560-seer""": RegNetConfig(
depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ),
"""regnet-y-10b-seer""": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ),
# finetuned on imagenet
"""regnet-y-320-seer-in1k""": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ),
"""regnet-y-640-seer-in1k""": ImageNetPreTrainedConfig(
depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ),
"""regnet-y-1280-seer-in1k""": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ),
"""regnet-y-2560-seer-in1k""": ImageNetPreTrainedConfig(
depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ),
"""regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig(
depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ),
}
snake_case = NameToOurModelFuncMap()
snake_case = NameToFromModelFuncMap()
# add seer weights logic
def load_using_classy_vision(__lowerCAmelCase : str , __lowerCAmelCase : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]:
snake_case = torch.hub.load_state_dict_from_url(__lowerCAmelCase , model_dir=str(__lowerCAmelCase ) , map_location="""cpu""" )
snake_case = model_func()
# check if we have a head, if yes add it
snake_case = files["""classy_state_dict"""]["""base_model"""]["""model"""]
snake_case = model_state_dict["""trunk"""]
model.load_state_dict(__lowerCAmelCase )
return model.eval(), model_state_dict["heads"]
# pretrained
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , )
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch""" , lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , )
# IN1K finetuned
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , )
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , )
snake_case = partial(
__lowerCAmelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch""" , lambda: FakeRegNetVisslWrapper(
RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , )
if model_name:
convert_weight_and_push(
__lowerCAmelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , __lowerCAmelCase , __lowerCAmelCase , )
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(
__lowerCAmelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , )
return config, expected_shape
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_name",
default=None,
type=str,
help=(
"The name of the model you wish to convert, it must be one of the supported regnet* architecture,"
" currently: regnetx-*, regnety-*. If `None`, all of them will the converted."
),
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=Path,
required=True,
help="Path to the output PyTorch model directory.",
)
parser.add_argument(
"--push_to_hub",
default=True,
type=bool,
required=False,
help="If True, push model and image processor to the hub.",
)
_SCREAMING_SNAKE_CASE = parser.parse_args()
_SCREAMING_SNAKE_CASE = args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 369 |
'''simple docstring'''
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch
import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin, SchedulerOutput
@dataclass
class _lowerCAmelCase ( A__ ):
"""simple docstring"""
snake_case_ = 42
snake_case_ = 42
class _lowerCAmelCase ( A__ , A__ ):
"""simple docstring"""
snake_case_ = 1
@register_to_config
def __init__( self : str , __snake_case : int = 20_00 , __snake_case : float = 0.15 , __snake_case : float = 0.01 , __snake_case : float = 13_48.0 , __snake_case : float = 1e-5 , __snake_case : int = 1 , )-> str:
# standard deviation of the initial noise distribution
snake_case = sigma_max
# setable values
snake_case = None
self.set_sigmas(__snake_case , __snake_case , __snake_case , __snake_case )
def lowerCAmelCase ( self : List[Any] , __snake_case : torch.FloatTensor , __snake_case : Optional[int] = None )-> torch.FloatTensor:
return sample
def lowerCAmelCase ( self : List[str] , __snake_case : int , __snake_case : float = None , __snake_case : Union[str, torch.device] = None )-> Optional[Any]:
snake_case = sampling_eps if sampling_eps is not None else self.config.sampling_eps
snake_case = torch.linspace(1 , __snake_case , __snake_case , device=__snake_case )
def lowerCAmelCase ( self : Union[str, Any] , __snake_case : int , __snake_case : float = None , __snake_case : float = None , __snake_case : float = None )-> str:
snake_case = sigma_min if sigma_min is not None else self.config.sigma_min
snake_case = sigma_max if sigma_max is not None else self.config.sigma_max
snake_case = sampling_eps if sampling_eps is not None else self.config.sampling_eps
if self.timesteps is None:
self.set_timesteps(__snake_case , __snake_case )
snake_case = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
snake_case = torch.exp(torch.linspace(math.log(__snake_case ) , math.log(__snake_case ) , __snake_case ) )
snake_case = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] )
def lowerCAmelCase ( self : str , __snake_case : List[str] , __snake_case : str )-> Optional[int]:
return torch.where(
timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , )
def lowerCAmelCase ( self : int , __snake_case : torch.FloatTensor , __snake_case : int , __snake_case : torch.FloatTensor , __snake_case : Optional[torch.Generator] = None , __snake_case : bool = True , )-> Union[SdeVeOutput, Tuple]:
if self.timesteps is None:
raise ValueError(
"""`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler""" )
snake_case = timestep * torch.ones(
sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0])
snake_case = (timestep * (len(self.timesteps ) - 1)).long()
# mps requires indices to be in the same device, so we use cpu as is the default with cuda
snake_case = timesteps.to(self.discrete_sigmas.device )
snake_case = self.discrete_sigmas[timesteps].to(sample.device )
snake_case = self.get_adjacent_sigma(__snake_case , __snake_case ).to(sample.device )
snake_case = torch.zeros_like(__snake_case )
snake_case = (sigma**2 - adjacent_sigma**2) ** 0.5
# equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
# also equation 47 shows the analog from SDE models to ancestral sampling methods
snake_case = diffusion.flatten()
while len(diffusion.shape ) < len(sample.shape ):
snake_case = diffusion.unsqueeze(-1 )
snake_case = drift - diffusion**2 * model_output
# equation 6: sample noise for the diffusion term of
snake_case = randn_tensor(
sample.shape , layout=sample.layout , generator=__snake_case , device=sample.device , dtype=sample.dtype )
snake_case = sample - drift # subtract because `dt` is a small negative timestep
# TODO is the variable diffusion the correct scaling term for the noise?
snake_case = prev_sample_mean + diffusion * noise # add impact of diffusion field g
if not return_dict:
return (prev_sample, prev_sample_mean)
return SdeVeOutput(prev_sample=__snake_case , prev_sample_mean=__snake_case )
def lowerCAmelCase ( self : Optional[Any] , __snake_case : torch.FloatTensor , __snake_case : torch.FloatTensor , __snake_case : Optional[torch.Generator] = None , __snake_case : bool = True , )-> Union[SchedulerOutput, Tuple]:
if self.timesteps is None:
raise ValueError(
"""`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler""" )
# For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
# sample noise for correction
snake_case = randn_tensor(sample.shape , layout=sample.layout , generator=__snake_case ).to(sample.device )
# compute step size from the model_output, the noise, and the snr
snake_case = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean()
snake_case = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean()
snake_case = (self.config.snr * noise_norm / grad_norm) ** 2 * 2
snake_case = step_size * torch.ones(sample.shape[0] ).to(sample.device )
# self.repeat_scalar(step_size, sample.shape[0])
# compute corrected sample: model_output term and noise term
snake_case = step_size.flatten()
while len(step_size.shape ) < len(sample.shape ):
snake_case = step_size.unsqueeze(-1 )
snake_case = sample + step_size * model_output
snake_case = prev_sample_mean + ((step_size * 2) ** 0.5) * noise
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__snake_case )
def lowerCAmelCase ( self : str , __snake_case : torch.FloatTensor , __snake_case : torch.FloatTensor , __snake_case : torch.FloatTensor , )-> torch.FloatTensor:
# Make sure sigmas and timesteps have the same device and dtype as original_samples
snake_case = timesteps.to(original_samples.device )
snake_case = self.discrete_sigmas.to(original_samples.device )[timesteps]
snake_case = (
noise * sigmas[:, None, None, None]
if noise is not None
else torch.randn_like(__snake_case ) * sigmas[:, None, None, None]
)
snake_case = noise + original_samples
return noisy_samples
def __len__( self : str )-> Any:
return self.config.num_train_timesteps
| 369 | 1 |
'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_A : Union[str, Any] ={'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A : Any =['''TimmBackbone''']
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
_A : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 4 |
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
_A : int =logging.get_logger(__name__)
_A : Union[str, Any] ={
'''Salesforce/instruct-blip-flan-t5''': '''https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json''',
}
class lowerCamelCase__ ( A ):
'''simple docstring'''
A_ = """instructblip_vision_model"""
def __init__( self : Union[str, Any] , UpperCamelCase_ : str=1408 , UpperCamelCase_ : Tuple=6144 , UpperCamelCase_ : Union[str, Any]=39 , UpperCamelCase_ : Optional[Any]=16 , UpperCamelCase_ : str=224 , UpperCamelCase_ : Dict=14 , UpperCamelCase_ : Dict="gelu" , UpperCamelCase_ : int=1E-6 , UpperCamelCase_ : int=0.0 , UpperCamelCase_ : List[str]=1E-10 , UpperCamelCase_ : str=True , **UpperCamelCase_ : Dict , ) -> Any:
'''simple docstring'''
super().__init__(**UpperCamelCase_ )
_lowercase : Optional[Any] = hidden_size
_lowercase : Optional[Any] = intermediate_size
_lowercase : Optional[int] = num_hidden_layers
_lowercase : str = num_attention_heads
_lowercase : Tuple = patch_size
_lowercase : Dict = image_size
_lowercase : Optional[int] = initializer_range
_lowercase : List[Any] = attention_dropout
_lowercase : int = layer_norm_eps
_lowercase : Optional[int] = hidden_act
_lowercase : str = qkv_bias
@classmethod
def __UpperCAmelCase ( cls : List[Any] , UpperCamelCase_ : Union[str, os.PathLike] , **UpperCamelCase_ : List[str] ) -> "PretrainedConfig":
'''simple docstring'''
cls._set_token_in_kwargs(UpperCamelCase_ )
_lowercase , _lowercase : Tuple = cls.get_config_dict(UpperCamelCase_ , **UpperCamelCase_ )
# get the vision config dict if we are loading from InstructBlipConfig
if config_dict.get('model_type' ) == "instructblip":
_lowercase : Any = config_dict['vision_config']
if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(UpperCamelCase_ , **UpperCamelCase_ )
class lowerCamelCase__ ( A ):
'''simple docstring'''
A_ = """instructblip_qformer"""
def __init__( self : Tuple , UpperCamelCase_ : Union[str, Any]=3_0522 , UpperCamelCase_ : Union[str, Any]=768 , UpperCamelCase_ : Tuple=12 , UpperCamelCase_ : Optional[Any]=12 , UpperCamelCase_ : List[str]=3072 , UpperCamelCase_ : List[str]="gelu" , UpperCamelCase_ : Union[str, Any]=0.1 , UpperCamelCase_ : List[str]=0.1 , UpperCamelCase_ : Any=512 , UpperCamelCase_ : Union[str, Any]=0.02 , UpperCamelCase_ : List[Any]=1E-12 , UpperCamelCase_ : Optional[Any]=0 , UpperCamelCase_ : str="absolute" , UpperCamelCase_ : List[Any]=2 , UpperCamelCase_ : Any=1408 , **UpperCamelCase_ : Dict , ) -> Any:
'''simple docstring'''
super().__init__(pad_token_id=UpperCamelCase_ , **UpperCamelCase_ )
_lowercase : Dict = vocab_size
_lowercase : Optional[Any] = hidden_size
_lowercase : Any = num_hidden_layers
_lowercase : List[Any] = num_attention_heads
_lowercase : Optional[int] = hidden_act
_lowercase : Union[str, Any] = intermediate_size
_lowercase : List[Any] = hidden_dropout_prob
_lowercase : Dict = attention_probs_dropout_prob
_lowercase : Any = max_position_embeddings
_lowercase : Optional[int] = initializer_range
_lowercase : Tuple = layer_norm_eps
_lowercase : List[str] = position_embedding_type
_lowercase : str = cross_attention_frequency
_lowercase : int = encoder_hidden_size
@classmethod
def __UpperCAmelCase ( cls : List[Any] , UpperCamelCase_ : Union[str, os.PathLike] , **UpperCamelCase_ : List[str] ) -> "PretrainedConfig":
'''simple docstring'''
cls._set_token_in_kwargs(UpperCamelCase_ )
_lowercase , _lowercase : List[str] = cls.get_config_dict(UpperCamelCase_ , **UpperCamelCase_ )
# get the qformer config dict if we are loading from InstructBlipConfig
if config_dict.get('model_type' ) == "instructblip":
_lowercase : Optional[int] = config_dict['qformer_config']
if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type '''
F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(UpperCamelCase_ , **UpperCamelCase_ )
class lowerCamelCase__ ( A ):
'''simple docstring'''
A_ = """instructblip"""
A_ = True
def __init__( self : Any , UpperCamelCase_ : List[Any]=None , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Dict=None , UpperCamelCase_ : Union[str, Any]=32 , **UpperCamelCase_ : int ) -> List[str]:
'''simple docstring'''
super().__init__(**UpperCamelCase_ )
if vision_config is None:
_lowercase : Any = {}
logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' )
if qformer_config is None:
_lowercase : List[Any] = {}
logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' )
if text_config is None:
_lowercase : List[Any] = {}
logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' )
_lowercase : List[Any] = InstructBlipVisionConfig(**UpperCamelCase_ )
_lowercase : Union[str, Any] = InstructBlipQFormerConfig(**UpperCamelCase_ )
_lowercase : Union[str, Any] = text_config['model_type'] if 'model_type' in text_config else 'opt'
_lowercase : int = CONFIG_MAPPING[text_model_type](**UpperCamelCase_ )
_lowercase : str = self.text_config.tie_word_embeddings
_lowercase : int = self.text_config.is_encoder_decoder
_lowercase : Tuple = num_query_tokens
_lowercase : str = self.vision_config.hidden_size
_lowercase : Union[str, Any] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
_lowercase : List[Any] = 1.0
_lowercase : int = 0.02
@classmethod
def __UpperCAmelCase ( cls : Tuple , UpperCamelCase_ : InstructBlipVisionConfig , UpperCamelCase_ : InstructBlipQFormerConfig , UpperCamelCase_ : PretrainedConfig , **UpperCamelCase_ : Dict , ) -> List[str]:
'''simple docstring'''
return cls(
vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **UpperCamelCase_ , )
def __UpperCAmelCase ( self : Dict ) -> List[str]:
'''simple docstring'''
_lowercase : List[Any] = copy.deepcopy(self.__dict__ )
_lowercase : Optional[int] = self.vision_config.to_dict()
_lowercase : Optional[Any] = self.qformer_config.to_dict()
_lowercase : Tuple = self.text_config.to_dict()
_lowercase : Dict = self.__class__.model_type
return output
| 4 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
lowerCamelCase = {
"""configuration_resnet""": ["""RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ResNetConfig""", """ResNetOnnxConfig"""]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase = [
"""RESNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ResNetForImageClassification""",
"""ResNetModel""",
"""ResNetPreTrainedModel""",
"""ResNetBackbone""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase = [
"""TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFResNetForImageClassification""",
"""TFResNetModel""",
"""TFResNetPreTrainedModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCamelCase = [
"""FlaxResNetForImageClassification""",
"""FlaxResNetModel""",
"""FlaxResNetPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_resnet import (
RESNET_PRETRAINED_MODEL_ARCHIVE_LIST,
ResNetBackbone,
ResNetForImageClassification,
ResNetModel,
ResNetPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_resnet import (
TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST,
TFResNetForImageClassification,
TFResNetModel,
TFResNetPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel
else:
import sys
lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
| 82 |
"""simple docstring"""
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
return round(float(moles / volume ) * nfactor )
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
return round(float((moles * 0.0821 * temperature) / (volume) ) )
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
return round(float((moles * 0.0821 * temperature) / (pressure) ) )
def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
return round(float((pressure * volume) / (0.0821 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 82 | 1 |
'''simple docstring'''
import unittest
from parameterized import parameterized
from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
GPTNeoXForCausalLM,
GPTNeoXForQuestionAnswering,
GPTNeoXForSequenceClassification,
GPTNeoXForTokenClassification,
GPTNeoXModel,
)
class a :
"""simple docstring"""
def __init__( self : Any , snake_case_ : str , snake_case_ : Optional[Any]=1_3 , snake_case_ : int=7 , snake_case_ : int=True , snake_case_ : Optional[Any]=True , snake_case_ : Dict=True , snake_case_ : int=True , snake_case_ : Optional[Any]=9_9 , snake_case_ : int=6_4 , snake_case_ : Dict=5 , snake_case_ : List[Any]=4 , snake_case_ : Union[str, Any]=3_7 , snake_case_ : Dict="gelu" , snake_case_ : Union[str, Any]=0.1 , snake_case_ : Dict=0.1 , snake_case_ : Any=5_1_2 , snake_case_ : Any=1_6 , snake_case_ : Any=2 , snake_case_ : Dict=0.0_2 , snake_case_ : List[str]=3 , snake_case_ : Optional[int]=4 , snake_case_ : str=None , ):
'''simple docstring'''
snake_case__ : List[Any] = parent
snake_case__ : int = batch_size
snake_case__ : Dict = seq_length
snake_case__ : int = is_training
snake_case__ : Optional[Any] = use_input_mask
snake_case__ : Optional[Any] = use_token_type_ids
snake_case__ : Dict = use_labels
snake_case__ : int = vocab_size
snake_case__ : Any = hidden_size
snake_case__ : int = num_hidden_layers
snake_case__ : Union[str, Any] = num_attention_heads
snake_case__ : List[Any] = intermediate_size
snake_case__ : int = hidden_act
snake_case__ : int = hidden_dropout_prob
snake_case__ : List[Any] = attention_probs_dropout_prob
snake_case__ : Optional[int] = max_position_embeddings
snake_case__ : Optional[int] = type_vocab_size
snake_case__ : Any = type_sequence_label_size
snake_case__ : str = initializer_range
snake_case__ : List[str] = num_labels
snake_case__ : Dict = num_choices
snake_case__ : Union[str, Any] = scope
snake_case__ : List[Any] = vocab_size - 1
def __magic_name__ ( self : List[Any] ):
'''simple docstring'''
snake_case__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case__ : Optional[int] = None
if self.use_input_mask:
snake_case__ : int = random_attention_mask([self.batch_size, self.seq_length] )
snake_case__ : Union[str, Any] = None
if self.use_labels:
snake_case__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
snake_case__ : Dict = self.get_config()
return config, input_ids, input_mask, token_labels
def __magic_name__ ( self : List[Any] ):
'''simple docstring'''
return GPTNeoXConfig(
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 , pad_token_id=self.pad_token_id , )
def __magic_name__ ( self : List[str] ):
'''simple docstring'''
snake_case__ , snake_case__ , snake_case__ , snake_case__ : str = self.prepare_config_and_inputs()
snake_case__ : List[str] = True
return config, input_ids, input_mask, token_labels
def __magic_name__ ( self : Tuple , snake_case_ : Any , snake_case_ : str , snake_case_ : str ):
'''simple docstring'''
snake_case__ : Any = GPTNeoXModel(config=snake_case_ )
model.to(snake_case_ )
model.eval()
snake_case__ : Union[str, Any] = model(snake_case_ , attention_mask=snake_case_ )
snake_case__ : int = model(snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __magic_name__ ( self : List[Any] , snake_case_ : Any , snake_case_ : List[Any] , snake_case_ : Optional[int] ):
'''simple docstring'''
snake_case__ : Union[str, Any] = True
snake_case__ : Tuple = GPTNeoXModel(snake_case_ )
model.to(snake_case_ )
model.eval()
snake_case__ : Dict = model(snake_case_ , attention_mask=snake_case_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __magic_name__ ( self : Any , snake_case_ : str , snake_case_ : Tuple , snake_case_ : Optional[int] , snake_case_ : List[Any] ):
'''simple docstring'''
snake_case__ : Union[str, Any] = GPTNeoXForCausalLM(config=snake_case_ )
model.to(snake_case_ )
model.eval()
snake_case__ : Tuple = model(snake_case_ , attention_mask=snake_case_ , labels=snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __magic_name__ ( self : Optional[int] , snake_case_ : str , snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : List[str] ):
'''simple docstring'''
snake_case__ : Dict = self.num_labels
snake_case__ : List[Any] = GPTNeoXForQuestionAnswering(snake_case_ )
model.to(snake_case_ )
model.eval()
snake_case__ : Any = model(snake_case_ , attention_mask=snake_case_ )
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 __magic_name__ ( self : List[Any] , snake_case_ : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Dict ):
'''simple docstring'''
snake_case__ : str = self.num_labels
snake_case__ : List[str] = GPTNeoXForSequenceClassification(snake_case_ )
model.to(snake_case_ )
model.eval()
snake_case__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size )
snake_case__ : str = model(snake_case_ , attention_mask=snake_case_ , labels=snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __magic_name__ ( self : Union[str, Any] , snake_case_ : Optional[Any] , snake_case_ : int , snake_case_ : Dict , snake_case_ : Optional[int] ):
'''simple docstring'''
snake_case__ : Any = self.num_labels
snake_case__ : Any = GPTNeoXForTokenClassification(snake_case_ )
model.to(snake_case_ )
model.eval()
snake_case__ : Optional[Any] = model(snake_case_ , attention_mask=snake_case_ , labels=snake_case_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def __magic_name__ ( self : Union[str, Any] , snake_case_ : int , snake_case_ : Union[str, Any] , snake_case_ : Tuple ):
'''simple docstring'''
snake_case__ : Optional[Any] = True
snake_case__ : Union[str, Any] = GPTNeoXForCausalLM(config=snake_case_ )
model.to(snake_case_ )
model.eval()
# first forward pass
snake_case__ : int = model(snake_case_ , attention_mask=snake_case_ , use_cache=snake_case_ )
snake_case__ : Dict = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
snake_case__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size )
snake_case__ : Union[str, Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
snake_case__ : Dict = torch.cat([input_ids, next_tokens] , dim=-1 )
snake_case__ : Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 )
snake_case__ : Optional[Any] = model(snake_case_ , attention_mask=snake_case_ , output_hidden_states=snake_case_ )
snake_case__ : Union[str, Any] = output_from_no_past['''hidden_states'''][0]
snake_case__ : str = model(
snake_case_ , attention_mask=snake_case_ , past_key_values=snake_case_ , output_hidden_states=snake_case_ , )['''hidden_states'''][0]
# select random slice
snake_case__ : str = ids_tensor((1,) , output_from_past.shape[-1] ).item()
snake_case__ : str = output_from_no_past[:, -3:, random_slice_idx].detach()
snake_case__ : Union[str, Any] = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(snake_case_ , snake_case_ , atol=1e-3 ) )
def __magic_name__ ( self : Optional[int] ):
'''simple docstring'''
snake_case__ : Dict = self.prepare_config_and_inputs()
snake_case__ , snake_case__ , snake_case__ , snake_case__ : Tuple = config_and_inputs
snake_case__ : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
__UpperCAmelCase = (
(
GPTNeoXModel,
GPTNeoXForCausalLM,
GPTNeoXForQuestionAnswering,
GPTNeoXForSequenceClassification,
GPTNeoXForTokenClassification,
)
if is_torch_available()
else ()
)
__UpperCAmelCase = (GPTNeoXForCausalLM,) if is_torch_available() else ()
__UpperCAmelCase = (
{
"""feature-extraction""": GPTNeoXModel,
"""question-answering""": GPTNeoXForQuestionAnswering,
"""text-classification""": GPTNeoXForSequenceClassification,
"""text-generation""": GPTNeoXForCausalLM,
"""token-classification""": GPTNeoXForTokenClassification,
"""zero-shot""": GPTNeoXForSequenceClassification,
}
if is_torch_available()
else {}
)
__UpperCAmelCase = False
__UpperCAmelCase = False
__UpperCAmelCase = False
__UpperCAmelCase = False
def __magic_name__ ( self : int ):
'''simple docstring'''
snake_case__ : Optional[int] = GPTNeoXModelTester(self )
snake_case__ : List[str] = ConfigTester(self , config_class=snake_case_ , hidden_size=6_4 , num_attention_heads=8 )
def __magic_name__ ( self : List[str] ):
'''simple docstring'''
self.config_tester.run_common_tests()
def __magic_name__ ( self : Dict ):
'''simple docstring'''
snake_case__ , snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(snake_case_ , snake_case_ , snake_case_ )
def __magic_name__ ( self : Dict ):
'''simple docstring'''
snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(snake_case_ , snake_case_ , snake_case_ )
def __magic_name__ ( self : Union[str, Any] ):
'''simple docstring'''
snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_decoder()
snake_case__ : Optional[int] = None
self.model_tester.create_and_check_model_as_decoder(snake_case_ , snake_case_ , snake_case_ )
def __magic_name__ ( self : Optional[int] ):
'''simple docstring'''
snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(snake_case_ , snake_case_ , snake_case_ )
def __magic_name__ ( self : int ):
'''simple docstring'''
snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_causal_lm(*snake_case_ )
def __magic_name__ ( self : List[str] ):
'''simple docstring'''
snake_case__ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*snake_case_ )
def __magic_name__ ( self : Any ):
'''simple docstring'''
snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*snake_case_ )
def __magic_name__ ( self : List[Any] ):
'''simple docstring'''
snake_case__ : int = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*snake_case_ )
@unittest.skip(reason='''Feed forward chunking is not implemented''' )
def __magic_name__ ( self : Optional[Any] ):
'''simple docstring'''
pass
@parameterized.expand([('''linear''',), ('''dynamic''',)] )
def __magic_name__ ( self : Optional[int] , snake_case_ : Optional[Any] ):
'''simple docstring'''
snake_case__ , snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
snake_case__ : Dict = ids_tensor([1, 1_0] , config.vocab_size )
snake_case__ : List[Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size )
set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights
snake_case__ : Tuple = GPTNeoXModel(snake_case_ )
original_model.to(snake_case_ )
original_model.eval()
snake_case__ : Any = original_model(snake_case_ ).last_hidden_state
snake_case__ : List[str] = original_model(snake_case_ ).last_hidden_state
set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights
snake_case__ : Optional[Any] = {'''type''': scaling_type, '''factor''': 1_0.0}
snake_case__ : Optional[Any] = GPTNeoXModel(snake_case_ )
scaled_model.to(snake_case_ )
scaled_model.eval()
snake_case__ : Optional[int] = scaled_model(snake_case_ ).last_hidden_state
snake_case__ : List[str] = scaled_model(snake_case_ ).last_hidden_state
# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
# maximum sequence length, so the outputs for the short input should match.
if scaling_type == "dynamic":
self.assertTrue(torch.allclose(snake_case_ , snake_case_ , atol=1e-5 ) )
else:
self.assertFalse(torch.allclose(snake_case_ , snake_case_ , atol=1e-5 ) )
# The output should be different for long inputs
self.assertFalse(torch.allclose(snake_case_ , snake_case_ , atol=1e-5 ) )
@require_torch
class a ( unittest.TestCase ):
"""simple docstring"""
@slow
def __magic_name__ ( self : List[str] ):
'''simple docstring'''
snake_case__ : Dict = AutoTokenizer.from_pretrained('''EleutherAI/pythia-410m-deduped''' )
for checkpointing in [True, False]:
snake_case__ : str = GPTNeoXForCausalLM.from_pretrained('''EleutherAI/pythia-410m-deduped''' )
if checkpointing:
model.gradient_checkpointing_enable()
else:
model.gradient_checkpointing_disable()
model.to(snake_case_ )
snake_case__ : Tuple = tokenizer('''My favorite food is''' , return_tensors='''pt''' ).to(snake_case_ )
# The hub repo. is updated on 2023-04-04, resulting in poor outputs.
# See: https://github.com/huggingface/transformers/pull/24193
snake_case__ : List[str] = '''My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI\'m not sure'''
snake_case__ : Optional[int] = model.generate(**snake_case_ , do_sample=snake_case_ , max_new_tokens=2_0 )
snake_case__ : Tuple = tokenizer.batch_decode(snake_case_ )[0]
self.assertEqual(snake_case_ , snake_case_ )
| 502 |
'''simple docstring'''
from argparse import ArgumentParser, Namespace
from typing import Any, List, Optional
from ..pipelines import Pipeline, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand
try:
from fastapi import Body, FastAPI, HTTPException
from fastapi.routing import APIRoute
from pydantic import BaseModel
from starlette.responses import JSONResponse
from uvicorn import run
lowerCAmelCase__ : Any = True
except (ImportError, AttributeError):
lowerCAmelCase__ : Dict = object
def _a ( *__lowerCAmelCase : List[str] , **__lowerCAmelCase : Tuple ):
"""simple docstring"""
pass
lowerCAmelCase__ : str = False
lowerCAmelCase__ : List[str] = logging.get_logger("""transformers-cli/serving""")
def _a ( __lowerCAmelCase : Namespace ):
"""simple docstring"""
snake_case__ : Union[str, Any] = pipeline(
task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , )
return ServeCommand(__lowerCAmelCase , args.host , args.port , args.workers )
class a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
__UpperCAmelCase = 42
class a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
__UpperCAmelCase = 42
__UpperCAmelCase = 42
class a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
__UpperCAmelCase = 42
class a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
__UpperCAmelCase = 42
class a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
@staticmethod
def __magic_name__ ( snake_case_ : ArgumentParser ):
'''simple docstring'''
snake_case__ : Optional[Any] = parser.add_parser(
'''serve''' , help='''CLI tool to run inference requests through REST and GraphQL endpoints.''' )
serve_parser.add_argument(
'''--task''' , type=snake_case_ , choices=get_supported_tasks() , help='''The task to run the pipeline on''' , )
serve_parser.add_argument('''--host''' , type=snake_case_ , default='''localhost''' , help='''Interface the server will listen on.''' )
serve_parser.add_argument('''--port''' , type=snake_case_ , default=8_8_8_8 , help='''Port the serving will listen to.''' )
serve_parser.add_argument('''--workers''' , type=snake_case_ , default=1 , help='''Number of http workers''' )
serve_parser.add_argument('''--model''' , type=snake_case_ , help='''Model\'s name or path to stored model.''' )
serve_parser.add_argument('''--config''' , type=snake_case_ , help='''Model\'s config name or path to stored model.''' )
serve_parser.add_argument('''--tokenizer''' , type=snake_case_ , help='''Tokenizer name to use.''' )
serve_parser.add_argument(
'''--device''' , type=snake_case_ , default=-1 , help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)''' , )
serve_parser.set_defaults(func=snake_case_ )
def __init__( self : Union[str, Any] , snake_case_ : Pipeline , snake_case_ : str , snake_case_ : int , snake_case_ : int ):
'''simple docstring'''
snake_case__ : Any = pipeline
snake_case__ : Tuple = host
snake_case__ : Optional[Any] = port
snake_case__ : Tuple = workers
if not _serve_dependencies_installed:
raise RuntimeError(
'''Using serve command requires FastAPI and uvicorn. '''
'''Please install transformers with [serving]: pip install "transformers[serving]".'''
'''Or install FastAPI and uvicorn separately.''' )
else:
logger.info(F"""Serving model over {host}:{port}""" )
snake_case__ : str = FastAPI(
routes=[
APIRoute(
'''/''' , self.model_info , response_model=snake_case_ , response_class=snake_case_ , methods=['''GET'''] , ),
APIRoute(
'''/tokenize''' , self.tokenize , response_model=snake_case_ , response_class=snake_case_ , methods=['''POST'''] , ),
APIRoute(
'''/detokenize''' , self.detokenize , response_model=snake_case_ , response_class=snake_case_ , methods=['''POST'''] , ),
APIRoute(
'''/forward''' , self.forward , response_model=snake_case_ , response_class=snake_case_ , methods=['''POST'''] , ),
] , timeout=6_0_0 , )
def __magic_name__ ( self : str ):
'''simple docstring'''
run(self._app , host=self.host , port=self.port , workers=self.workers )
def __magic_name__ ( self : Optional[Any] ):
'''simple docstring'''
return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) )
def __magic_name__ ( self : List[str] , snake_case_ : str = Body(snake_case_ , embed=snake_case_ ) , snake_case_ : bool = Body(snake_case_ , embed=snake_case_ ) ):
'''simple docstring'''
try:
snake_case__ : Optional[Any] = self._pipeline.tokenizer.tokenize(snake_case_ )
if return_ids:
snake_case__ : Optional[int] = self._pipeline.tokenizer.convert_tokens_to_ids(snake_case_ )
return ServeTokenizeResult(tokens=snake_case_ , tokens_ids=snake_case_ )
else:
return ServeTokenizeResult(tokens=snake_case_ )
except Exception as e:
raise HTTPException(status_code=5_0_0 , detail={'''model''': '''''', '''error''': str(snake_case_ )} )
def __magic_name__ ( self : List[Any] , snake_case_ : List[int] = Body(snake_case_ , embed=snake_case_ ) , snake_case_ : bool = Body(snake_case_ , embed=snake_case_ ) , snake_case_ : bool = Body(snake_case_ , embed=snake_case_ ) , ):
'''simple docstring'''
try:
snake_case__ : Optional[int] = self._pipeline.tokenizer.decode(snake_case_ , snake_case_ , snake_case_ )
return ServeDeTokenizeResult(model='''''' , text=snake_case_ )
except Exception as e:
raise HTTPException(status_code=5_0_0 , detail={'''model''': '''''', '''error''': str(snake_case_ )} )
async def __magic_name__ ( self : Tuple , snake_case_ : List[str]=Body(snake_case_ , embed=snake_case_ ) ):
'''simple docstring'''
if len(snake_case_ ) == 0:
return ServeForwardResult(output=[] , attention=[] )
try:
# Forward through the model
snake_case__ : Tuple = self._pipeline(snake_case_ )
return ServeForwardResult(output=snake_case_ )
except Exception as e:
raise HTTPException(5_0_0 , {'''error''': str(snake_case_ )} )
| 502 | 1 |
import warnings
from ...utils import logging
from .image_processing_flava import FlavaImageProcessor
__A : str = logging.get_logger(__name__)
class _SCREAMING_SNAKE_CASE ( __snake_case ):
'''simple docstring'''
def __init__( self : List[str] , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : List[Any] ):
warnings.warn(
"The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
" use FlavaImageProcessor instead." , __lowerCamelCase , )
super().__init__(*__lowerCamelCase , **__lowerCamelCase ) | 16 |
def __a ( A__ : int ):
if not isinstance(A__ , A__ ):
raise ValueError("Input must be an integer" )
if input_num <= 0:
raise ValueError("Input must be positive" )
return sum(
divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 16 | 1 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging
A__ : List[str] = logging.get_logger(__name__)
A__ : List[Any] = '▁'
A__ : Any = {'vocab_file': 'sentencepiece.bpe.model'}
A__ : List[Any] = {
'vocab_file': {
'facebook/mbart-large-en-ro': (
'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model'
),
'facebook/mbart-large-cc25': (
'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model'
),
}
}
A__ : int = {
'facebook/mbart-large-en-ro': 1_024,
'facebook/mbart-large-cc25': 1_024,
}
# fmt: off
A__ : Tuple = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN']
class lowercase__ ( snake_case__ ):
_UpperCAmelCase :int = VOCAB_FILES_NAMES
_UpperCAmelCase :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_UpperCAmelCase :str = PRETRAINED_VOCAB_FILES_MAP
_UpperCAmelCase :Optional[Any] = ["input_ids", "attention_mask"]
_UpperCAmelCase :List[int] = []
_UpperCAmelCase :List[int] = []
def __init__( self : Any , snake_case__ : List[str] , snake_case__ : Union[str, Any]="<s>" , snake_case__ : List[Any]="</s>" , snake_case__ : Any="</s>" , snake_case__ : Optional[int]="<s>" , snake_case__ : Dict="<unk>" , snake_case__ : Optional[Any]="<pad>" , snake_case__ : Union[str, Any]="<mask>" , snake_case__ : Dict=None , snake_case__ : int=None , snake_case__ : List[str]=None , snake_case__ : Optional[Dict[str, Any]] = None , snake_case__ : Optional[int]=None , **snake_case__ : Optional[Any] , ):
# Mask token behave like a normal word, i.e. include the space before it
lowerCamelCase_ : Union[str, Any] =AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else mask_token
lowerCamelCase_ : int ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=snake_case__ , eos_token=snake_case__ , unk_token=snake_case__ , sep_token=snake_case__ , cls_token=snake_case__ , pad_token=snake_case__ , mask_token=snake_case__ , tokenizer_file=snake_case__ , src_lang=snake_case__ , tgt_lang=snake_case__ , additional_special_tokens=snake_case__ , sp_model_kwargs=self.sp_model_kwargs , **snake_case__ , )
lowerCamelCase_ : Optional[int] =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(snake_case__ ) )
lowerCamelCase_ : Optional[int] =vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
# Mimic fairseq token-to-id alignment for the first 4 token
lowerCamelCase_ : List[Any] ={"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
lowerCamelCase_ : Dict =1
lowerCamelCase_ : Union[str, Any] =len(self.sp_model )
lowerCamelCase_ : List[str] ={
code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(snake_case__ )
}
lowerCamelCase_ : Optional[int] ={v: k for k, v in self.lang_code_to_id.items()}
lowerCamelCase_ : Dict =len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset
self.fairseq_tokens_to_ids.update(self.lang_code_to_id )
lowerCamelCase_ : Any ={v: k for k, v in self.fairseq_tokens_to_ids.items()}
lowerCamelCase_ : Optional[int] =list(self.lang_code_to_id.keys() )
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
self._additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in self._additional_special_tokens] )
lowerCamelCase_ : Dict =src_lang if src_lang is not None else "en_XX"
lowerCamelCase_ : Dict =self.lang_code_to_id[self._src_lang]
lowerCamelCase_ : Tuple =tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
def __getstate__( self : Union[str, Any] ):
lowerCamelCase_ : Tuple =self.__dict__.copy()
lowerCamelCase_ : int =None
lowerCamelCase_ : int =self.sp_model.serialized_model_proto()
return state
def __setstate__( self : List[Any] , snake_case__ : List[str] ):
lowerCamelCase_ : Any =d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
lowerCamelCase_ : List[Any] ={}
lowerCamelCase_ : List[str] =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
@property
def UpperCAmelCase__ ( self : Optional[int] ):
return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token
@property
def UpperCAmelCase__ ( self : Optional[int] ):
return self._src_lang
@src_lang.setter
def UpperCAmelCase__ ( self : Any , snake_case__ : str ):
lowerCamelCase_ : List[str] =new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def UpperCAmelCase__ ( self : Optional[Any] , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None , snake_case__ : bool = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=snake_case__ , token_ids_a=snake_case__ , already_has_special_tokens=snake_case__ )
lowerCamelCase_ : str =[1] * len(self.prefix_tokens )
lowerCamelCase_ : Any =[1] * len(self.suffix_tokens )
if token_ids_a is None:
return prefix_ones + ([0] * len(snake_case__ )) + suffix_ones
return prefix_ones + ([0] * len(snake_case__ )) + ([0] * len(snake_case__ )) + suffix_ones
def UpperCAmelCase__ ( self : Union[str, Any] , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None ):
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def UpperCAmelCase__ ( self : List[Any] , snake_case__ : List[int] , snake_case__ : Optional[List[int]] = None ):
lowerCamelCase_ : Union[str, Any] =[self.sep_token_id]
lowerCamelCase_ : str =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def UpperCAmelCase__ ( self : Tuple , snake_case__ : Optional[int] , snake_case__ : str , snake_case__ : Optional[str] , snake_case__ : Optional[str] , **snake_case__ : Any ):
if src_lang is None or tgt_lang is None:
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
lowerCamelCase_ : str =src_lang
lowerCamelCase_ : str =self(snake_case__ , add_special_tokens=snake_case__ , return_tensors=snake_case__ , **snake_case__ )
lowerCamelCase_ : Any =self.convert_tokens_to_ids(snake_case__ )
lowerCamelCase_ : Optional[int] =tgt_lang_id
return inputs
def UpperCAmelCase__ ( self : List[Any] ):
lowerCamelCase_ : Dict ={self.convert_ids_to_tokens(snake_case__ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def UpperCAmelCase__ ( self : int , snake_case__ : str ):
return self.sp_model.encode(snake_case__ , out_type=snake_case__ )
def UpperCAmelCase__ ( self : int , snake_case__ : Dict ):
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
lowerCamelCase_ : Union[str, Any] =self.sp_model.PieceToId(snake_case__ )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def UpperCAmelCase__ ( self : Any , snake_case__ : Optional[int] ):
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def UpperCAmelCase__ ( self : List[str] , snake_case__ : Optional[Any] ):
lowerCamelCase_ : str ="".join(snake_case__ ).replace(snake_case__ , " " ).strip()
return out_string
def UpperCAmelCase__ ( self : Union[str, Any] , snake_case__ : str , snake_case__ : Optional[str] = None ):
if not os.path.isdir(snake_case__ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
lowerCamelCase_ : str =os.path.join(
snake_case__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case__ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , snake_case__ )
elif not os.path.isfile(self.vocab_file ):
with open(snake_case__ , "wb" ) as fi:
lowerCamelCase_ : Tuple =self.sp_model.serialized_model_proto()
fi.write(snake_case__ )
return (out_vocab_file,)
def UpperCAmelCase__ ( self : Tuple , snake_case__ : List[str] , snake_case__ : str = "en_XX" , snake_case__ : Optional[List[str]] = None , snake_case__ : str = "ro_RO" , **snake_case__ : List[str] , ):
lowerCamelCase_ : Optional[int] =src_lang
lowerCamelCase_ : Any =tgt_lang
return super().prepare_seqaseq_batch(snake_case__ , snake_case__ , **snake_case__ )
def UpperCAmelCase__ ( self : List[str] ):
return self.set_src_lang_special_tokens(self.src_lang )
def UpperCAmelCase__ ( self : Dict ):
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def UpperCAmelCase__ ( self : List[Any] , snake_case__ : List[Any] ):
lowerCamelCase_ : Dict =self.lang_code_to_id[src_lang]
lowerCamelCase_ : Dict =[]
lowerCamelCase_ : List[str] =[self.eos_token_id, self.cur_lang_code]
def UpperCAmelCase__ ( self : int , snake_case__ : str ):
lowerCamelCase_ : Union[str, Any] =self.lang_code_to_id[lang]
lowerCamelCase_ : int =[]
lowerCamelCase_ : Optional[Any] =[self.eos_token_id, self.cur_lang_code]
| 244 |
"""simple docstring"""
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class lowercase__ ( snake_case__ ):
_UpperCAmelCase :Tuple = ["image_processor", "tokenizer"]
_UpperCAmelCase :Dict = "LayoutLMv3ImageProcessor"
_UpperCAmelCase :Any = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast")
def __init__( self : List[Any] , snake_case__ : str=None , snake_case__ : int=None , **snake_case__ : Dict ):
lowerCamelCase_ : List[str] =None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , snake_case__ , )
lowerCamelCase_ : List[str] =kwargs.pop("feature_extractor" )
lowerCamelCase_ : Union[str, Any] =image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError("You need to specify an `image_processor`." )
if tokenizer is None:
raise ValueError("You need to specify a `tokenizer`." )
super().__init__(snake_case__ , snake_case__ )
def __call__( self : Optional[Any] , snake_case__ : Any , snake_case__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , snake_case__ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , snake_case__ : Union[List[List[int]], List[List[List[int]]]] = None , snake_case__ : Optional[Union[List[int], List[List[int]]]] = None , snake_case__ : bool = True , snake_case__ : Union[bool, str, PaddingStrategy] = False , snake_case__ : Union[bool, str, TruncationStrategy] = None , snake_case__ : Optional[int] = None , snake_case__ : int = 0 , snake_case__ : Optional[int] = None , snake_case__ : Optional[bool] = None , snake_case__ : Optional[bool] = None , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = False , snake_case__ : bool = True , snake_case__ : Optional[Union[str, TensorType]] = None , **snake_case__ : int , ):
# verify input
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
"You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True." )
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
"You cannot provide word labels if you initialized the image processor with apply_ocr set to True." )
# first, apply the image processor
lowerCamelCase_ : Dict =self.image_processor(images=snake_case__ , return_tensors=snake_case__ )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(snake_case__ , snake_case__ ):
lowerCamelCase_ : List[Any] =[text] # add batch dimension (as the image processor always adds a batch dimension)
lowerCamelCase_ : List[str] =features["words"]
lowerCamelCase_ : List[str] =self.tokenizer(
text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=snake_case__ , add_special_tokens=snake_case__ , padding=snake_case__ , truncation=snake_case__ , max_length=snake_case__ , stride=snake_case__ , pad_to_multiple_of=snake_case__ , return_token_type_ids=snake_case__ , return_attention_mask=snake_case__ , return_overflowing_tokens=snake_case__ , return_special_tokens_mask=snake_case__ , return_offsets_mapping=snake_case__ , return_length=snake_case__ , verbose=snake_case__ , return_tensors=snake_case__ , **snake_case__ , )
# add pixel values
lowerCamelCase_ : str =features.pop("pixel_values" )
if return_overflowing_tokens is True:
lowerCamelCase_ : Tuple =self.get_overflowing_images(snake_case__ , encoded_inputs["overflow_to_sample_mapping"] )
lowerCamelCase_ : Dict =images
return encoded_inputs
def UpperCAmelCase__ ( self : List[str] , snake_case__ : Union[str, Any] , snake_case__ : Any ):
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
lowerCamelCase_ : Optional[int] =[]
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(snake_case__ ) != len(snake_case__ ):
raise ValueError(
"Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
F""" {len(snake_case__ )} and {len(snake_case__ )}""" )
return images_with_overflow
def UpperCAmelCase__ ( self : str , *snake_case__ : List[str] , **snake_case__ : List[str] ):
return self.tokenizer.batch_decode(*snake_case__ , **snake_case__ )
def UpperCAmelCase__ ( self : List[Any] , *snake_case__ : Tuple , **snake_case__ : Any ):
return self.tokenizer.decode(*snake_case__ , **snake_case__ )
@property
def UpperCAmelCase__ ( self : Optional[Any] ):
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def UpperCAmelCase__ ( self : Union[str, Any] ):
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , snake_case__ , )
return self.image_processor_class
@property
def UpperCAmelCase__ ( self : List[Any] ):
warnings.warn(
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , snake_case__ , )
return self.image_processor
| 244 | 1 |
"""simple docstring"""
from itertools import product
def lowercase__ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> list[int]:
'''simple docstring'''
a__ : Optional[Any] = sides_number
a__ : Tuple = max_face_number * dice_number
a__ : Any = [0] * (max_total + 1)
a__ : Optional[int] = 1
a__ : Optional[int] = range(lowerCAmelCase__ , max_face_number + 1 )
for dice_numbers in product(lowerCAmelCase__ , repeat=lowerCAmelCase__ ):
a__ : str = sum(lowerCAmelCase__ )
totals_frequencies[total] += 1
return totals_frequencies
def lowercase__ ( ) -> float:
'''simple docstring'''
a__ : Optional[Any] = total_frequency_distribution(
sides_number=4 , dice_number=9 )
a__ : List[str] = total_frequency_distribution(
sides_number=6 , dice_number=6 )
a__ : Union[str, Any] = 0
a__ : Dict = 9
a__ : Union[str, Any] = 4 * 9
a__ : List[Any] = 6
for peter_total in range(lowerCAmelCase__ , max_peter_total + 1 ):
peter_wins_count += peter_totals_frequencies[peter_total] * sum(
colin_totals_frequencies[min_colin_total:peter_total] )
a__ : Any = (4**9) * (6**6)
a__ : Union[str, Any] = peter_wins_count / total_games_number
a__ : Union[str, Any] = round(lowerCAmelCase__ , ndigits=7 )
return rounded_peter_win_probability
if __name__ == "__main__":
print(f"{solution() = }") | 642 |
"""simple docstring"""
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 __UpperCAmelCase ( _UpperCamelCase , unittest.TestCase ):
__lowerCamelCase : List[Any] = "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"
def UpperCAmelCase ( self : str , a_ : Optional[Any]=0 ) -> Union[str, Any]:
'''simple docstring'''
a__ : Union[str, Any] = np.random.RandomState(a_ )
a__ : List[Any] = {
"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 UpperCAmelCase ( self : Dict ) -> Optional[Any]:
'''simple docstring'''
a__ : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = self.get_dummy_inputs()
a__ : Union[str, Any] = pipe(**a_ ).images
a__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : List[str] = np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : List[str] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=a_ )
pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = self.get_dummy_inputs()
a__ : List[Any] = pipe(**a_ ).images
a__ : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : List[str] = np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Tuple ) -> Tuple:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : Tuple = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : List[Any] = self.get_dummy_inputs()
a__ : Optional[Any] = pipe(**a_ ).images
a__ : int = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : Dict = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Optional[Any] ) -> Dict:
'''simple docstring'''
a__ : Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : Dict = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = self.get_dummy_inputs()
a__ : int = pipe(**a_ ).images
a__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : str = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Union[str, Any] ) -> str:
'''simple docstring'''
a__ : str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : Dict = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : Any = self.get_dummy_inputs()
a__ : List[str] = pipe(**a_ ).images
a__ : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : Any = np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Tuple ) -> Any:
'''simple docstring'''
a__ : str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : Tuple = self.get_dummy_inputs()
a__ : List[str] = pipe(**a_ ).images
a__ : Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : Any = np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : str ) -> Tuple:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=a_ )
a__ : Any = self.get_dummy_inputs()
a__ : Any = 3 * [inputs["prompt"]]
# forward
a__ : Union[str, Any] = pipe(**a_ )
a__ : int = output.images[0, -3:, -3:, -1]
a__ : Union[str, Any] = self.get_dummy_inputs()
a__ : List[Any] = 3 * [inputs.pop("prompt" )]
a__ : Optional[Any] = pipe.tokenizer(
a_ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=a_ , return_tensors="np" , )
a__ : List[str] = text_inputs["input_ids"]
a__ : int = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0]
a__ : List[Any] = prompt_embeds
# forward
a__ : List[Any] = pipe(**a_ )
a__ : List[str] = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
def UpperCAmelCase ( self : Dict ) -> Optional[int]:
'''simple docstring'''
a__ : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=a_ )
a__ : Tuple = self.get_dummy_inputs()
a__ : Dict = 3 * ["this is a negative prompt"]
a__ : Optional[Any] = negative_prompt
a__ : Any = 3 * [inputs["prompt"]]
# forward
a__ : str = pipe(**a_ )
a__ : List[str] = output.images[0, -3:, -3:, -1]
a__ : Union[str, Any] = self.get_dummy_inputs()
a__ : Union[str, Any] = 3 * [inputs.pop("prompt" )]
a__ : List[Any] = []
for p in [prompt, negative_prompt]:
a__ : int = pipe.tokenizer(
a_ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=a_ , return_tensors="np" , )
a__ : Any = text_inputs["input_ids"]
embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] )
a__ , a__ : Union[str, Any] = embeds
# forward
a__ : Dict = pipe(**a_ )
a__ : Any = 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 __UpperCAmelCase ( unittest.TestCase ):
@property
def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCAmelCase ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
a__ : List[str] = ort.SessionOptions()
a__ : List[str] = False
return options
def UpperCAmelCase ( self : Optional[int] ) -> List[Any]:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = "A painting of a squirrel eating a burger"
np.random.seed(0 )
a__ : Dict = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" )
a__ : Any = output.images
a__ : Optional[int] = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
a__ : str = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
a__ : Any = DDIMScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
a__ : str = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=a_ , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=a_ )
a__ : str = "open neural network exchange"
a__ : Tuple = np.random.RandomState(0 )
a__ : Dict = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=a_ , output_type="np" )
a__ : Dict = output.images
a__ : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
a__ : Dict = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase ( self : Optional[int] ) -> Dict:
'''simple docstring'''
a__ : List[Any] = LMSDiscreteScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
a__ : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=a_ , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=a_ )
a__ : Any = "open neural network exchange"
a__ : Optional[Any] = np.random.RandomState(0 )
a__ : Optional[int] = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=a_ , output_type="np" )
a__ : int = output.images
a__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
a__ : Dict = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase ( self : int ) -> Optional[Any]:
'''simple docstring'''
a__ : List[str] = 0
def test_callback_fn(a_ : int , a_ : int , a_ : np.ndarray ) -> None:
a__ : Optional[int] = True
nonlocal number_of_steps
number_of_steps += 1
if step == 0:
assert latents.shape == (1, 4, 64, 64)
a__ : Any = latents[0, -3:, -3:, -1]
a__ : Union[str, Any] = np.array(
[-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
elif step == 5:
assert latents.shape == (1, 4, 64, 64)
a__ : Union[str, Any] = latents[0, -3:, -3:, -1]
a__ : Optional[int] = np.array(
[-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
a__ : Tuple = False
a__ : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=a_ )
a__ : List[Any] = "Andromeda galaxy in a bottle"
a__ : str = np.random.RandomState(0 )
pipe(
prompt=a_ , num_inference_steps=5 , guidance_scale=7.5 , generator=a_ , callback=a_ , callback_steps=1 , )
assert test_callback_fn.has_been_called
assert number_of_steps == 6
def UpperCAmelCase ( self : Tuple ) -> List[str]:
'''simple docstring'''
a__ : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
assert isinstance(a_ , a_ )
assert pipe.safety_checker is None
a__ : Tuple = 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(a_ )
a__ : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(a_ )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
a__ : Dict = pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None | 642 | 1 |
"""simple docstring"""
import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional
from torch.utils.data import ConcatDataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_WITH_LM_HEAD_MAPPING,
AutoConfig,
AutoModelWithLMHead,
AutoTokenizer,
DataCollatorForLanguageModeling,
DataCollatorForPermutationLanguageModeling,
DataCollatorForWholeWordMask,
HfArgumentParser,
LineByLineTextDataset,
LineByLineWithRefDataset,
PreTrainedTokenizer,
TextDataset,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.trainer_utils import is_main_process
lowerCamelCase__ = logging.getLogger(__name__)
lowerCamelCase__ = list(MODEL_WITH_LM_HEAD_MAPPING.keys())
lowerCamelCase__ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class __SCREAMING_SNAKE_CASE :
'''simple docstring'''
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={
"help": (
"The model checkpoint for weights initialization. Leave None if you want to train a model from"
" scratch."
)
} , )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_UpperCamelCase )} , )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"} )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , )
@dataclass
class __SCREAMING_SNAKE_CASE :
'''simple docstring'''
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "The input training data file (a text file)."} )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={
"help": (
"The input training data files (multiple files in glob format). "
"Very often splitting large files to smaller files can prevent tokenizer going out of memory"
)
} , )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "An optional input train ref data file for whole word mask in Chinese."} , )
SCREAMING_SNAKE_CASE__ :Optional[str] = field(
default=_UpperCamelCase , metadata={"help": "An optional input eval ref data file for whole word mask in Chinese."} , )
SCREAMING_SNAKE_CASE__ :bool = field(
default=_UpperCamelCase , metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."} , )
SCREAMING_SNAKE_CASE__ :bool = field(
default=_UpperCamelCase , metadata={"help": "Train with masked-language modeling loss instead of language modeling."} )
SCREAMING_SNAKE_CASE__ :bool = field(default=_UpperCamelCase , metadata={"help": "Whether ot not to use whole word mask."} )
SCREAMING_SNAKE_CASE__ :float = field(
default=0.15 , metadata={"help": "Ratio of tokens to mask for masked language modeling loss"} )
SCREAMING_SNAKE_CASE__ :float = field(
default=1 / 6 , metadata={
"help": (
"Ratio of length of a span of masked tokens to surrounding context length for permutation language"
" modeling."
)
} , )
SCREAMING_SNAKE_CASE__ :int = field(
default=5 , metadata={"help": "Maximum length of a span of masked tokens for permutation language modeling."} )
SCREAMING_SNAKE_CASE__ :int = field(
default=-1 , metadata={
"help": (
"Optional input sequence length after tokenization."
"The training dataset will be truncated in block of this size for training."
"Default to the model max input length for single sentence inputs (take into account special tokens)."
)
} , )
SCREAMING_SNAKE_CASE__ :bool = field(
default=_UpperCamelCase , metadata={"help": "Overwrite the cached training and evaluation sets"} )
def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ = False ,lowercase_ = None ,) -> List[str]:
"""simple docstring"""
def _dataset(lowercase_ ,lowercase_=None ):
if args.line_by_line:
if ref_path is not None:
if not args.whole_word_mask or not args.mlm:
raise ValueError("You need to set world whole masking and mlm to True for Chinese Whole Word Mask" )
return LineByLineWithRefDataset(
tokenizer=lowercase_ ,file_path=lowercase_ ,block_size=args.block_size ,ref_path=lowercase_ ,)
return LineByLineTextDataset(tokenizer=lowercase_ ,file_path=lowercase_ ,block_size=args.block_size )
else:
return TextDataset(
tokenizer=lowercase_ ,file_path=lowercase_ ,block_size=args.block_size ,overwrite_cache=args.overwrite_cache ,cache_dir=lowercase_ ,)
if evaluate:
return _dataset(args.eval_data_file ,args.eval_ref_file )
elif args.train_data_files:
return ConcatDataset([_dataset(lowercase_ ) for f in glob(args.train_data_files )] )
else:
return _dataset(args.train_data_file ,args.train_ref_file )
def lowercase__ ( ) -> int:
"""simple docstring"""
_UpperCamelCase : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
_UpperCamelCase : int = parser.parse_args_into_dataclasses()
if data_args.eval_data_file is None and training_args.do_eval:
raise ValueError(
"Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file "
"or remove the --do_eval argument." )
if (
os.path.exists(training_args.output_dir )
and os.listdir(training_args.output_dir )
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
" --overwrite_output_dir to overcome." )
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" ,datefmt="%m/%d/%Y %H:%M:%S" ,level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN ,)
logger.warning(
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" ,training_args.local_rank ,training_args.device ,training_args.n_gpu ,bool(training_args.local_rank != -1 ) ,training_args.fpaa ,)
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
logger.info("Training/evaluation parameters %s" ,lowercase_ )
# Set seed
set_seed(training_args.seed )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
if model_args.config_name:
_UpperCamelCase : Optional[int] = AutoConfig.from_pretrained(model_args.config_name ,cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
_UpperCamelCase : List[Any] = AutoConfig.from_pretrained(model_args.model_name_or_path ,cache_dir=model_args.cache_dir )
else:
_UpperCamelCase : Dict = CONFIG_MAPPING[model_args.model_type]()
logger.warning("You are instantiating a new config instance from scratch." )
if model_args.tokenizer_name:
_UpperCamelCase : int = AutoTokenizer.from_pretrained(model_args.tokenizer_name ,cache_dir=model_args.cache_dir )
elif model_args.model_name_or_path:
_UpperCamelCase : Optional[Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path ,cache_dir=model_args.cache_dir )
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another"
" script, save it,and load it from here, using --tokenizer_name" )
if model_args.model_name_or_path:
_UpperCamelCase : List[Any] = AutoModelWithLMHead.from_pretrained(
model_args.model_name_or_path ,from_tf=bool(".ckpt" in model_args.model_name_or_path ) ,config=lowercase_ ,cache_dir=model_args.cache_dir ,)
else:
logger.info("Training new model from scratch" )
_UpperCamelCase : List[Any] = AutoModelWithLMHead.from_config(lowercase_ )
model.resize_token_embeddings(len(lowercase_ ) )
if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
raise ValueError(
"BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the"
"--mlm flag (masked language modeling)." )
if data_args.block_size <= 0:
_UpperCamelCase : Dict = tokenizer.max_len
# Our input block size will be the max possible for the model
else:
_UpperCamelCase : Union[str, Any] = min(data_args.block_size ,tokenizer.max_len )
# Get datasets
_UpperCamelCase : int = (
get_dataset(lowercase_ ,tokenizer=lowercase_ ,cache_dir=model_args.cache_dir ) if training_args.do_train else None
)
_UpperCamelCase : int = (
get_dataset(lowercase_ ,tokenizer=lowercase_ ,evaluate=lowercase_ ,cache_dir=model_args.cache_dir )
if training_args.do_eval
else None
)
if config.model_type == "xlnet":
_UpperCamelCase : Dict = DataCollatorForPermutationLanguageModeling(
tokenizer=lowercase_ ,plm_probability=data_args.plm_probability ,max_span_length=data_args.max_span_length ,)
else:
if data_args.mlm and data_args.whole_word_mask:
_UpperCamelCase : Optional[Any] = DataCollatorForWholeWordMask(
tokenizer=lowercase_ ,mlm_probability=data_args.mlm_probability )
else:
_UpperCamelCase : Union[str, Any] = DataCollatorForLanguageModeling(
tokenizer=lowercase_ ,mlm=data_args.mlm ,mlm_probability=data_args.mlm_probability )
# Initialize our Trainer
_UpperCamelCase : str = Trainer(
model=lowercase_ ,args=lowercase_ ,data_collator=lowercase_ ,train_dataset=lowercase_ ,eval_dataset=lowercase_ ,prediction_loss_only=lowercase_ ,)
# Training
if training_args.do_train:
_UpperCamelCase : Tuple = (
model_args.model_name_or_path
if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path )
else None
)
trainer.train(model_path=lowercase_ )
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
_UpperCamelCase : int = {}
if training_args.do_eval:
logger.info("*** Evaluate ***" )
_UpperCamelCase : Union[str, Any] = trainer.evaluate()
_UpperCamelCase : Dict = math.exp(eval_output["eval_loss"] )
_UpperCamelCase : int = {"perplexity": perplexity}
_UpperCamelCase : int = os.path.join(training_args.output_dir ,"eval_results_lm.txt" )
if trainer.is_world_master():
with open(lowercase_ ,"w" ) as writer:
logger.info("***** Eval results *****" )
for key in sorted(result.keys() ):
logger.info(" %s = %s" ,lowercase_ ,str(result[key] ) )
writer.write("%s = %s\n" % (key, str(result[key] )) )
results.update(lowercase_ )
return results
def lowercase__ ( lowercase_ ) -> Optional[int]:
"""simple docstring"""
main()
if __name__ == "__main__":
main()
| 706 |
"""simple docstring"""
import json
import os
import unittest
from transformers.models.roc_bert.tokenization_roc_bert import (
VOCAB_FILES_NAMES,
RoCBertBasicTokenizer,
RoCBertTokenizer,
RoCBertWordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ :Union[str, Any] = RoCBertTokenizer
SCREAMING_SNAKE_CASE__ :Dict = None
SCREAMING_SNAKE_CASE__ :List[Any] = False
SCREAMING_SNAKE_CASE__ :Union[str, Any] = True
SCREAMING_SNAKE_CASE__ :Union[str, Any] = filter_non_english
def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict:
super().setUp()
_UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"]
_UpperCamelCase : List[str] = {}
_UpperCamelCase : Tuple = {}
for i, value in enumerate(__a ):
_UpperCamelCase : List[str] = i
_UpperCamelCase : Optional[Any] = i
_UpperCamelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_UpperCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] )
_UpperCamelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer:
json.dump(__a , __a , ensure_ascii=__a )
with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer:
json.dump(__a , __a , ensure_ascii=__a )
def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]:
_UpperCamelCase : Tuple = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
_UpperCamelCase : int = tokenizer.tokenize("你好[SEP]你是谁" )
self.assertListEqual(__a , ["你", "好", "[SEP]", "你", "是", "谁"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__a ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__a ) , [5, 6, 2, 5, 7, 8] )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict:
_UpperCamelCase : Dict = RoCBertBasicTokenizer()
self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] )
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any:
_UpperCamelCase : List[Any] = RoCBertBasicTokenizer(do_lower_case=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple:
_UpperCamelCase : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=__a , strip_accents=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> str:
_UpperCamelCase : Dict = RoCBertBasicTokenizer(do_lower_case=__a , strip_accents=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Union[str, Any]:
_UpperCamelCase : List[str] = RoCBertBasicTokenizer(do_lower_case=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] )
self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] )
def __SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]:
_UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] )
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]:
_UpperCamelCase : Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=__a , strip_accents=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] )
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> List[Any]:
_UpperCamelCase : Tuple = RoCBertBasicTokenizer(do_lower_case=__a , strip_accents=__a )
self.assertListEqual(
tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] )
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int:
_UpperCamelCase : int = RoCBertBasicTokenizer(do_lower_case=__a , never_split=["[UNK]"] )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] )
def __SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]:
_UpperCamelCase : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"]
_UpperCamelCase : Any = {}
for i, token in enumerate(__a ):
_UpperCamelCase : str = i
_UpperCamelCase : Optional[int] = RoCBertWordpieceTokenizer(vocab=__a , unk_token="[UNK]" )
self.assertListEqual(tokenizer.tokenize("" ) , [] )
self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] )
self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]:
self.assertTrue(_is_whitespace(" " ) )
self.assertTrue(_is_whitespace("\t" ) )
self.assertTrue(_is_whitespace("\r" ) )
self.assertTrue(_is_whitespace("\n" ) )
self.assertTrue(_is_whitespace("\u00A0" ) )
self.assertFalse(_is_whitespace("A" ) )
self.assertFalse(_is_whitespace("-" ) )
def __SCREAMING_SNAKE_CASE ( self : Any ) -> Dict:
self.assertTrue(_is_control("\u0005" ) )
self.assertFalse(_is_control("A" ) )
self.assertFalse(_is_control(" " ) )
self.assertFalse(_is_control("\t" ) )
self.assertFalse(_is_control("\r" ) )
def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]:
self.assertTrue(_is_punctuation("-" ) )
self.assertTrue(_is_punctuation("$" ) )
self.assertTrue(_is_punctuation("`" ) )
self.assertTrue(_is_punctuation("." ) )
self.assertFalse(_is_punctuation("A" ) )
self.assertFalse(_is_punctuation(" " ) )
def __SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]:
_UpperCamelCase : Optional[Any] = self.get_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] )
if self.test_rust_tokenizer:
_UpperCamelCase : Tuple = self.get_rust_tokenizer()
self.assertListEqual(
[rust_tokenizer.tokenize(__a ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] )
def __SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_UpperCamelCase : int = self.rust_tokenizer_class.from_pretrained(__a , **__a )
_UpperCamelCase : Union[str, Any] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'''
_UpperCamelCase : Optional[Any] = tokenizer_r.encode_plus(
__a , return_attention_mask=__a , return_token_type_ids=__a , return_offsets_mapping=__a , add_special_tokens=__a , )
_UpperCamelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__a , "do_lower_case" ) else False
_UpperCamelCase : Dict = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), "A"),
((1, 2), ","),
((3, 5), "na"),
((5, 6), "##ï"),
((6, 8), "##ve"),
((9, 15), tokenizer_r.mask_token),
((16, 21), "Allen"),
((21, 23), "##NL"),
((23, 24), "##P"),
((25, 33), "sentence"),
((33, 34), "."),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), "a"),
((1, 2), ","),
((3, 8), "naive"),
((9, 15), tokenizer_r.mask_token),
((16, 21), "allen"),
((21, 23), "##nl"),
((23, 24), "##p"),
((25, 33), "sentence"),
((33, 34), "."),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) )
self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] )
def __SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]:
_UpperCamelCase : Optional[Any] = ["的", "人", "有"]
_UpperCamelCase : int = "".join(__a )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_UpperCamelCase : int = True
_UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a )
_UpperCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__a , **__a )
_UpperCamelCase : int = tokenizer_p.encode(__a , add_special_tokens=__a )
_UpperCamelCase : int = tokenizer_r.encode(__a , add_special_tokens=__a )
_UpperCamelCase : List[Any] = tokenizer_r.convert_ids_to_tokens(__a )
_UpperCamelCase : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(__a )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(__a , __a )
self.assertListEqual(__a , __a )
_UpperCamelCase : Any = False
_UpperCamelCase : Dict = self.rust_tokenizer_class.from_pretrained(__a , **__a )
_UpperCamelCase : Any = self.tokenizer_class.from_pretrained(__a , **__a )
_UpperCamelCase : Any = tokenizer_r.encode(__a , add_special_tokens=__a )
_UpperCamelCase : Any = tokenizer_p.encode(__a , add_special_tokens=__a )
_UpperCamelCase : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(__a )
_UpperCamelCase : Dict = tokenizer_p.convert_ids_to_tokens(__a )
# it is expected that only the first Chinese character is not preceded by "##".
_UpperCamelCase : Any = [
F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__a )
]
self.assertListEqual(__a , __a )
self.assertListEqual(__a , __a )
@slow
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any:
_UpperCamelCase : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
_UpperCamelCase : Optional[int] = tokenizer.encode("你好" , add_special_tokens=__a )
_UpperCamelCase : Dict = tokenizer.encode("你是谁" , add_special_tokens=__a )
_UpperCamelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__a )
_UpperCamelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__a , __a )
assert encoded_sentence == [1] + text + [2]
assert encoded_pair == [1] + text + [2] + text_a + [2]
def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> int:
_UpperCamelCase : Optional[Any] = self.get_tokenizers(do_lower_case=__a )
for tokenizer in tokenizers:
with self.subTest(F'''{tokenizer.__class__.__name__}''' ):
_UpperCamelCase : int = "你好,你是谁"
_UpperCamelCase : Any = tokenizer.tokenize(__a )
_UpperCamelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(__a )
_UpperCamelCase : List[str] = tokenizer.convert_tokens_to_shape_ids(__a )
_UpperCamelCase : Any = tokenizer.convert_tokens_to_pronunciation_ids(__a )
_UpperCamelCase : Optional[int] = tokenizer.prepare_for_model(
__a , __a , __a , add_special_tokens=__a )
_UpperCamelCase : Tuple = tokenizer.encode_plus(__a , add_special_tokens=__a )
self.assertEqual(__a , __a )
| 51 | 0 |
"""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.
from argparse import ArgumentParser
from accelerate.commands.config import get_config_parser
from accelerate.commands.env import env_command_parser
from accelerate.commands.launch import launch_command_parser
from accelerate.commands.test import test_command_parser
from accelerate.commands.tpu import tpu_command_parser
def __lowerCamelCase ( ) -> Optional[int]:
__SCREAMING_SNAKE_CASE :Any = ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE :Optional[Any] = parser.add_subparsers(help='''accelerate command helpers''' )
# Register commands
get_config_parser(subparsers=_lowerCAmelCase )
env_command_parser(subparsers=_lowerCAmelCase )
launch_command_parser(subparsers=_lowerCAmelCase )
tpu_command_parser(subparsers=_lowerCAmelCase )
test_command_parser(subparsers=_lowerCAmelCase )
# Let's go
__SCREAMING_SNAKE_CASE :int = parser.parse_args()
if not hasattr(_lowerCAmelCase , '''func''' ):
parser.print_help()
exit(1 )
# Run
args.func(_lowerCAmelCase )
if __name__ == "__main__":
main() | 498 |
from ... import PretrainedConfig
lowercase : Dict = {
"sijunhe/nezha-cn-base": "https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json",
}
class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ):
"""simple docstring"""
lowercase : List[str] = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP
lowercase : Union[str, Any] = 'nezha'
def __init__( self , __UpperCamelCase=2_11_28 , __UpperCamelCase=7_68 , __UpperCamelCase=12 , __UpperCamelCase=12 , __UpperCamelCase=30_72 , __UpperCamelCase="gelu" , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=5_12 , __UpperCamelCase=64 , __UpperCamelCase=2 , __UpperCamelCase=0.02 , __UpperCamelCase=1E-12 , __UpperCamelCase=0.1 , __UpperCamelCase=0 , __UpperCamelCase=2 , __UpperCamelCase=3 , __UpperCamelCase=True , **__UpperCamelCase , ) -> int:
'''simple docstring'''
super().__init__(pad_token_id=__UpperCamelCase , bos_token_id=__UpperCamelCase , eos_token_id=__UpperCamelCase , **__UpperCamelCase )
__UpperCamelCase : int = vocab_size
__UpperCamelCase : int = hidden_size
__UpperCamelCase : Tuple = num_hidden_layers
__UpperCamelCase : Tuple = num_attention_heads
__UpperCamelCase : Optional[int] = hidden_act
__UpperCamelCase : List[str] = intermediate_size
__UpperCamelCase : Union[str, Any] = hidden_dropout_prob
__UpperCamelCase : Tuple = attention_probs_dropout_prob
__UpperCamelCase : Optional[int] = max_position_embeddings
__UpperCamelCase : str = max_relative_position
__UpperCamelCase : List[str] = type_vocab_size
__UpperCamelCase : Dict = initializer_range
__UpperCamelCase : Optional[int] = layer_norm_eps
__UpperCamelCase : int = classifier_dropout
__UpperCamelCase : List[str] = use_cache | 327 | 0 |
from __future__ import annotations
def _A ( lowerCAmelCase_ : list[int | str] ):
"""simple docstring"""
create_state_space_tree(lowerCAmelCase_ , [] , 0 , [0 for i in range(len(lowerCAmelCase_ ) )] )
def _A ( lowerCAmelCase_ : list[int | str] , lowerCAmelCase_ : list[int | str] , lowerCAmelCase_ : int , lowerCAmelCase_ : list[int] , ):
"""simple docstring"""
if index == len(lowerCAmelCase_ ):
print(lowerCAmelCase_ )
return
for i in range(len(lowerCAmelCase_ ) ):
if not index_used[i]:
current_sequence.append(sequence[i] )
lowerCAmelCase__ = True
create_state_space_tree(lowerCAmelCase_ , lowerCAmelCase_ , index + 1 , lowerCAmelCase_ )
current_sequence.pop()
lowerCAmelCase__ = False
UpperCamelCase = [3, 1, 2, 4]
generate_all_permutations(sequence)
UpperCamelCase = ["A", "B", "C"]
generate_all_permutations(sequence_a)
| 125 |
import tempfile
import torch
from diffusers import PNDMScheduler
from .test_schedulers import SchedulerCommonTest
class __lowerCamelCase ( UpperCamelCase__ ):
"""simple docstring"""
snake_case__ = (PNDMScheduler,)
snake_case__ = (("num_inference_steps", 5_0),)
def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[int]:
lowerCAmelCase__ = {
"num_train_timesteps": 1_000,
"beta_start": 0.0_001,
"beta_end": 0.02,
"beta_schedule": "linear",
}
config.update(**SCREAMING_SNAKE_CASE__ )
return config
def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str=0 , **SCREAMING_SNAKE_CASE__ : int ) -> List[str]:
lowerCAmelCase__ = dict(self.forward_default_kwargs )
lowerCAmelCase__ = kwargs.pop("num_inference_steps" , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = self.dummy_sample
lowerCAmelCase__ = 0.1 * sample
lowerCAmelCase__ = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
for scheduler_class in self.scheduler_classes:
lowerCAmelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
# copy over dummy past residuals
lowerCAmelCase__ = dummy_past_residuals[:]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__ )
new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
# copy over dummy past residuals
lowerCAmelCase__ = dummy_past_residuals[:]
lowerCAmelCase__ = scheduler.step_prk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
lowerCAmelCase__ = new_scheduler.step_prk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
lowerCAmelCase__ = scheduler.step_plms(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
lowerCAmelCase__ = new_scheduler.step_plms(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def a ( self : Dict ) -> Any:
pass
def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , **SCREAMING_SNAKE_CASE__ : List[str] ) -> str:
lowerCAmelCase__ = dict(self.forward_default_kwargs )
lowerCAmelCase__ = kwargs.pop("num_inference_steps" , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = self.dummy_sample
lowerCAmelCase__ = 0.1 * sample
lowerCAmelCase__ = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
for scheduler_class in self.scheduler_classes:
lowerCAmelCase__ = self.get_scheduler_config()
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
# copy over dummy past residuals (must be after setting timesteps)
lowerCAmelCase__ = dummy_past_residuals[:]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = scheduler_class.from_pretrained(SCREAMING_SNAKE_CASE__ )
# copy over dummy past residuals
new_scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
# copy over dummy past residual (must be after setting timesteps)
lowerCAmelCase__ = dummy_past_residuals[:]
lowerCAmelCase__ = scheduler.step_prk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
lowerCAmelCase__ = new_scheduler.step_prk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
lowerCAmelCase__ = scheduler.step_plms(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
lowerCAmelCase__ = new_scheduler.step_plms(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical"
def a ( self : List[str] , **SCREAMING_SNAKE_CASE__ : int ) -> List[Any]:
lowerCAmelCase__ = self.scheduler_classes[0]
lowerCAmelCase__ = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = 10
lowerCAmelCase__ = self.dummy_model()
lowerCAmelCase__ = self.dummy_sample_deter
scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
for i, t in enumerate(scheduler.prk_timesteps ):
lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = scheduler.step_prk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample
for i, t in enumerate(scheduler.plms_timesteps ):
lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = scheduler.step_plms(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample
return sample
def a ( self : Optional[int] ) -> List[str]:
lowerCAmelCase__ = dict(self.forward_default_kwargs )
lowerCAmelCase__ = kwargs.pop("num_inference_steps" , SCREAMING_SNAKE_CASE__ )
for scheduler_class in self.scheduler_classes:
lowerCAmelCase__ = self.get_scheduler_config()
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = self.dummy_sample
lowerCAmelCase__ = 0.1 * sample
if num_inference_steps is not None and hasattr(SCREAMING_SNAKE_CASE__ , "set_timesteps" ):
scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
elif num_inference_steps is not None and not hasattr(SCREAMING_SNAKE_CASE__ , "set_timesteps" ):
lowerCAmelCase__ = num_inference_steps
# copy over dummy past residuals (must be done after set_timesteps)
lowerCAmelCase__ = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
lowerCAmelCase__ = dummy_past_residuals[:]
lowerCAmelCase__ = scheduler.step_prk(SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
lowerCAmelCase__ = scheduler.step_prk(SCREAMING_SNAKE_CASE__ , 1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
lowerCAmelCase__ = scheduler.step_plms(SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
lowerCAmelCase__ = scheduler.step_plms(SCREAMING_SNAKE_CASE__ , 1 , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample
self.assertEqual(output_a.shape , sample.shape )
self.assertEqual(output_a.shape , output_a.shape )
def a ( self : Tuple ) -> int:
for timesteps in [100, 1_000]:
self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ )
def a ( self : Tuple ) -> List[str]:
for steps_offset in [0, 1]:
self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE__ )
lowerCAmelCase__ = self.scheduler_classes[0]
lowerCAmelCase__ = self.get_scheduler_config(steps_offset=1 )
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
scheduler.set_timesteps(10 )
assert torch.equal(
scheduler.timesteps , torch.LongTensor(
[901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , )
def a ( self : List[str] ) -> Union[str, Any]:
for beta_start, beta_end in zip([0.0_001, 0.001] , [0.002, 0.02] ):
self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ )
def a ( self : Union[str, Any] ) -> Union[str, Any]:
for schedule in ["linear", "squaredcos_cap_v2"]:
self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ )
def a ( self : Any ) -> Union[str, Any]:
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ )
def a ( self : str ) -> Union[str, Any]:
for t in [1, 5, 10]:
self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ )
def a ( self : List[str] ) -> Union[str, Any]:
for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ):
self.check_over_forward(num_inference_steps=SCREAMING_SNAKE_CASE__ )
def a ( self : List[str] ) -> List[str]:
# earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3
lowerCAmelCase__ = 27
for scheduler_class in self.scheduler_classes:
lowerCAmelCase__ = self.dummy_sample
lowerCAmelCase__ = 0.1 * sample
lowerCAmelCase__ = self.get_scheduler_config()
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ )
# before power of 3 fix, would error on first step, so we only need to do two
for i, t in enumerate(scheduler.prk_timesteps[:2] ):
lowerCAmelCase__ = scheduler.step_prk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample
def a ( self : Union[str, Any] ) -> Optional[Any]:
with self.assertRaises(SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase__ = self.scheduler_classes[0]
lowerCAmelCase__ = self.get_scheduler_config()
lowerCAmelCase__ = scheduler_class(**SCREAMING_SNAKE_CASE__ )
scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample
def a ( self : Any ) -> Tuple:
lowerCAmelCase__ = self.full_loop()
lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) )
lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) )
assert abs(result_sum.item() - 198.1_318 ) < 1e-2
assert abs(result_mean.item() - 0.2_580 ) < 1e-3
def a ( self : int ) -> Dict:
lowerCAmelCase__ = self.full_loop(prediction_type="v_prediction" )
lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) )
lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) )
assert abs(result_sum.item() - 67.3_986 ) < 1e-2
assert abs(result_mean.item() - 0.0_878 ) < 1e-3
def a ( self : Any ) -> Tuple:
# We specify different beta, so that the first alpha is 0.99
lowerCAmelCase__ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 )
lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) )
lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) )
assert abs(result_sum.item() - 230.0_399 ) < 1e-2
assert abs(result_mean.item() - 0.2_995 ) < 1e-3
def a ( self : int ) -> List[Any]:
# We specify different beta, so that the first alpha is 0.99
lowerCAmelCase__ = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 )
lowerCAmelCase__ = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) )
lowerCAmelCase__ = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) )
assert abs(result_sum.item() - 186.9_482 ) < 1e-2
assert abs(result_mean.item() - 0.2_434 ) < 1e-3
| 125 | 1 |
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class A :
'''simple docstring'''
A__ = 42
A__ = 42
class A :
'''simple docstring'''
def __init__(self : Any , _UpperCAmelCase : int ) -> Optional[Any]:
"""simple docstring"""
lowercase__ = [[] for _ in range(_UpperCAmelCase )]
lowercase__ = size
def __getitem__(self : Optional[int] , _UpperCAmelCase : int ) -> Iterator[Edge]:
"""simple docstring"""
return iter(self._graph[vertex] )
@property
def lowerCamelCase__ (self : int ) -> Optional[int]:
"""simple docstring"""
return self._size
def lowerCamelCase__ (self : int , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> Dict:
"""simple docstring"""
if weight not in (0, 1):
raise ValueError("""Edge weight must be either 0 or 1.""" )
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError("""Vertex indexes must be in [0; size).""" )
self._graph[from_vertex].append(Edge(_UpperCAmelCase , _UpperCAmelCase ) )
def lowerCamelCase__ (self : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int | None:
"""simple docstring"""
lowercase__ = deque([start_vertex] )
lowercase__ = [None] * self.size
lowercase__ = 0
while queue:
lowercase__ = queue.popleft()
lowercase__ = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
lowercase__ = current_distance + edge.weight
lowercase__ = distances[edge.destination_vertex]
if (
isinstance(_UpperCAmelCase , _UpperCAmelCase )
and new_distance >= dest_vertex_distance
):
continue
lowercase__ = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex )
else:
queue.append(edge.destination_vertex )
if distances[finish_vertex] is None:
raise ValueError("""No path from start_vertex to finish_vertex.""" )
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 15 |
"""simple docstring"""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer
__lowerCamelCase :str = logging.get_logger(__name__)
__lowerCamelCase :Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}
__lowerCamelCase :str = {
'vocab_file': {
'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt',
'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt',
'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt',
'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt',
'bert-base-multilingual-uncased': (
'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt'
),
'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt',
'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt',
'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt',
'bert-large-uncased-whole-word-masking': (
'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt'
),
'bert-large-cased-whole-word-masking': (
'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt'
),
'bert-large-uncased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'
),
'bert-large-cased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'
),
'bert-base-cased-finetuned-mrpc': (
'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt'
),
'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt',
'bert-base-german-dbmdz-uncased': (
'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt'
),
'TurkuNLP/bert-base-finnish-cased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt'
),
'TurkuNLP/bert-base-finnish-uncased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt'
),
'wietsedv/bert-base-dutch-cased': (
'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt'
),
},
'tokenizer_file': {
'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json',
'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json',
'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json',
'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json',
'bert-base-multilingual-uncased': (
'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json'
),
'bert-base-multilingual-cased': (
'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json'
),
'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json',
'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json',
'bert-large-uncased-whole-word-masking': (
'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json'
),
'bert-large-cased-whole-word-masking': (
'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json'
),
'bert-large-uncased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'
),
'bert-large-cased-whole-word-masking-finetuned-squad': (
'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'
),
'bert-base-cased-finetuned-mrpc': (
'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json'
),
'bert-base-german-dbmdz-cased': (
'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json'
),
'bert-base-german-dbmdz-uncased': (
'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json'
),
'TurkuNLP/bert-base-finnish-cased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json'
),
'TurkuNLP/bert-base-finnish-uncased-v1': (
'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json'
),
'wietsedv/bert-base-dutch-cased': (
'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json'
),
},
}
__lowerCamelCase :List[Any] = {
'bert-base-uncased': 512,
'bert-large-uncased': 512,
'bert-base-cased': 512,
'bert-large-cased': 512,
'bert-base-multilingual-uncased': 512,
'bert-base-multilingual-cased': 512,
'bert-base-chinese': 512,
'bert-base-german-cased': 512,
'bert-large-uncased-whole-word-masking': 512,
'bert-large-cased-whole-word-masking': 512,
'bert-large-uncased-whole-word-masking-finetuned-squad': 512,
'bert-large-cased-whole-word-masking-finetuned-squad': 512,
'bert-base-cased-finetuned-mrpc': 512,
'bert-base-german-dbmdz-cased': 512,
'bert-base-german-dbmdz-uncased': 512,
'TurkuNLP/bert-base-finnish-cased-v1': 512,
'TurkuNLP/bert-base-finnish-uncased-v1': 512,
'wietsedv/bert-base-dutch-cased': 512,
}
__lowerCamelCase :Tuple = {
'bert-base-uncased': {'do_lower_case': True},
'bert-large-uncased': {'do_lower_case': True},
'bert-base-cased': {'do_lower_case': False},
'bert-large-cased': {'do_lower_case': False},
'bert-base-multilingual-uncased': {'do_lower_case': True},
'bert-base-multilingual-cased': {'do_lower_case': False},
'bert-base-chinese': {'do_lower_case': False},
'bert-base-german-cased': {'do_lower_case': False},
'bert-large-uncased-whole-word-masking': {'do_lower_case': True},
'bert-large-cased-whole-word-masking': {'do_lower_case': False},
'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True},
'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False},
'bert-base-cased-finetuned-mrpc': {'do_lower_case': False},
'bert-base-german-dbmdz-cased': {'do_lower_case': False},
'bert-base-german-dbmdz-uncased': {'do_lower_case': True},
'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False},
'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True},
'wietsedv/bert-base-dutch-cased': {'do_lower_case': False},
}
class A__ ( __lowercase):
"""simple docstring"""
snake_case__ : Union[str, Any] =VOCAB_FILES_NAMES
snake_case__ : Union[str, Any] =PRETRAINED_VOCAB_FILES_MAP
snake_case__ : int =PRETRAINED_INIT_CONFIGURATION
snake_case__ : Tuple =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ : str =BertTokenizer
def __init__( self: str , __a: Union[str, Any]=None , __a: Tuple=None , __a: int=True , __a: List[str]="[UNK]" , __a: Optional[Any]="[SEP]" , __a: Union[str, Any]="[PAD]" , __a: Optional[Any]="[CLS]" , __a: Optional[Any]="[MASK]" , __a: List[Any]=True , __a: int=None , **__a: Union[str, Any] , )-> int:
super().__init__(
__a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , )
lowerCamelCase : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("""lowercase""" , __a ) != do_lower_case
or normalizer_state.get("""strip_accents""" , __a ) != strip_accents
or normalizer_state.get("""handle_chinese_chars""" , __a ) != tokenize_chinese_chars
):
lowerCamelCase : int = getattr(__a , normalizer_state.pop("""type""" ) )
lowerCamelCase : str = do_lower_case
lowerCamelCase : List[Any] = strip_accents
lowerCamelCase : Tuple = tokenize_chinese_chars
lowerCamelCase : str = normalizer_class(**__a )
lowerCamelCase : Union[str, Any] = do_lower_case
def a__ ( self: Tuple , __a: List[Any] , __a: int=None )-> Optional[Any]:
lowerCamelCase : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def a__ ( self: Any , __a: List[int] , __a: Optional[List[int]] = None )-> List[int]:
lowerCamelCase : Dict = [self.sep_token_id]
lowerCamelCase : Any = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def a__ ( self: Optional[int] , __a: str , __a: Optional[str] = None )-> Tuple[str]:
lowerCamelCase : Optional[Any] = self._tokenizer.model.save(__a , name=__a )
return tuple(__a )
| 222 | 0 |
"""simple docstring"""
def UpperCAmelCase ( A__: int = 1000 ) -> int:
__lowerCamelCase , __lowerCamelCase : Optional[Any] = 1, 1
__lowerCamelCase : Union[str, Any] = []
for i in range(1 , n + 1 ):
__lowerCamelCase : Any = prev_numerator + 2 * prev_denominator
__lowerCamelCase : Any = prev_numerator + prev_denominator
if len(str(A__ ) ) > len(str(A__ ) ):
result.append(A__ )
__lowerCamelCase : int = numerator
__lowerCamelCase : Optional[Any] = denominator
return len(A__ )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 263 |
"""simple docstring"""
import collections.abc
from typing import Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig
a_ : Tuple = logging.get_logger(__name__)
# General docstring
a_ : List[str] = '''PoolFormerConfig'''
# Base docstring
a_ : Optional[Any] = '''sail/poolformer_s12'''
a_ : List[Any] = [1, 5_12, 7, 7]
# Image classification docstring
a_ : Any = '''sail/poolformer_s12'''
a_ : Optional[int] = '''tabby, tabby cat'''
a_ : Optional[Any] = [
'''sail/poolformer_s12''',
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]
def UpperCAmelCase ( A__: Optional[Any] , A__: float = 0.0 , A__: bool = False ) -> Tuple:
if drop_prob == 0.0 or not training:
return input
__lowerCamelCase : Dict = 1 - drop_prob
__lowerCamelCase : List[Any] = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
__lowerCamelCase : List[Any] = keep_prob + torch.rand(A__ , dtype=input.dtype , device=input.device )
random_tensor.floor_() # binarize
__lowerCamelCase : Any = input.div(A__ ) * random_tensor
return output
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a = None ):
super().__init__()
__lowerCamelCase : int = drop_prob
def snake_case_ ( self , __a ):
return drop_path(__a , self.drop_prob , self.training )
def snake_case_ ( self ):
return "p={}".format(self.drop_prob )
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a , __a , __a , __a=None ):
super().__init__()
__lowerCamelCase : int = patch_size if isinstance(__a , collections.abc.Iterable ) else (patch_size, patch_size)
__lowerCamelCase : int = stride if isinstance(__a , collections.abc.Iterable ) else (stride, stride)
__lowerCamelCase : Optional[int] = padding if isinstance(__a , collections.abc.Iterable ) else (padding, padding)
__lowerCamelCase : Optional[Any] = nn.Convad(__a , __a , kernel_size=__a , stride=__a , padding=__a )
__lowerCamelCase : List[str] = norm_layer(__a ) if norm_layer else nn.Identity()
def snake_case_ ( self , __a ):
__lowerCamelCase : List[Any] = self.projection(__a )
__lowerCamelCase : Dict = self.norm(__a )
return embeddings
class __lowercase( nn.GroupNorm ):
'''simple docstring'''
def __init__( self , __a , **__a ):
super().__init__(1 , __a , **__a )
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__()
__lowerCamelCase : str = nn.AvgPoolad(__a , stride=1 , padding=pool_size // 2 , count_include_pad=__a )
def snake_case_ ( self , __a ):
return self.pool(__a ) - hidden_states
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a , __a ):
super().__init__()
__lowerCamelCase : Any = nn.Convad(__a , __a , 1 )
__lowerCamelCase : Dict = nn.Convad(__a , __a , 1 )
__lowerCamelCase : List[Any] = PoolFormerDropPath(__a )
if isinstance(config.hidden_act , __a ):
__lowerCamelCase : List[str] = ACTaFN[config.hidden_act]
else:
__lowerCamelCase : str = config.hidden_act
def snake_case_ ( self , __a ):
__lowerCamelCase : int = self.conva(__a )
__lowerCamelCase : Dict = self.act_fn(__a )
__lowerCamelCase : List[str] = self.drop(__a )
__lowerCamelCase : int = self.conva(__a )
__lowerCamelCase : str = self.drop(__a )
return hidden_states
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a , __a , __a , __a , __a , __a ):
super().__init__()
__lowerCamelCase : Tuple = PoolFormerPooling(__a )
__lowerCamelCase : Union[str, Any] = PoolFormerOutput(__a , __a , __a , __a )
__lowerCamelCase : List[Any] = PoolFormerGroupNorm(__a )
__lowerCamelCase : List[Any] = PoolFormerGroupNorm(__a )
# Useful for training neural nets
__lowerCamelCase : Any = PoolFormerDropPath(__a ) if drop_path > 0.0 else nn.Identity()
__lowerCamelCase : Tuple = config.use_layer_scale
if config.use_layer_scale:
__lowerCamelCase : List[str] = nn.Parameter(
config.layer_scale_init_value * torch.ones((__a) ) , requires_grad=__a )
__lowerCamelCase : Optional[int] = nn.Parameter(
config.layer_scale_init_value * torch.ones((__a) ) , requires_grad=__a )
def snake_case_ ( self , __a ):
if self.use_layer_scale:
__lowerCamelCase : Union[str, Any] = self.pooling(self.before_norm(__a ) )
__lowerCamelCase : Any = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output
# First residual connection
__lowerCamelCase : Optional[Any] = hidden_states + self.drop_path(__a )
__lowerCamelCase : Tuple = ()
__lowerCamelCase : Optional[Any] = self.output(self.after_norm(__a ) )
__lowerCamelCase : List[Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output
# Second residual connection
__lowerCamelCase : List[Any] = hidden_states + self.drop_path(__a )
__lowerCamelCase : Optional[Any] = (output,) + outputs
return outputs
else:
__lowerCamelCase : Tuple = self.drop_path(self.pooling(self.before_norm(__a ) ) )
# First residual connection
__lowerCamelCase : List[str] = pooling_output + hidden_states
__lowerCamelCase : int = ()
# Second residual connection inside the PoolFormerOutput block
__lowerCamelCase : List[str] = self.drop_path(self.output(self.after_norm(__a ) ) )
__lowerCamelCase : str = hidden_states + layer_output
__lowerCamelCase : int = (output,) + outputs
return outputs
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__()
__lowerCamelCase : int = config
# stochastic depth decay rule
__lowerCamelCase : int = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )]
# patch embeddings
__lowerCamelCase : List[str] = []
for i in range(config.num_encoder_blocks ):
embeddings.append(
PoolFormerEmbeddings(
patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) )
__lowerCamelCase : Optional[int] = nn.ModuleList(__a )
# Transformer blocks
__lowerCamelCase : Any = []
__lowerCamelCase : int = 0
for i in range(config.num_encoder_blocks ):
# each block consists of layers
__lowerCamelCase : Optional[int] = []
if i != 0:
cur += config.depths[i - 1]
for j in range(config.depths[i] ):
layers.append(
PoolFormerLayer(
__a , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) )
blocks.append(nn.ModuleList(__a ) )
__lowerCamelCase : str = nn.ModuleList(__a )
def snake_case_ ( self , __a , __a=False , __a=True ):
__lowerCamelCase : Union[str, Any] = () if output_hidden_states else None
__lowerCamelCase : int = pixel_values
for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ):
__lowerCamelCase , __lowerCamelCase : Any = layers
# Get patch embeddings from hidden_states
__lowerCamelCase : Any = embedding_layer(__a )
# Send the embeddings through the blocks
for _, blk in enumerate(__a ):
__lowerCamelCase : Optional[int] = blk(__a )
__lowerCamelCase : Tuple = layer_outputs[0]
if output_hidden_states:
__lowerCamelCase : Union[str, Any] = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states] if v is not None )
return BaseModelOutputWithNoAttention(last_hidden_state=__a , hidden_states=__a )
class __lowercase( lowercase__ ):
'''simple docstring'''
__a : Tuple = PoolFormerConfig
__a : Tuple = 'poolformer'
__a : Optional[int] = 'pixel_values'
__a : Optional[Any] = True
def snake_case_ ( self , __a ):
if isinstance(__a , (nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(__a , nn.LayerNorm ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
def snake_case_ ( self , __a , __a=False ):
if isinstance(__a , __a ):
__lowerCamelCase : Union[str, Any] = value
a_ : Union[str, Any] = R'''
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''
a_ : List[str] = R'''
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`PoolFormerImageProcessor.__call__`] for details.
'''
@add_start_docstrings(
'The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.' , lowercase__ , )
class __lowercase( lowercase__ ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__(__a )
__lowerCamelCase : Optional[Any] = config
__lowerCamelCase : Any = PoolFormerEncoder(__a )
# Initialize weights and apply final processing
self.post_init()
def snake_case_ ( self ):
return self.embeddings.patch_embeddings
@add_start_docstrings_to_model_forward(__a )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def snake_case_ ( self , __a = None , __a = None , __a = None , ):
__lowerCamelCase : Union[str, Any] = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
__lowerCamelCase : Dict = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('You have to specify pixel_values' )
__lowerCamelCase : Any = self.encoder(
__a , output_hidden_states=__a , return_dict=__a , )
__lowerCamelCase : int = encoder_outputs[0]
if not return_dict:
return (sequence_output, None) + encoder_outputs[1:]
return BaseModelOutputWithNoAttention(
last_hidden_state=__a , hidden_states=encoder_outputs.hidden_states , )
class __lowercase( nn.Module ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__()
__lowerCamelCase : Optional[Any] = nn.Linear(config.hidden_size , config.hidden_size )
def snake_case_ ( self , __a ):
__lowerCamelCase : List[Any] = self.dense(__a )
return output
@add_start_docstrings(
'\n PoolFormer Model transformer with an image classification head on top\n ' , lowercase__ , )
class __lowercase( lowercase__ ):
'''simple docstring'''
def __init__( self , __a ):
super().__init__(__a )
__lowerCamelCase : str = config.num_labels
__lowerCamelCase : Optional[Any] = PoolFormerModel(__a )
# Final norm
__lowerCamelCase : str = PoolFormerGroupNorm(config.hidden_sizes[-1] )
# Classifier head
__lowerCamelCase : Optional[Any] = (
nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity()
)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(__a )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def snake_case_ ( self , __a = None , __a = None , __a = None , __a = None , ):
__lowerCamelCase : Any = return_dict if return_dict is not None else self.config.use_return_dict
__lowerCamelCase : Tuple = self.poolformer(
__a , output_hidden_states=__a , return_dict=__a , )
__lowerCamelCase : int = outputs[0]
__lowerCamelCase : Optional[int] = self.classifier(self.norm(__a ).mean([-2, -1] ) )
__lowerCamelCase : Union[str, Any] = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
__lowerCamelCase : Any = 'regression'
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
__lowerCamelCase : Any = 'single_label_classification'
else:
__lowerCamelCase : Optional[Any] = 'multi_label_classification'
if self.config.problem_type == "regression":
__lowerCamelCase : int = MSELoss()
if self.num_labels == 1:
__lowerCamelCase : Optional[Any] = loss_fct(logits.squeeze() , labels.squeeze() )
else:
__lowerCamelCase : Optional[Any] = loss_fct(__a , __a )
elif self.config.problem_type == "single_label_classification":
__lowerCamelCase : Tuple = CrossEntropyLoss()
__lowerCamelCase : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
__lowerCamelCase : List[Any] = BCEWithLogitsLoss()
__lowerCamelCase : Optional[Any] = loss_fct(__a , __a )
if not return_dict:
__lowerCamelCase : Optional[Any] = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=__a , logits=__a , hidden_states=outputs.hidden_states )
| 263 | 1 |
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_keras_nlp_available():
from transformers.models.gpta import TFGPTaTokenizer
_lowercase : Tuple =["gpt2"]
_lowercase : Optional[Any] ="gpt2"
if is_tf_available():
class snake_case__ (tf.Module ):
"""simple docstring"""
def __init__( self , __lowercase ) -> Optional[int]:
"""simple docstring"""
super().__init__()
a__ : List[str] = tokenizer
a__ : Optional[int] = AutoConfig.from_pretrained(__UpperCAmelCase )
a__ : Optional[Any] = TFGPTaLMHeadModel.from_config(__UpperCAmelCase )
@tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name="""text""" ),) )
def SCREAMING_SNAKE_CASE__( self , __lowercase ) -> Optional[Any]:
"""simple docstring"""
a__ : str = self.tokenizer(__UpperCAmelCase )
a__ : int = tokenized['input_ids'].to_tensor()
a__ : Optional[Any] = tf.cast(input_ids_dense > 0 , tf.intaa )
# input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])
a__ : int = self.model(input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase )['logits']
return outputs
@require_tf
@require_keras_nlp
class snake_case__ (unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE__( self ) -> List[Any]:
"""simple docstring"""
super().setUp()
a__ : List[str] = [GPTaTokenizer.from_pretrained(__UpperCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
a__ : Union[str, Any] = [TFGPTaTokenizer.from_pretrained(__UpperCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
a__ : int = [
'This is a straightforward English test sentence.',
'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.',
'Now we\'re going to add some Chinese: 一 二 三 一二三',
'And some much more rare Chinese: 齉 堃 齉堃',
'Je vais aussi écrire en français pour tester les accents',
'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ',
]
a__ : str = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def SCREAMING_SNAKE_CASE__( self ) -> Optional[int]:
"""simple docstring"""
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in self.test_sentences:
a__ : int = tokenizer([test_inputs] , return_tensors="""tf""" )
a__ : Optional[int] = tf_tokenizer([test_inputs] )
for key in python_outputs.keys():
# convert them to numpy to avoid messing with ragged tensors
a__ : Optional[int] = python_outputs[key].numpy()
a__ : List[str] = tf_outputs[key].numpy()
self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) )
self.assertTrue(tf.reduce_all(tf.cast(__UpperCAmelCase , tf.intaa ) == tf_outputs_values ) )
@slow
def SCREAMING_SNAKE_CASE__( self ) -> Optional[Any]:
"""simple docstring"""
for tf_tokenizer in self.tf_tokenizers:
a__ : Optional[int] = tf.function(__UpperCAmelCase )
for test_inputs in self.test_sentences:
a__ : Any = tf.constant(__UpperCAmelCase )
a__ : int = compiled_tokenizer(__UpperCAmelCase )
a__ : Any = tf_tokenizer(__UpperCAmelCase )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def SCREAMING_SNAKE_CASE__( self ) -> Optional[int]:
"""simple docstring"""
for tf_tokenizer in self.tf_tokenizers:
a__ : List[str] = ModelToSave(tokenizer=__UpperCAmelCase )
a__ : Union[str, Any] = tf.convert_to_tensor([self.test_sentences[0]] )
a__ : List[str] = model.serving(__UpperCAmelCase ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
a__ : Union[str, Any] = Path(__UpperCAmelCase ) / 'saved.model'
tf.saved_model.save(__UpperCAmelCase , __UpperCAmelCase , signatures={"""serving_default""": model.serving} )
a__ : str = tf.saved_model.load(__UpperCAmelCase )
a__ : Dict = loaded_model.signatures['serving_default'](__UpperCAmelCase )['output_0']
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertTrue(tf.reduce_all(out == loaded_output ) )
@slow
def SCREAMING_SNAKE_CASE__( self ) -> Optional[Any]:
"""simple docstring"""
for tf_tokenizer in self.tf_tokenizers:
a__ : List[str] = tf.convert_to_tensor([self.test_sentences[0]] )
a__ : List[str] = tf_tokenizer(__UpperCAmelCase ) # Build model with some sample inputs
a__ : Union[str, Any] = tf_tokenizer.get_config()
a__ : Tuple = TFGPTaTokenizer.from_config(__UpperCAmelCase )
a__ : Tuple = model_from_config(__UpperCAmelCase )
for key in from_config_output.keys():
self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) )
@slow
def SCREAMING_SNAKE_CASE__( self ) -> int:
"""simple docstring"""
for tf_tokenizer in self.tf_tokenizers:
# for the test to run
a__ : int = 1_2_3_1_2_3
for max_length in [3, 5, 1_0_2_4]:
a__ : Tuple = tf.convert_to_tensor([self.test_sentences[0]] )
a__ : List[str] = tf_tokenizer(__UpperCAmelCase , max_length=__UpperCAmelCase )
a__ : Union[str, Any] = out['input_ids'].numpy().shape[1]
assert out_length == max_length
| 136 |
"""simple docstring"""
import random
import unittest
import numpy as np
from diffusers import (
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionImgaImgPipeline,
PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
is_onnx_available,
load_image,
nightly,
require_onnxruntime,
require_torch_gpu,
)
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class _lowerCAmelCase ( a , unittest.TestCase ):
"""simple docstring"""
__magic_name__ :int = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"""
def snake_case ( self , __UpperCAmelCase=0 ):
'''simple docstring'''
lowerCAmelCase__ :List[str] = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(__UpperCAmelCase ) )
lowerCAmelCase__ :List[str] = np.random.RandomState(__UpperCAmelCase )
lowerCAmelCase__ :List[str] = {
'prompt': 'A painting of a squirrel eating a burger',
'image': image,
'generator': generator,
'num_inference_steps': 3,
'strength': 0.75,
'guidance_scale': 7.5,
'output_type': 'numpy',
}
return inputs
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :Union[str, Any] = self.get_dummy_inputs()
lowerCAmelCase__ :Optional[int] = pipe(**__UpperCAmelCase ).images
lowerCAmelCase__ :Union[str, Any] = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 1_2_8, 1_2_8, 3)
lowerCAmelCase__ :Union[str, Any] = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87] )
assert np.abs(image_slice - expected_slice ).max() < 1E-1
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
lowerCAmelCase__ :str = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__UpperCAmelCase )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :Tuple = self.get_dummy_inputs()
lowerCAmelCase__ :Optional[Any] = pipe(**__UpperCAmelCase ).images
lowerCAmelCase__ :Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
lowerCAmelCase__ :int = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
lowerCAmelCase__ :List[str] = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
# warmup pass to apply optimizations
lowerCAmelCase__ :List[Any] = pipe(**self.get_dummy_inputs() )
lowerCAmelCase__ :Tuple = self.get_dummy_inputs()
lowerCAmelCase__ :int = pipe(**__UpperCAmelCase ).images
lowerCAmelCase__ :Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
lowerCAmelCase__ :Union[str, Any] = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
lowerCAmelCase__ :Dict = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :Any = self.get_dummy_inputs()
lowerCAmelCase__ :List[str] = pipe(**__UpperCAmelCase ).images
lowerCAmelCase__ :List[str] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
lowerCAmelCase__ :Optional[int] = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :str = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
lowerCAmelCase__ :str = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :Tuple = self.get_dummy_inputs()
lowerCAmelCase__ :Any = pipe(**__UpperCAmelCase ).images
lowerCAmelCase__ :Optional[int] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
lowerCAmelCase__ :int = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :List[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
lowerCAmelCase__ :List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :Any = self.get_dummy_inputs()
lowerCAmelCase__ :List[Any] = pipe(**__UpperCAmelCase ).images
lowerCAmelCase__ :int = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_2_8, 1_2_8, 3)
lowerCAmelCase__ :Optional[Any] = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
@nightly
@require_onnxruntime
@require_torch_gpu
class _lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
@property
def snake_case ( self ):
'''simple docstring'''
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Tuple = ort.SessionOptions()
lowerCAmelCase__ :Optional[int] = False
return options
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Any = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
lowerCAmelCase__ :Any = init_image.resize((7_6_8, 5_1_2) )
# using the PNDM scheduler by default
lowerCAmelCase__ :Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :List[Any] = 'A fantasy landscape, trending on artstation'
lowerCAmelCase__ :Optional[Any] = np.random.RandomState(0 )
lowerCAmelCase__ :List[str] = pipe(
prompt=__UpperCAmelCase , image=__UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , num_inference_steps=1_0 , generator=__UpperCAmelCase , output_type='np' , )
lowerCAmelCase__ :Any = output.images
lowerCAmelCase__ :List[str] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]
assert images.shape == (1, 5_1_2, 7_6_8, 3)
lowerCAmelCase__ :List[Any] = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
def snake_case ( self ):
'''simple docstring'''
lowerCAmelCase__ :Union[str, Any] = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
lowerCAmelCase__ :Optional[Any] = init_image.resize((7_6_8, 5_1_2) )
lowerCAmelCase__ :List[Any] = LMSDiscreteScheduler.from_pretrained(
'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' )
lowerCAmelCase__ :Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=__UpperCAmelCase , safety_checker=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=__UpperCAmelCase )
lowerCAmelCase__ :List[Any] = 'A fantasy landscape, trending on artstation'
lowerCAmelCase__ :List[Any] = np.random.RandomState(0 )
lowerCAmelCase__ :List[Any] = pipe(
prompt=__UpperCAmelCase , image=__UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , num_inference_steps=2_0 , generator=__UpperCAmelCase , output_type='np' , )
lowerCAmelCase__ :Optional[Any] = output.images
lowerCAmelCase__ :int = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]
assert images.shape == (1, 5_1_2, 7_6_8, 3)
lowerCAmelCase__ :List[Any] = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
| 93 | 0 |
import os
import random
import sys
from . import cryptomath_module as cryptoMath # noqa: N812
from . import rabin_miller as rabinMiller # noqa: N812
def UpperCamelCase_( ) -> None:
print('Making key files...' )
make_key_files('rsa' , 1024 )
print('Key files generation successful.' )
def UpperCamelCase_( lowerCamelCase_ ) -> tuple[tuple[int, int], tuple[int, int]]:
print('Generating prime p...' )
_lowercase : List[Any] = rabinMiller.generate_large_prime(lowerCamelCase_ )
print('Generating prime q...' )
_lowercase : int = rabinMiller.generate_large_prime(lowerCamelCase_ )
_lowercase : Tuple = p * q
print('Generating e that is relatively prime to (p - 1) * (q - 1)...' )
while True:
_lowercase : Tuple = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) )
if cryptoMath.gcd(lowerCamelCase_ , (p - 1) * (q - 1) ) == 1:
break
print('Calculating d that is mod inverse of e...' )
_lowercase : List[Any] = cryptoMath.find_mod_inverse(lowerCamelCase_ , (p - 1) * (q - 1) )
_lowercase : Optional[Any] = (n, e)
_lowercase : List[Any] = (n, d)
return (public_key, private_key)
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> None:
if os.path.exists(F'''{name}_pubkey.txt''' ) or os.path.exists(F'''{name}_privkey.txt''' ):
print('\nWARNING:' )
print(
F'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n'''
'Use a different name or delete these files and re-run this program.' )
sys.exit()
_lowercase , _lowercase : List[str] = generate_key(lowerCamelCase_ )
print(F'''\nWriting public key to file {name}_pubkey.txt...''' )
with open(F'''{name}_pubkey.txt''' , 'w' ) as out_file:
out_file.write(F'''{key_size},{public_key[0]},{public_key[1]}''' )
print(F'''Writing private key to file {name}_privkey.txt...''' )
with open(F'''{name}_privkey.txt''' , 'w' ) as out_file:
out_file.write(F'''{key_size},{private_key[0]},{private_key[1]}''' )
if __name__ == "__main__":
main()
| 354 |
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.:
# python ./utils/get_modified_files.py utils src tests examples
#
# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered
# since the output of this script is fed into Makefile commands it doesn't print a newline after the results
import re
import subprocess
import sys
SCREAMING_SNAKE_CASE : List[Any] = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
SCREAMING_SNAKE_CASE : Optional[int] = (
subprocess.check_output(F"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split()
)
SCREAMING_SNAKE_CASE : Any = "|".join(sys.argv[1:])
SCREAMING_SNAKE_CASE : Union[str, Any] = re.compile(rF"^({joined_dirs}).*?\.py$")
SCREAMING_SNAKE_CASE : List[Any] = [x for x in modified_files if regex.match(x)]
print(" ".join(relevant_modified_files), end="")
| 354 | 1 |
def __lowerCAmelCase ( ):
for n in range(1 , 100_0000 ):
yield n * (n + 1) // 2
def __lowerCAmelCase ( __snake_case ):
__lowerCAmelCase = 1
__lowerCAmelCase = 2
while i * i <= n:
__lowerCAmelCase = 0
while n % i == 0:
n //= i
multiplicity += 1
divisors_count *= multiplicity + 1
i += 1
if n > 1:
divisors_count *= 2
return divisors_count
def __lowerCAmelCase ( ):
return next(i for i in triangle_number_generator() if count_divisors(__snake_case ) > 500 )
if __name__ == "__main__":
print(solution())
| 367 |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from transformers.generation import DisjunctiveConstraint
@require_torch
class _UpperCamelCase (unittest.TestCase ):
def __UpperCAmelCase ( self )-> List[Any]:
# For consistency across different places the DisjunctiveConstraint is called,
# dc.token_ids is a list of integers. It is also initialized only by integers.
__lowerCAmelCase = [[1, 2, 4], [1, 2, 3, 4]]
__lowerCAmelCase = DisjunctiveConstraint(__UpperCamelCase )
self.assertTrue(isinstance(dc.token_ids , __UpperCamelCase ) )
with self.assertRaises(__UpperCamelCase ):
DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) )
with self.assertRaises(__UpperCamelCase ):
DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] )
def __UpperCAmelCase ( self )-> Tuple:
# We can't have constraints that are complete subsets of another. This leads to a preverse
# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
__lowerCAmelCase = [[1, 2], [1, 2, 3, 4]]
with self.assertRaises(__UpperCamelCase ):
DisjunctiveConstraint(__UpperCamelCase ) # fails here
def __UpperCAmelCase ( self )-> List[Any]:
__lowerCAmelCase = [[1, 2, 3], [1, 2, 4]]
__lowerCAmelCase = DisjunctiveConstraint(__UpperCamelCase )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(1 )
__lowerCAmelCase = stepped is True and completed is False and reset is False
self.assertTrue(__UpperCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(2 )
__lowerCAmelCase = stepped is True and completed is False and reset is False
self.assertTrue(__UpperCamelCase )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(3 )
__lowerCAmelCase = stepped is True and completed is True and reset is False
self.assertTrue(__UpperCamelCase )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 3] )
def __UpperCAmelCase ( self )-> int:
__lowerCAmelCase = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]
__lowerCAmelCase = DisjunctiveConstraint(__UpperCamelCase )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(4 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.current_seq == [1, 2, 4] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.current_seq == [1, 2, 4, 5] )
dc.reset()
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(1 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 3 )
self.assertTrue(dc.current_seq == [1] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(2 )
self.assertTrue(not dc.completed )
self.assertTrue(dc.remaining() == 2 )
self.assertTrue(dc.current_seq == [1, 2] )
__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(5 )
self.assertTrue(dc.completed ) # Completed!
self.assertTrue(dc.remaining() == 0 )
self.assertTrue(dc.current_seq == [1, 2, 5] )
| 367 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
__lowerCamelCase : Optional[Any] = {"""configuration_deit""": ["""DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DeiTConfig""", """DeiTOnnxConfig"""]}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : Optional[Any] = ["""DeiTFeatureExtractor"""]
__lowerCamelCase : Union[str, Any] = ["""DeiTImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : Dict = [
"""DEIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""DeiTForImageClassification""",
"""DeiTForImageClassificationWithTeacher""",
"""DeiTForMaskedImageModeling""",
"""DeiTModel""",
"""DeiTPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCamelCase : Any = [
"""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
__lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 448 |
import unittest
import numpy as np
from transformers import RoFormerConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.roformer.modeling_flax_roformer import (
FlaxRoFormerForMaskedLM,
FlaxRoFormerForMultipleChoice,
FlaxRoFormerForQuestionAnswering,
FlaxRoFormerForSequenceClassification,
FlaxRoFormerForTokenClassification,
FlaxRoFormerModel,
)
class _lowercase ( unittest.TestCase ):
def __init__( self , a , a=1_3 , a=7 , a=True , a=True , a=True , a=True , a=9_9 , a=3_2 , a=5 , a=4 , a=3_7 , a="gelu" , a=0.1 , a=0.1 , a=5_1_2 , a=1_6 , a=2 , a=0.02 , a=4 , ):
snake_case__ : Any =parent
snake_case__ : Dict =batch_size
snake_case__ : List[Any] =seq_length
snake_case__ : str =is_training
snake_case__ : Union[str, Any] =use_attention_mask
snake_case__ : str =use_token_type_ids
snake_case__ : int =use_labels
snake_case__ : Tuple =vocab_size
snake_case__ : List[str] =hidden_size
snake_case__ : Dict =num_hidden_layers
snake_case__ : Optional[Any] =num_attention_heads
snake_case__ : List[str] =intermediate_size
snake_case__ : str =hidden_act
snake_case__ : Union[str, Any] =hidden_dropout_prob
snake_case__ : Tuple =attention_probs_dropout_prob
snake_case__ : Tuple =max_position_embeddings
snake_case__ : str =type_vocab_size
snake_case__ : Optional[Any] =type_sequence_label_size
snake_case__ : str =initializer_range
snake_case__ : List[Any] =num_choices
def lowercase__ ( self ):
snake_case__ : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case__ : Tuple =None
if self.use_attention_mask:
snake_case__ : Union[str, Any] =random_attention_mask([self.batch_size, self.seq_length] )
snake_case__ : Union[str, Any] =None
if self.use_token_type_ids:
snake_case__ : Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
snake_case__ : Tuple =RoFormerConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def lowercase__ ( self ):
snake_case__ : Optional[int] =self.prepare_config_and_inputs()
snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[Any] =config_and_inputs
snake_case__ : Dict ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
return config, inputs_dict
@require_flax
class _lowercase ( _A , unittest.TestCase ):
_a : str = True
_a : Optional[Any] = (
(
FlaxRoFormerModel,
FlaxRoFormerForMaskedLM,
FlaxRoFormerForSequenceClassification,
FlaxRoFormerForTokenClassification,
FlaxRoFormerForMultipleChoice,
FlaxRoFormerForQuestionAnswering,
)
if is_flax_available()
else ()
)
def lowercase__ ( self ):
snake_case__ : Optional[Any] =FlaxRoFormerModelTester(self )
@slow
def lowercase__ ( self ):
for model_class_name in self.all_model_classes:
snake_case__ : Tuple =model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=a )
snake_case__ : List[Any] =model(np.ones((1, 1) ) )
self.assertIsNotNone(a )
@require_flax
class _lowercase ( unittest.TestCase ):
@slow
def lowercase__ ( self ):
snake_case__ : Optional[int] =FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" )
snake_case__ : Tuple =jnp.array([[0, 1, 2, 3, 4, 5]] )
snake_case__ : str =model(a )[0]
snake_case__ : List[str] =5_0_0_0_0
snake_case__ : str =(1, 6, vocab_size)
self.assertEqual(output.shape , a )
snake_case__ : Optional[int] =jnp.array(
[[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] )
self.assertTrue(jnp.allclose(output[:, :3, :3] , a , atol=1e-4 ) )
| 448 | 1 |
'''simple docstring'''
import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List
from ..utils import logging
_UpperCAmelCase : Optional[Any] = logging.get_logger(__name__)
def UpperCamelCase ( lowercase_ : Optional[int]=None , lowercase_ : Union[str, Any]=None ) -> Dict:
'''simple docstring'''
return field(default_factory=lambda: default , metadata=lowercase_ )
@dataclass
class __magic_name__ :
UpperCamelCase__ = list_field(
default=[] , metadata={
'help': (
'Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version'
' of all available models'
)
} , )
UpperCamelCase__ = list_field(
default=[8] , metadata={'help': 'List of batch sizes for which memory and time performance will be evaluated'} )
UpperCamelCase__ = list_field(
default=[8, 32, 1_28, 5_12] , metadata={'help': 'List of sequence lengths for which memory and time performance will be evaluated'} , )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to benchmark inference of model. Inference can be disabled via --no-inference.'} , )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'} , )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'} )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Use FP16 to accelerate inference.'} )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Benchmark training of model'} )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Verbose memory tracing'} )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'} , )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={
'help': 'Whether to perform memory measurements. Memory measurements can be disabled via --no-memory'
} , )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Trace memory line by line'} )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Save result to a CSV file'} )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Save all print statements in a log file'} )
UpperCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to print environment information'} )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={
'help': (
'Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use'
' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled'
' for debugging / testing and on TPU.'
)
} , )
UpperCamelCase__ = field(
default=f"""inference_time_{round(time() )}.csv""" , metadata={'help': 'CSV filename used if saving time results to csv.'} , )
UpperCamelCase__ = field(
default=f"""inference_memory_{round(time() )}.csv""" , metadata={'help': 'CSV filename used if saving memory results to csv.'} , )
UpperCamelCase__ = field(
default=f"""train_time_{round(time() )}.csv""" , metadata={'help': 'CSV filename used if saving time results to csv for training.'} , )
UpperCamelCase__ = field(
default=f"""train_memory_{round(time() )}.csv""" , metadata={'help': 'CSV filename used if saving memory results to csv for training.'} , )
UpperCamelCase__ = field(
default=f"""env_info_{round(time() )}.csv""" , metadata={'help': 'CSV filename used if saving environment information.'} , )
UpperCamelCase__ = field(
default=f"""log_{round(time() )}.csv""" , metadata={'help': 'Log filename used if print statements are saved in log.'} , )
UpperCamelCase__ = field(default=3 , metadata={'help': 'Times an experiment will be run.'} )
UpperCamelCase__ = field(
default=__SCREAMING_SNAKE_CASE , metadata={
'help': (
'Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain'
' model weights.'
)
} , )
def _A( self ):
warnings.warn(
f'The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'
''' are deprecated in general and it is advised to use external Benchmarking libraries '''
''' to benchmark Transformer models.''' , snake_case_ , )
def _A( self ):
return json.dumps(dataclasses.asdict(self ) , indent=2 )
@property
def _A( self ):
if len(self.models ) <= 0:
raise ValueError(
'''Please make sure you provide at least one model name / model identifier, *e.g.* `--models'''
''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' )
return self.models
@property
def _A( self ):
if not self.multi_process:
return False
elif self.is_tpu:
logger.info('''Multiprocessing is currently not possible on TPU.''' )
return False
else:
return True
| 72 |
import numpy as np
import pandas as pd
from sklearn.preprocessing import Normalizer
from sklearn.svm import SVR
from statsmodels.tsa.statespace.sarimax import SARIMAX
def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> float:
"""simple docstring"""
lowerCamelCase__ : Tuple = np.array([[1, item, train_mtch[i]] for i, item in enumerate(UpperCAmelCase )] )
lowerCamelCase__ : str = np.array(UpperCAmelCase )
lowerCamelCase__ : Optional[Any] = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , UpperCAmelCase ) ) , x.transpose() ) , UpperCAmelCase )
return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] )
def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> float:
"""simple docstring"""
lowerCamelCase__ : Optional[int] = (1, 2, 1)
lowerCamelCase__ : List[str] = (1, 1, 0, 7)
lowerCamelCase__ : Union[str, Any] = SARIMAX(
UpperCAmelCase , exog=UpperCAmelCase , order=UpperCAmelCase , seasonal_order=UpperCAmelCase )
lowerCamelCase__ : int = model.fit(disp=UpperCAmelCase , maxiter=600 , method='''nm''' )
lowerCamelCase__ : Optional[int] = model_fit.predict(1 , len(UpperCAmelCase ) , exog=[test_match] )
return result[0]
def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> float:
"""simple docstring"""
lowerCamelCase__ : Dict = SVR(kernel='''rbf''' , C=1 , gamma=0.1 , epsilon=0.1 )
regressor.fit(UpperCAmelCase , UpperCAmelCase )
lowerCamelCase__ : Tuple = regressor.predict(UpperCAmelCase )
return y_pred[0]
def _a ( UpperCAmelCase ) -> float:
"""simple docstring"""
train_user.sort()
lowerCamelCase__ : Any = np.percentile(UpperCAmelCase , 25 )
lowerCamelCase__ : Any = np.percentile(UpperCAmelCase , 75 )
lowerCamelCase__ : Optional[Any] = qa - qa
lowerCamelCase__ : Any = qa - (iqr * 0.1)
return low_lim
def _a ( UpperCAmelCase , UpperCAmelCase ) -> bool:
"""simple docstring"""
lowerCamelCase__ : List[str] = 0
lowerCamelCase__ : Any = 0
for i in list_vote:
if i > actual_result:
lowerCamelCase__ : List[str] = not_safe + 1
else:
if abs(abs(UpperCAmelCase ) - abs(UpperCAmelCase ) ) <= 0.1:
safe += 1
else:
not_safe += 1
return safe > not_safe
if __name__ == "__main__":
# data_input_df = pd.read_csv("ex_data.csv", header=None)
_A : Dict = [[1_82_31, 0.0, 1], [2_26_21, 1.0, 2], [1_56_75, 0.0, 3], [2_35_83, 1.0, 4]]
_A : Dict = pd.DataFrame(
data_input, columns=['total_user', 'total_even', 'days']
)
_A : Optional[int] = Normalizer().fit_transform(data_input_df.values)
# split data
_A : str = normalize_df[:, 2].tolist()
_A : Union[str, Any] = normalize_df[:, 0].tolist()
_A : Union[str, Any] = normalize_df[:, 1].tolist()
# for svr (input variable = total date and total match)
_A : int = normalize_df[:, [1, 2]].tolist()
_A : str = x[: len(x) - 1]
_A : Optional[Any] = x[len(x) - 1 :]
# for linear regression & sarimax
_A : Any = total_date[: len(total_date) - 1]
_A : List[str] = total_user[: len(total_user) - 1]
_A : List[str] = total_match[: len(total_match) - 1]
_A : Any = total_date[len(total_date) - 1 :]
_A : Optional[int] = total_user[len(total_user) - 1 :]
_A : str = total_match[len(total_match) - 1 :]
# voting system with forecasting
_A : Any = [
linear_regression_prediction(
trn_date, trn_user, trn_match, tst_date, tst_match
),
sarimax_predictor(trn_user, trn_match, tst_match),
support_vector_regressor(x_train, x_test, trn_user),
]
# check the safety of today's data
_A : Union[str, Any] = '' if data_safety_checker(res_vote, tst_user) else 'not '
print('Today\'s data is {not_str}safe.')
| 315 | 0 |
"""simple docstring"""
import datasets
SCREAMING_SNAKE_CASE__ : Optional[int] = "\\n@InProceedings{conneau2018xnli,\n author = \"Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin\",\n title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",\n booktitle = \"Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing\",\n year = \"2018\",\n publisher = \"Association for Computational Linguistics\",\n location = \"Brussels, Belgium\",\n}\n"
SCREAMING_SNAKE_CASE__ : str = "\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n"
SCREAMING_SNAKE_CASE__ : Any = "\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n 'accuracy': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric(\"xnli\")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n"
def A_ ( UpperCAmelCase__ , UpperCAmelCase__ ) -> Dict:
return (preds == labels).mean()
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class A_ ( datasets.Metric ):
"""simple docstring"""
def lowercase_ ( self ) -> Optional[Any]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32' ),
'references': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32' ),
} ) , codebase_urls=[] , reference_urls=[] , format='numpy' , )
def lowercase_ ( self , __UpperCAmelCase , __UpperCAmelCase ) -> List[str]:
return {"accuracy": simple_accuracy(__UpperCAmelCase , __UpperCAmelCase )}
| 509 |
"""simple docstring"""
import unittest
from transformers import CamembertTokenizer, CamembertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
SCREAMING_SNAKE_CASE__ : int = get_tests_dir("fixtures/test_sentencepiece.model")
SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model")
SCREAMING_SNAKE_CASE__ : Tuple = "pt" if is_torch_available() else "tf"
@require_sentencepiece
@require_tokenizers
class A_ ( _UpperCAmelCase , unittest.TestCase ):
"""simple docstring"""
lowercase : str = CamembertTokenizer
lowercase : str = CamembertTokenizerFast
lowercase : List[str] = True
lowercase : Tuple = True
def lowercase_ ( self ) -> Tuple:
super().setUp()
# We have a SentencePiece fixture for testing
a : List[str] = CamembertTokenizer(__UpperCAmelCase )
tokenizer.save_pretrained(self.tmpdirname )
def lowercase_ ( self ) -> int:
a : Dict = '<pad>'
a : Optional[int] = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase )
def lowercase_ ( self ) -> List[str]:
a : str = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '<s>NOTUSED' )
self.assertEqual(vocab_keys[1] , '<pad>' )
self.assertEqual(vocab_keys[-1] , '<mask>' )
self.assertEqual(len(__UpperCAmelCase ) , 10_04 )
def lowercase_ ( self ) -> Optional[int]:
self.assertEqual(self.get_tokenizer().vocab_size , 10_05 )
def lowercase_ ( self ) -> int:
a : List[str] = CamembertTokenizer(__UpperCAmelCase )
tokenizer.save_pretrained(self.tmpdirname )
a : str = CamembertTokenizerFast.from_pretrained(self.tmpdirname )
a : Tuple = 'I was born in 92000, and this is falsé.'
a : Union[str, Any] = tokenizer.encode(__UpperCAmelCase )
a : Union[str, Any] = rust_tokenizer.encode(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
a : Dict = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
a : Tuple = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
# <unk> tokens are not the same for `rust` than for `slow`.
# Because spm gives back raw token instead of `unk` in EncodeAsPieces
# tokens = tokenizer.tokenize(sequence)
a : Tuple = tokenizer.convert_ids_to_tokens(__UpperCAmelCase )
a : Tuple = rust_tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
def lowercase_ ( self ) -> str:
if not self.test_rust_tokenizer:
return
a : Tuple = self.get_tokenizer()
a : List[str] = self.get_rust_tokenizer()
a : Optional[Any] = 'I was born in 92000, and this is falsé.'
a : Optional[int] = tokenizer.tokenize(__UpperCAmelCase )
a : str = rust_tokenizer.tokenize(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
a : Optional[int] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
a : Tuple = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
a : str = self.get_rust_tokenizer()
a : List[Any] = tokenizer.encode(__UpperCAmelCase )
a : List[Any] = rust_tokenizer.encode(__UpperCAmelCase )
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
@slow
def lowercase_ ( self ) -> List[str]:
# fmt: off
a : Optional[int] = {'input_ids': [[5, 54, 71_96, 2_97, 30, 23, 7_76, 18, 11, 32_15, 37_05, 82_52, 22, 31_64, 11_81, 21_16, 29, 16, 8_13, 25, 7_91, 33_14, 20, 34_46, 38, 2_75_75, 1_20, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_68, 17, 11, 90_88, 20, 15_17, 8, 2_28_04, 1_88_18, 10, 38, 6_29, 6_07, 6_07, 1_42, 19, 71_96, 8_67, 56, 1_03_26, 24, 22_67, 20, 4_16, 50_72, 1_56_12, 2_33, 7_34, 7, 23_99, 27, 16, 30_15, 16_49, 7, 24, 20, 43_38, 23_99, 27, 13, 34_00, 14, 13, 61_89, 8, 9_30, 9, 6]], '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, 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]]} # noqa: E501
# fmt: on
# camembert is a french model. So we also use french texts.
a : Any = [
'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=__UpperCAmelCase , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=__UpperCAmelCase , )
| 509 | 1 |
import argparse
import hashlib
import os
import urllib
import warnings
import torch
from torch import nn
from tqdm import tqdm
from transformers import WhisperConfig, WhisperForConditionalGeneration
lowercase_ : int = {
'tiny.en': 'https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt',
'tiny': 'https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt',
'base.en': 'https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt',
'base': 'https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt',
'small.en': 'https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt',
'small': 'https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt',
'medium.en': 'https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt',
'medium': 'https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt',
'large': 'https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt',
'large-v2': 'https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt',
}
def A__ ( snake_case_ : List[Any] ):
SCREAMING_SNAKE_CASE__: Dict= ['''layers''', '''blocks''']
for k in ignore_keys:
state_dict.pop(snake_case_ , snake_case_ )
lowercase_ : Tuple = {
'blocks': 'layers',
'mlp.0': 'fc1',
'mlp.2': 'fc2',
'mlp_ln': 'final_layer_norm',
'.attn.query': '.self_attn.q_proj',
'.attn.key': '.self_attn.k_proj',
'.attn.value': '.self_attn.v_proj',
'.attn_ln': '.self_attn_layer_norm',
'.attn.out': '.self_attn.out_proj',
'.cross_attn.query': '.encoder_attn.q_proj',
'.cross_attn.key': '.encoder_attn.k_proj',
'.cross_attn.value': '.encoder_attn.v_proj',
'.cross_attn_ln': '.encoder_attn_layer_norm',
'.cross_attn.out': '.encoder_attn.out_proj',
'decoder.ln.': 'decoder.layer_norm.',
'encoder.ln.': 'encoder.layer_norm.',
'token_embedding': 'embed_tokens',
'encoder.positional_embedding': 'encoder.embed_positions.weight',
'decoder.positional_embedding': 'decoder.embed_positions.weight',
'ln_post': 'layer_norm',
}
def A__ ( snake_case_ : Optional[int] ):
SCREAMING_SNAKE_CASE__: Optional[int]= list(s_dict.keys() )
for key in keys:
SCREAMING_SNAKE_CASE__: List[Any]= key
for k, v in WHISPER_MAPPING.items():
if k in key:
SCREAMING_SNAKE_CASE__: int= new_key.replace(snake_case_ , snake_case_ )
print(F'{key} -> {new_key}' )
SCREAMING_SNAKE_CASE__: Union[str, Any]= s_dict.pop(snake_case_ )
return s_dict
def A__ ( snake_case_ : Tuple ):
SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: str= emb.weight.shape
SCREAMING_SNAKE_CASE__: str= nn.Linear(snake_case_ , snake_case_ , bias=snake_case_ )
SCREAMING_SNAKE_CASE__: Any= emb.weight.data
return lin_layer
def A__ ( snake_case_ : str , snake_case_ : str ):
os.makedirs(snake_case_ , exist_ok=snake_case_ )
SCREAMING_SNAKE_CASE__: Tuple= os.path.basename(snake_case_ )
SCREAMING_SNAKE_CASE__: Optional[Any]= url.split('''/''' )[-2]
SCREAMING_SNAKE_CASE__: List[Any]= os.path.join(snake_case_ , snake_case_ )
if os.path.exists(snake_case_ ) and not os.path.isfile(snake_case_ ):
raise RuntimeError(F'{download_target} exists and is not a regular file' )
if os.path.isfile(snake_case_ ):
SCREAMING_SNAKE_CASE__: Tuple= open(snake_case_ , '''rb''' ).read()
if hashlib.shaaaa(snake_case_ ).hexdigest() == expected_shaaaa:
return model_bytes
else:
warnings.warn(F'{download_target} exists, but the SHA256 checksum does not match; re-downloading the file' )
with urllib.request.urlopen(snake_case_ ) as source, open(snake_case_ , '''wb''' ) as output:
with tqdm(
total=int(source.info().get('''Content-Length''' ) ) , ncols=80 , unit='''iB''' , unit_scale=snake_case_ , unit_divisor=1_024 ) as loop:
while True:
SCREAMING_SNAKE_CASE__: List[str]= source.read(8_192 )
if not buffer:
break
output.write(snake_case_ )
loop.update(len(snake_case_ ) )
SCREAMING_SNAKE_CASE__: Optional[Any]= open(snake_case_ , '''rb''' ).read()
if hashlib.shaaaa(snake_case_ ).hexdigest() != expected_shaaaa:
raise RuntimeError(
'''Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.''' )
return model_bytes
def A__ ( snake_case_ : Optional[Any] , snake_case_ : int ):
if ".pt" not in checkpoint_path:
SCREAMING_SNAKE_CASE__: Dict= _download(_MODELS[checkpoint_path] )
else:
SCREAMING_SNAKE_CASE__: Tuple= torch.load(snake_case_ , map_location='''cpu''' )
SCREAMING_SNAKE_CASE__: str= original_checkpoint['''dims''']
SCREAMING_SNAKE_CASE__: Optional[Any]= original_checkpoint['''model_state_dict''']
SCREAMING_SNAKE_CASE__: Any= state_dict['''decoder.token_embedding.weight''']
remove_ignore_keys_(snake_case_ )
rename_keys(snake_case_ )
SCREAMING_SNAKE_CASE__: Optional[Any]= True
SCREAMING_SNAKE_CASE__: Optional[int]= state_dict['''decoder.layers.0.fc1.weight'''].shape[0]
SCREAMING_SNAKE_CASE__: Dict= WhisperConfig(
vocab_size=dimensions['''n_vocab'''] , encoder_ffn_dim=snake_case_ , decoder_ffn_dim=snake_case_ , num_mel_bins=dimensions['''n_mels'''] , d_model=dimensions['''n_audio_state'''] , max_target_positions=dimensions['''n_text_ctx'''] , encoder_layers=dimensions['''n_audio_layer'''] , encoder_attention_heads=dimensions['''n_audio_head'''] , decoder_layers=dimensions['''n_text_layer'''] , decoder_attention_heads=dimensions['''n_text_state'''] , max_source_positions=dimensions['''n_audio_ctx'''] , )
SCREAMING_SNAKE_CASE__: str= WhisperForConditionalGeneration(snake_case_ )
SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Dict= model.model.load_state_dict(snake_case_ , strict=snake_case_ )
if len(snake_case_ ) > 0 and not set(snake_case_ ) <= {
"encoder.embed_positions.weights",
"decoder.embed_positions.weights",
}:
raise ValueError(
'''Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,'''
F' but all the following weights are missing {missing}' )
if tie_embeds:
SCREAMING_SNAKE_CASE__: List[Any]= make_linear_from_emb(model.model.decoder.embed_tokens )
else:
SCREAMING_SNAKE_CASE__: str= proj_out_weights
model.save_pretrained(snake_case_ )
if __name__ == "__main__":
lowercase_ : int = argparse.ArgumentParser()
# # Required parameters
parser.add_argument('--checkpoint_path', type=str, help='Patht to the downloaded checkpoints')
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
lowercase_ : int = parser.parse_args()
convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
| 64 |
from collections import OrderedDict
from ...utils import logging
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from .configuration_auto import CONFIG_MAPPING_NAMES
__UpperCamelCase : List[str] = logging.get_logger(__name__)
__UpperCamelCase : List[str] = OrderedDict(
[
# Base model mapping
("""albert""", """FlaxAlbertModel"""),
("""bart""", """FlaxBartModel"""),
("""beit""", """FlaxBeitModel"""),
("""bert""", """FlaxBertModel"""),
("""big_bird""", """FlaxBigBirdModel"""),
("""blenderbot""", """FlaxBlenderbotModel"""),
("""blenderbot-small""", """FlaxBlenderbotSmallModel"""),
("""clip""", """FlaxCLIPModel"""),
("""distilbert""", """FlaxDistilBertModel"""),
("""electra""", """FlaxElectraModel"""),
("""gpt-sw3""", """FlaxGPT2Model"""),
("""gpt2""", """FlaxGPT2Model"""),
("""gpt_neo""", """FlaxGPTNeoModel"""),
("""gptj""", """FlaxGPTJModel"""),
("""longt5""", """FlaxLongT5Model"""),
("""marian""", """FlaxMarianModel"""),
("""mbart""", """FlaxMBartModel"""),
("""mt5""", """FlaxMT5Model"""),
("""opt""", """FlaxOPTModel"""),
("""pegasus""", """FlaxPegasusModel"""),
("""regnet""", """FlaxRegNetModel"""),
("""resnet""", """FlaxResNetModel"""),
("""roberta""", """FlaxRobertaModel"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""),
("""roformer""", """FlaxRoFormerModel"""),
("""t5""", """FlaxT5Model"""),
("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""),
("""vit""", """FlaxViTModel"""),
("""wav2vec2""", """FlaxWav2Vec2Model"""),
("""whisper""", """FlaxWhisperModel"""),
("""xglm""", """FlaxXGLMModel"""),
("""xlm-roberta""", """FlaxXLMRobertaModel"""),
]
)
__UpperCamelCase : Tuple = OrderedDict(
[
# Model for pre-training mapping
("""albert""", """FlaxAlbertForPreTraining"""),
("""bart""", """FlaxBartForConditionalGeneration"""),
("""bert""", """FlaxBertForPreTraining"""),
("""big_bird""", """FlaxBigBirdForPreTraining"""),
("""electra""", """FlaxElectraForPreTraining"""),
("""longt5""", """FlaxLongT5ForConditionalGeneration"""),
("""mbart""", """FlaxMBartForConditionalGeneration"""),
("""mt5""", """FlaxMT5ForConditionalGeneration"""),
("""roberta""", """FlaxRobertaForMaskedLM"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""),
("""roformer""", """FlaxRoFormerForMaskedLM"""),
("""t5""", """FlaxT5ForConditionalGeneration"""),
("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""),
("""whisper""", """FlaxWhisperForConditionalGeneration"""),
("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""),
]
)
__UpperCamelCase : Optional[Any] = OrderedDict(
[
# Model for Masked LM mapping
("""albert""", """FlaxAlbertForMaskedLM"""),
("""bart""", """FlaxBartForConditionalGeneration"""),
("""bert""", """FlaxBertForMaskedLM"""),
("""big_bird""", """FlaxBigBirdForMaskedLM"""),
("""distilbert""", """FlaxDistilBertForMaskedLM"""),
("""electra""", """FlaxElectraForMaskedLM"""),
("""mbart""", """FlaxMBartForConditionalGeneration"""),
("""roberta""", """FlaxRobertaForMaskedLM"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""),
("""roformer""", """FlaxRoFormerForMaskedLM"""),
("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""),
]
)
__UpperCamelCase : Optional[Any] = OrderedDict(
[
# Model for Seq2Seq Causal LM mapping
("""bart""", """FlaxBartForConditionalGeneration"""),
("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""),
("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""),
("""encoder-decoder""", """FlaxEncoderDecoderModel"""),
("""longt5""", """FlaxLongT5ForConditionalGeneration"""),
("""marian""", """FlaxMarianMTModel"""),
("""mbart""", """FlaxMBartForConditionalGeneration"""),
("""mt5""", """FlaxMT5ForConditionalGeneration"""),
("""pegasus""", """FlaxPegasusForConditionalGeneration"""),
("""t5""", """FlaxT5ForConditionalGeneration"""),
]
)
__UpperCamelCase : int = OrderedDict(
[
# Model for Image-classsification
("""beit""", """FlaxBeitForImageClassification"""),
("""regnet""", """FlaxRegNetForImageClassification"""),
("""resnet""", """FlaxResNetForImageClassification"""),
("""vit""", """FlaxViTForImageClassification"""),
]
)
__UpperCamelCase : List[Any] = OrderedDict(
[
("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""),
]
)
__UpperCamelCase : List[Any] = OrderedDict(
[
# Model for Causal LM mapping
("""bart""", """FlaxBartForCausalLM"""),
("""bert""", """FlaxBertForCausalLM"""),
("""big_bird""", """FlaxBigBirdForCausalLM"""),
("""electra""", """FlaxElectraForCausalLM"""),
("""gpt-sw3""", """FlaxGPT2LMHeadModel"""),
("""gpt2""", """FlaxGPT2LMHeadModel"""),
("""gpt_neo""", """FlaxGPTNeoForCausalLM"""),
("""gptj""", """FlaxGPTJForCausalLM"""),
("""opt""", """FlaxOPTForCausalLM"""),
("""roberta""", """FlaxRobertaForCausalLM"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""),
("""xglm""", """FlaxXGLMForCausalLM"""),
("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""),
]
)
__UpperCamelCase : List[str] = OrderedDict(
[
# Model for Sequence Classification mapping
("""albert""", """FlaxAlbertForSequenceClassification"""),
("""bart""", """FlaxBartForSequenceClassification"""),
("""bert""", """FlaxBertForSequenceClassification"""),
("""big_bird""", """FlaxBigBirdForSequenceClassification"""),
("""distilbert""", """FlaxDistilBertForSequenceClassification"""),
("""electra""", """FlaxElectraForSequenceClassification"""),
("""mbart""", """FlaxMBartForSequenceClassification"""),
("""roberta""", """FlaxRobertaForSequenceClassification"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""),
("""roformer""", """FlaxRoFormerForSequenceClassification"""),
("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""),
]
)
__UpperCamelCase : List[str] = OrderedDict(
[
# Model for Question Answering mapping
("""albert""", """FlaxAlbertForQuestionAnswering"""),
("""bart""", """FlaxBartForQuestionAnswering"""),
("""bert""", """FlaxBertForQuestionAnswering"""),
("""big_bird""", """FlaxBigBirdForQuestionAnswering"""),
("""distilbert""", """FlaxDistilBertForQuestionAnswering"""),
("""electra""", """FlaxElectraForQuestionAnswering"""),
("""mbart""", """FlaxMBartForQuestionAnswering"""),
("""roberta""", """FlaxRobertaForQuestionAnswering"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""),
("""roformer""", """FlaxRoFormerForQuestionAnswering"""),
("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""),
]
)
__UpperCamelCase : int = OrderedDict(
[
# Model for Token Classification mapping
("""albert""", """FlaxAlbertForTokenClassification"""),
("""bert""", """FlaxBertForTokenClassification"""),
("""big_bird""", """FlaxBigBirdForTokenClassification"""),
("""distilbert""", """FlaxDistilBertForTokenClassification"""),
("""electra""", """FlaxElectraForTokenClassification"""),
("""roberta""", """FlaxRobertaForTokenClassification"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""),
("""roformer""", """FlaxRoFormerForTokenClassification"""),
("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""),
]
)
__UpperCamelCase : Dict = OrderedDict(
[
# Model for Multiple Choice mapping
("""albert""", """FlaxAlbertForMultipleChoice"""),
("""bert""", """FlaxBertForMultipleChoice"""),
("""big_bird""", """FlaxBigBirdForMultipleChoice"""),
("""distilbert""", """FlaxDistilBertForMultipleChoice"""),
("""electra""", """FlaxElectraForMultipleChoice"""),
("""roberta""", """FlaxRobertaForMultipleChoice"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""),
("""roformer""", """FlaxRoFormerForMultipleChoice"""),
("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""),
]
)
__UpperCamelCase : str = OrderedDict(
[
("""bert""", """FlaxBertForNextSentencePrediction"""),
]
)
__UpperCamelCase : Optional[int] = OrderedDict(
[
("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""),
("""whisper""", """FlaxWhisperForConditionalGeneration"""),
]
)
__UpperCamelCase : Dict = OrderedDict(
[
("""whisper""", """FlaxWhisperForAudioClassification"""),
]
)
__UpperCamelCase : List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
__UpperCamelCase : str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
__UpperCamelCase : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
__UpperCamelCase : Dict = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
__UpperCamelCase : Dict = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
__UpperCamelCase : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
__UpperCamelCase : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
__UpperCamelCase : Tuple = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
)
__UpperCamelCase : Any = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
__UpperCamelCase : Union[str, Any] = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
)
__UpperCamelCase : Tuple = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
)
__UpperCamelCase : str = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
)
__UpperCamelCase : List[str] = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
)
__UpperCamelCase : Optional[Any] = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Tuple = FLAX_MODEL_MAPPING
__UpperCamelCase : Tuple = auto_class_update(FlaxAutoModel)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Union[str, Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING
__UpperCamelCase : List[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Dict = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
__UpperCamelCase : Union[str, Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :List[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING
__UpperCamelCase : Dict = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
__UpperCamelCase : Optional[Any] = auto_class_update(
FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
__UpperCamelCase : Optional[int] = auto_class_update(
FlaxAutoModelForSequenceClassification, head_doc="""sequence classification"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
__UpperCamelCase : Union[str, Any] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :List[Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
__UpperCamelCase : Optional[int] = auto_class_update(
FlaxAutoModelForTokenClassification, head_doc="""token classification"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[int] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
__UpperCamelCase : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :str = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
__UpperCamelCase : int = auto_class_update(
FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
__UpperCamelCase : Optional[Any] = auto_class_update(
FlaxAutoModelForImageClassification, head_doc="""image classification"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
__UpperCamelCase : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
__UpperCamelCase : str = auto_class_update(
FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling"""
)
| 80 | 0 |
"""simple docstring"""
import random
import unittest
import numpy as np
from diffusers import (
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionImgaImgPipeline,
PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
is_onnx_available,
load_image,
nightly,
require_onnxruntime,
require_torch_gpu,
)
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class lowercase_ ( __lowerCAmelCase , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase : Optional[Any] = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''
def lowerCAmelCase_ ( self : str , _UpperCAmelCase : Any=0 ):
_A = floats_tensor((1, 3, 128, 128) , rng=random.Random(_UpperCAmelCase ) )
_A = np.random.RandomState(_UpperCAmelCase )
_A = {
'prompt': 'A painting of a squirrel eating a burger',
'image': image,
'generator': generator,
'num_inference_steps': 3,
'strength': 0.75,
'guidance_scale': 7.5,
'output_type': 'numpy',
}
return inputs
def lowerCAmelCase_ ( self : Tuple ):
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = self.get_dummy_inputs()
_A = pipe(**_UpperCAmelCase ).images
_A = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 128, 128, 3)
_A = np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087] )
assert np.abs(image_slice - expected_slice ).max() < 1E-1
def lowerCAmelCase_ ( self : int ):
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
_A = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_UpperCAmelCase )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = self.get_dummy_inputs()
_A = pipe(**_UpperCAmelCase ).images
_A = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
_A = np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def lowerCAmelCase_ ( self : List[Any] ):
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
_A = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
# warmup pass to apply optimizations
_A = pipe(**self.get_dummy_inputs() )
_A = self.get_dummy_inputs()
_A = pipe(**_UpperCAmelCase ).images
_A = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
_A = np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def lowerCAmelCase_ ( self : Dict ):
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
_A = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = self.get_dummy_inputs()
_A = pipe(**_UpperCAmelCase ).images
_A = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
_A = np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def lowerCAmelCase_ ( self : int ):
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
_A = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = self.get_dummy_inputs()
_A = pipe(**_UpperCAmelCase ).images
_A = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
_A = np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
def lowerCAmelCase_ ( self : Dict ):
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
_A = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = self.get_dummy_inputs()
_A = pipe(**_UpperCAmelCase ).images
_A = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
_A = np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
@nightly
@require_onnxruntime
@require_torch_gpu
class lowercase_ ( unittest.TestCase ):
'''simple docstring'''
@property
def lowerCAmelCase_ ( self : Union[str, Any] ):
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def lowerCAmelCase_ ( self : Dict ):
_A = ort.SessionOptions()
_A = False
return options
def lowerCAmelCase_ ( self : List[str] ):
_A = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
_A = init_image.resize((768, 512) )
# using the PNDM scheduler by default
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_UpperCAmelCase , feature_extractor=_UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = 'A fantasy landscape, trending on artstation'
_A = np.random.RandomState(0 )
_A = pipe(
prompt=_UpperCAmelCase , image=_UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=_UpperCAmelCase , output_type='np' , )
_A = output.images
_A = images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 768, 3)
_A = np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
def lowerCAmelCase_ ( self : Any ):
_A = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
_A = init_image.resize((768, 512) )
_A = LMSDiscreteScheduler.from_pretrained(
'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' )
_A = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=_UpperCAmelCase , safety_checker=_UpperCAmelCase , feature_extractor=_UpperCAmelCase , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_UpperCAmelCase )
_A = 'A fantasy landscape, trending on artstation'
_A = np.random.RandomState(0 )
_A = pipe(
prompt=_UpperCAmelCase , image=_UpperCAmelCase , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=_UpperCAmelCase , output_type='np' , )
_A = output.images
_A = images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 768, 3)
_A = np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
| 505 |
"""simple docstring"""
from ....configuration_utils import PretrainedConfig
from ....utils import logging
a = logging.get_logger(__name__)
a = {
'''Visual-Attention-Network/van-base''': (
'''https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json'''
),
}
class lowercase_ ( __lowerCAmelCase ):
'''simple docstring'''
UpperCAmelCase : List[str] = '''van'''
def __init__( self : Optional[Any] , _UpperCAmelCase : Union[str, Any]=224 , _UpperCAmelCase : Optional[Any]=3 , _UpperCAmelCase : Optional[Any]=[7, 3, 3, 3] , _UpperCAmelCase : Optional[int]=[4, 2, 2, 2] , _UpperCAmelCase : Tuple=[64, 128, 320, 512] , _UpperCAmelCase : Optional[int]=[3, 3, 12, 3] , _UpperCAmelCase : Union[str, Any]=[8, 8, 4, 4] , _UpperCAmelCase : List[Any]="gelu" , _UpperCAmelCase : int=0.02 , _UpperCAmelCase : List[Any]=1E-6 , _UpperCAmelCase : Optional[Any]=1E-2 , _UpperCAmelCase : Optional[Any]=0.0 , _UpperCAmelCase : Union[str, Any]=0.0 , **_UpperCAmelCase : str , ):
super().__init__(**_UpperCAmelCase )
_A = image_size
_A = num_channels
_A = patch_sizes
_A = strides
_A = hidden_sizes
_A = depths
_A = mlp_ratios
_A = hidden_act
_A = initializer_range
_A = layer_norm_eps
_A = layer_scale_init_value
_A = drop_path_rate
_A = dropout_rate
| 505 | 1 |
"""simple docstring"""
from typing import Any
class a :
def __init__( self , _snake_case ):
"""simple docstring"""
lowerCAmelCase = data
lowerCAmelCase = None
def __repr__( self ):
"""simple docstring"""
return F'Node({self.data})'
class a :
def __init__( self ):
"""simple docstring"""
lowerCAmelCase = None
def __iter__( self ):
"""simple docstring"""
lowerCAmelCase = self.head
while node:
yield node.data
lowerCAmelCase = node.next
def __len__( self ):
"""simple docstring"""
return sum(1 for _ in self )
def __repr__( self ):
"""simple docstring"""
return "->".join([str(_snake_case ) for item in self] )
def __getitem__( self , _snake_case ):
"""simple docstring"""
if not 0 <= index < len(self ):
raise ValueError('list index out of range.' )
for i, node in enumerate(self ):
if i == index:
return node
return None
def __setitem__( self , _snake_case , _snake_case ):
"""simple docstring"""
if not 0 <= index < len(self ):
raise ValueError('list index out of range.' )
lowerCAmelCase = self.head
for _ in range(_snake_case ):
lowerCAmelCase = current.next
lowerCAmelCase = data
def UpperCamelCase__ ( self , _snake_case ):
"""simple docstring"""
self.insert_nth(len(self ) , _snake_case )
def UpperCamelCase__ ( self , _snake_case ):
"""simple docstring"""
self.insert_nth(0 , _snake_case )
def UpperCamelCase__ ( self , _snake_case , _snake_case ):
"""simple docstring"""
if not 0 <= index <= len(self ):
raise IndexError('list index out of range' )
lowerCAmelCase = Node(_snake_case )
if self.head is None:
lowerCAmelCase = new_node
elif index == 0:
lowerCAmelCase = self.head # link new_node to head
lowerCAmelCase = new_node
else:
lowerCAmelCase = self.head
for _ in range(index - 1 ):
lowerCAmelCase = temp.next
lowerCAmelCase = temp.next
lowerCAmelCase = new_node
def UpperCamelCase__ ( self ): # print every node data
"""simple docstring"""
print(self )
def UpperCamelCase__ ( self ):
"""simple docstring"""
return self.delete_nth(0 )
def UpperCamelCase__ ( self ): # delete from tail
"""simple docstring"""
return self.delete_nth(len(self ) - 1 )
def UpperCamelCase__ ( self , _snake_case = 0 ):
"""simple docstring"""
if not 0 <= index <= len(self ) - 1: # test if index is valid
raise IndexError('List index out of range.' )
lowerCAmelCase = self.head # default first node
if index == 0:
lowerCAmelCase = self.head.next
else:
lowerCAmelCase = self.head
for _ in range(index - 1 ):
lowerCAmelCase = temp.next
lowerCAmelCase = temp.next
lowerCAmelCase = temp.next.next
return delete_node.data
def UpperCamelCase__ ( self ):
"""simple docstring"""
return self.head is None
def UpperCamelCase__ ( self ):
"""simple docstring"""
lowerCAmelCase = None
lowerCAmelCase = self.head
while current:
# Store the current node's next node.
lowerCAmelCase = current.next
# Make the current node's next point backwards
lowerCAmelCase = prev
# Make the previous node be the current node
lowerCAmelCase = current
# Make the current node the next node (to progress iteration)
lowerCAmelCase = next_node
# Return prev in order to put the head at the end
lowerCAmelCase = prev
def _SCREAMING_SNAKE_CASE ():
lowerCAmelCase = LinkedList()
assert linked_list.is_empty() is True
assert str(_UpperCAmelCase ) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10 ):
assert len(_UpperCAmelCase ) == i
linked_list.insert_nth(_UpperCAmelCase , i + 1 )
assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 11 ) )
linked_list.insert_head(0 )
linked_list.insert_tail(11 )
assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(0 , 12 ) )
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9 ) == 10
assert linked_list.delete_tail() == 11
assert len(_UpperCAmelCase ) == 9
assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(1 , 10 ) )
assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True
for i in range(0 , 9 ):
lowerCAmelCase = -i
assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True
linked_list.reverse()
assert str(_UpperCAmelCase ) == "->".join(str(_UpperCAmelCase ) for i in range(-8 , 1 ) )
def _SCREAMING_SNAKE_CASE ():
lowerCAmelCase = [
-9,
100,
Node(7734_5112 ),
'dlrow olleH',
7,
5555,
0,
-192.5_5555,
'Hello, world!',
77.9,
Node(10 ),
None,
None,
12.20,
]
lowerCAmelCase = LinkedList()
for i in test_input:
linked_list.insert_tail(_UpperCAmelCase )
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(_UpperCAmelCase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
lowerCAmelCase = linked_list.delete_head()
assert result == -9
assert (
str(_UpperCAmelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
lowerCAmelCase = linked_list.delete_tail()
assert result == 12.2
assert (
str(_UpperCAmelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None"
)
# Delete a node in specific location in linked list
lowerCAmelCase = linked_list.delete_nth(10 )
assert result is None
assert (
str(_UpperCAmelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None"
)
# Add a Node instance to its head
linked_list.insert_head(Node('Hello again, world!' ) )
assert (
str(_UpperCAmelCase )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None"
)
# Add None to its tail
linked_list.insert_tail(_UpperCAmelCase )
assert (
str(_UpperCAmelCase )
== "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->"
"7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(_UpperCAmelCase )
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def _SCREAMING_SNAKE_CASE ():
from doctest import testmod
testmod()
lowerCAmelCase = LinkedList()
linked_list.insert_head(input('Inserting 1st at head ' ).strip() )
linked_list.insert_head(input('Inserting 2nd at head ' ).strip() )
print('\nPrint list:' )
linked_list.print_list()
linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() )
linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() )
print('\nPrint list:' )
linked_list.print_list()
print('\nDelete head' )
linked_list.delete_head()
print('Delete tail' )
linked_list.delete_tail()
print('\nPrint list:' )
linked_list.print_list()
print('\nReverse linked list' )
linked_list.reverse()
print('\nPrint list:' )
linked_list.print_list()
print('\nString representation of linked list:' )
print(_UpperCAmelCase )
print('\nReading/changing Node data using indexing:' )
print(F'Element at Position 1: {linked_list[1]}' )
lowerCAmelCase = input('Enter New Value: ' ).strip()
print('New list:' )
print(_UpperCAmelCase )
print(F'length of linked_list is : {len(_UpperCAmelCase )}' )
if __name__ == "__main__":
main()
| 4 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__A : Dict = {
"configuration_blenderbot": [
"BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BlenderbotConfig",
"BlenderbotOnnxConfig",
],
"tokenization_blenderbot": ["BlenderbotTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : str = ["BlenderbotTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : str = [
"BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlenderbotForCausalLM",
"BlenderbotForConditionalGeneration",
"BlenderbotModel",
"BlenderbotPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Union[str, Any] = [
"TFBlenderbotForConditionalGeneration",
"TFBlenderbotModel",
"TFBlenderbotPreTrainedModel",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Optional[Any] = [
"FlaxBlenderbotForConditionalGeneration",
"FlaxBlenderbotModel",
"FlaxBlenderbotPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_blenderbot import (
BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotConfig,
BlenderbotOnnxConfig,
)
from .tokenization_blenderbot import BlenderbotTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot import (
BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotForCausalLM,
BlenderbotForConditionalGeneration,
BlenderbotModel,
BlenderbotPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot import (
TFBlenderbotForConditionalGeneration,
TFBlenderbotModel,
TFBlenderbotPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
FlaxBlenderbotPreTrainedModel,
)
else:
import sys
__A : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 27 | 0 |
from copy import deepcopy
from typing import Optional, Union
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
class UpperCAmelCase ( __snake_case ):
a: Dict = ["image_processor"]
a: Optional[int] = "SamImageProcessor"
def __init__( self: Optional[int] , __UpperCamelCase: Optional[Any] ):
super().__init__(__UpperCamelCase )
_a = self.image_processor
_a = -10
_a = self.image_processor.size['''longest_edge''']
def __call__( self: Tuple , __UpperCamelCase: Union[str, Any]=None , __UpperCamelCase: int=None , __UpperCamelCase: Tuple=None , __UpperCamelCase: Optional[int]=None , __UpperCamelCase: Optional[Union[str, TensorType]] = None , **__UpperCamelCase: int , ):
_a = self.image_processor(
__UpperCamelCase , return_tensors=__UpperCamelCase , **__UpperCamelCase , )
# pop arguments that are not used in the foward but used nevertheless
_a = encoding_image_processor['''original_sizes''']
if hasattr(__UpperCamelCase , '''numpy''' ): # Checks if Torch or TF tensor
_a = original_sizes.numpy()
_a , _a , _a = self._check_and_preprocess_points(
input_points=__UpperCamelCase , input_labels=__UpperCamelCase , input_boxes=__UpperCamelCase , )
_a = self._normalize_and_convert(
__UpperCamelCase , __UpperCamelCase , input_points=__UpperCamelCase , input_labels=__UpperCamelCase , input_boxes=__UpperCamelCase , return_tensors=__UpperCamelCase , )
return encoding_image_processor
def _A ( self: Optional[int] , __UpperCamelCase: Tuple , __UpperCamelCase: Optional[Any] , __UpperCamelCase: str=None , __UpperCamelCase: int=None , __UpperCamelCase: List[Any]=None , __UpperCamelCase: Tuple="pt" , ):
if input_points is not None:
if len(__UpperCamelCase ) != len(__UpperCamelCase ):
_a = [
self._normalize_coordinates(self.target_size , __UpperCamelCase , original_sizes[0] ) for point in input_points
]
else:
_a = [
self._normalize_coordinates(self.target_size , __UpperCamelCase , __UpperCamelCase )
for point, original_size in zip(__UpperCamelCase , __UpperCamelCase )
]
# check that all arrays have the same shape
if not all(point.shape == input_points[0].shape for point in input_points ):
if input_labels is not None:
_a , _a = self._pad_points_and_labels(__UpperCamelCase , __UpperCamelCase )
_a = np.array(__UpperCamelCase )
if input_labels is not None:
_a = np.array(__UpperCamelCase )
if input_boxes is not None:
if len(__UpperCamelCase ) != len(__UpperCamelCase ):
_a = [
self._normalize_coordinates(self.target_size , __UpperCamelCase , original_sizes[0] , is_bounding_box=__UpperCamelCase )
for box in input_boxes
]
else:
_a = [
self._normalize_coordinates(self.target_size , __UpperCamelCase , __UpperCamelCase , is_bounding_box=__UpperCamelCase )
for box, original_size in zip(__UpperCamelCase , __UpperCamelCase )
]
_a = np.array(__UpperCamelCase )
if input_boxes is not None:
if return_tensors == "pt":
_a = torch.from_numpy(__UpperCamelCase )
# boxes batch size of 1 by default
_a = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes
elif return_tensors == "tf":
_a = tf.convert_to_tensor(__UpperCamelCase )
# boxes batch size of 1 by default
_a = tf.expand_dims(__UpperCamelCase , 1 ) if len(input_boxes.shape ) != 3 else input_boxes
encoding_image_processor.update({'''input_boxes''': input_boxes} )
if input_points is not None:
if return_tensors == "pt":
_a = torch.from_numpy(__UpperCamelCase )
# point batch size of 1 by default
_a = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points
elif return_tensors == "tf":
_a = tf.convert_to_tensor(__UpperCamelCase )
# point batch size of 1 by default
_a = tf.expand_dims(__UpperCamelCase , 1 ) if len(input_points.shape ) != 4 else input_points
encoding_image_processor.update({'''input_points''': input_points} )
if input_labels is not None:
if return_tensors == "pt":
_a = torch.from_numpy(__UpperCamelCase )
# point batch size of 1 by default
_a = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels
elif return_tensors == "tf":
_a = tf.convert_to_tensor(__UpperCamelCase )
# point batch size of 1 by default
_a = tf.expand_dims(__UpperCamelCase , 1 ) if len(input_labels.shape ) != 3 else input_labels
encoding_image_processor.update({'''input_labels''': input_labels} )
return encoding_image_processor
def _A ( self: Tuple , __UpperCamelCase: str , __UpperCamelCase: Tuple ):
_a = max([point.shape[0] for point in input_points] )
_a = []
for i, point in enumerate(__UpperCamelCase ):
if point.shape[0] != expected_nb_points:
_a = np.concatenate(
[point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 )
_a = np.append(input_labels[i] , [self.point_pad_value] )
processed_input_points.append(__UpperCamelCase )
_a = processed_input_points
return input_points, input_labels
def _A ( self: List[str] , __UpperCamelCase: int , __UpperCamelCase: np.ndarray , __UpperCamelCase: Dict , __UpperCamelCase: Optional[Any]=False ):
_a , _a = original_size
_a , _a = self.image_processor._get_preprocess_shape(__UpperCamelCase , longest_edge=__UpperCamelCase )
_a = deepcopy(__UpperCamelCase ).astype(__UpperCamelCase )
if is_bounding_box:
_a = coords.reshape(-1 , 2 , 2 )
_a = coords[..., 0] * (new_w / old_w)
_a = coords[..., 1] * (new_h / old_h)
if is_bounding_box:
_a = coords.reshape(-1 , 4 )
return coords
def _A ( self: List[Any] , __UpperCamelCase: Tuple=None , __UpperCamelCase: List[Any]=None , __UpperCamelCase: Dict=None , ):
if input_points is not None:
if hasattr(__UpperCamelCase , '''numpy''' ): # Checks for TF or Torch tensor
_a = input_points.numpy().tolist()
if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not isinstance(input_points[0] , __UpperCamelCase ):
raise ValueError('''Input points must be a list of list of floating points.''' )
_a = [np.array(__UpperCamelCase ) for input_point in input_points]
else:
_a = None
if input_labels is not None:
if hasattr(__UpperCamelCase , '''numpy''' ):
_a = input_labels.numpy().tolist()
if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not isinstance(input_labels[0] , __UpperCamelCase ):
raise ValueError('''Input labels must be a list of list integers.''' )
_a = [np.array(__UpperCamelCase ) for label in input_labels]
else:
_a = None
if input_boxes is not None:
if hasattr(__UpperCamelCase , '''numpy''' ):
_a = input_boxes.numpy().tolist()
if (
not isinstance(__UpperCamelCase , __UpperCamelCase )
or not isinstance(input_boxes[0] , __UpperCamelCase )
or not isinstance(input_boxes[0][0] , __UpperCamelCase )
):
raise ValueError('''Input boxes must be a list of list of list of floating points.''' )
_a = [np.array(__UpperCamelCase ).astype(np.floataa ) for box in input_boxes]
else:
_a = None
return input_points, input_labels, input_boxes
@property
def _A ( self: Optional[Any] ):
_a = self.image_processor.model_input_names
return list(dict.fromkeys(__UpperCamelCase ) )
def _A ( self: str , *__UpperCamelCase: Union[str, Any] , **__UpperCamelCase: Optional[int] ):
return self.image_processor.post_process_masks(*__UpperCamelCase , **__UpperCamelCase )
| 346 |
from collections.abc import Generator
from math import sin
def __snake_case ( _UpperCamelCase ) -> bytes:
if len(_UpperCamelCase ) != 32:
raise ValueError('''Input must be of length 32''' )
_a = b''''''
for i in [3, 2, 1, 0]:
little_endian += string_aa[8 * i : 8 * i + 8]
return little_endian
def __snake_case ( _UpperCamelCase ) -> bytes:
if i < 0:
raise ValueError('''Input must be non-negative''' )
_a = format(_UpperCamelCase , '''08x''' )[-8:]
_a = b''''''
for i in [3, 2, 1, 0]:
little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8''' )
return little_endian_hex
def __snake_case ( _UpperCamelCase ) -> bytes:
_a = b''''''
for char in message:
bit_string += format(_UpperCamelCase , '''08b''' ).encode('''utf-8''' )
_a = format(len(_UpperCamelCase ) , '''064b''' ).encode('''utf-8''' )
# Pad bit_string to a multiple of 512 chars
bit_string += b"1"
while len(_UpperCamelCase ) % 5_12 != 4_48:
bit_string += b"0"
bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] )
return bit_string
def __snake_case ( _UpperCamelCase ) -> Generator[list[int], None, None]:
if len(_UpperCamelCase ) % 5_12 != 0:
raise ValueError('''Input must have length that\'s a multiple of 512''' )
for pos in range(0 , len(_UpperCamelCase ) , 5_12 ):
_a = bit_string[pos : pos + 5_12]
_a = []
for i in range(0 , 5_12 , 32 ):
block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) )
yield block_words
def __snake_case ( _UpperCamelCase ) -> int:
if i < 0:
raise ValueError('''Input must be non-negative''' )
_a = format(_UpperCamelCase , '''032b''' )
_a = ''''''
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(_UpperCamelCase , 2 )
def __snake_case ( _UpperCamelCase , _UpperCamelCase ) -> int:
return (a + b) % 2**32
def __snake_case ( _UpperCamelCase , _UpperCamelCase ) -> int:
if i < 0:
raise ValueError('''Input must be non-negative''' )
if shift < 0:
raise ValueError('''Shift must be non-negative''' )
return ((i << shift) ^ (i >> (32 - shift))) % 2**32
def __snake_case ( _UpperCamelCase ) -> bytes:
_a = preprocess(_UpperCamelCase )
_a = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )]
# Starting states
_a = 0X67_45_23_01
_a = 0XEF_CD_AB_89
_a = 0X98_BA_DC_FE
_a = 0X10_32_54_76
_a = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
# Process bit string in chunks, each with 16 32-char words
for block_words in get_block_words(_UpperCamelCase ):
_a = aa
_a = ba
_a = ca
_a = da
# Hash current chunk
for i in range(64 ):
if i <= 15:
# f = (b & c) | (not_32(b) & d) # Alternate definition for f
_a = d ^ (b & (c ^ d))
_a = i
elif i <= 31:
# f = (d & b) | (not_32(d) & c) # Alternate definition for f
_a = c ^ (d & (b ^ c))
_a = (5 * i + 1) % 16
elif i <= 47:
_a = b ^ c ^ d
_a = (3 * i + 5) % 16
else:
_a = c ^ (b | not_aa(_UpperCamelCase ))
_a = (7 * i) % 16
_a = (f + a + added_consts[i] + block_words[g]) % 2**32
_a = d
_a = c
_a = b
_a = sum_aa(_UpperCamelCase , left_rotate_aa(_UpperCamelCase , shift_amounts[i] ) )
# Add hashed chunk to running total
_a = sum_aa(_UpperCamelCase , _UpperCamelCase )
_a = sum_aa(_UpperCamelCase , _UpperCamelCase )
_a = sum_aa(_UpperCamelCase , _UpperCamelCase )
_a = sum_aa(_UpperCamelCase , _UpperCamelCase )
_a = reformat_hex(_UpperCamelCase ) + reformat_hex(_UpperCamelCase ) + reformat_hex(_UpperCamelCase ) + reformat_hex(_UpperCamelCase )
return digest
if __name__ == "__main__":
import doctest
doctest.testmod()
| 346 | 1 |
'''simple docstring'''
import argparse
from typing import Dict
import tensorflow as tf
import torch
from tqdm import tqdm
from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration
lowerCAmelCase_ : List[Any] = [
# tf -> hf
('/', '.'),
('layer_', 'layers.'),
('kernel', 'weight'),
('beta', 'bias'),
('gamma', 'weight'),
('pegasus', 'model'),
]
lowerCAmelCase_ : Optional[int] = [
('.output.dense', '.fc2'),
('intermediate.LayerNorm', 'final_layer_norm'),
('intermediate.dense', 'fc1'),
]
lowerCAmelCase_ : Any = (
INIT_COMMON
+ [
('attention.self.LayerNorm', 'self_attn_layer_norm'),
('attention.output.dense', 'self_attn.out_proj'),
('attention.self', 'self_attn'),
('attention.encdec.LayerNorm', 'encoder_attn_layer_norm'),
('attention.encdec_output.dense', 'encoder_attn.out_proj'),
('attention.encdec', 'encoder_attn'),
('key', 'k_proj'),
('value', 'v_proj'),
('query', 'q_proj'),
('decoder.LayerNorm', 'decoder.layernorm_embedding'),
]
+ END_COMMON
)
lowerCAmelCase_ : Tuple = (
INIT_COMMON
+ [
('embeddings.word_embeddings', 'shared.weight'),
('embeddings.position_embeddings', 'embed_positions.weight'),
('attention.self.LayerNorm', 'self_attn_layer_norm'),
('attention.output.dense', 'self_attn.output'),
('attention.self', 'self_attn.self'),
('encoder.LayerNorm', 'encoder.layernorm_embedding'),
]
+ END_COMMON
)
lowerCAmelCase_ : Optional[int] = [
'encdec/key/bias',
'encdec/query/bias',
'encdec/value/bias',
'self/key/bias',
'self/query/bias',
'self/value/bias',
'encdec_output/dense/bias',
'attention/output/dense/bias',
]
def _lowerCamelCase ( lowercase : Any , lowercase : Any ) -> Optional[Any]:
for tf_name, hf_name in patterns:
_a = k.replace(lowercase , lowercase )
return k
def _lowerCamelCase ( lowercase : dict , lowercase : dict ) -> BigBirdPegasusForConditionalGeneration:
_a = BigBirdPegasusConfig(**lowercase )
_a = BigBirdPegasusForConditionalGeneration(lowercase )
_a = torch_model.state_dict()
_a = {}
# separating decoder weights
_a = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )}
_a = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )}
for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ):
_a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE]
if any(lowercase ):
continue
_a = DECODER_PATTERNS
_a = rename_state_dict_key(lowercase , lowercase )
if new_k not in state_dict:
raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' )
if any(True if i in k else False for i in ["dense", "query", "key", "value"] ):
_a = v.T
_a = torch.from_numpy(lowercase )
assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'
for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ):
_a = [k.endswith(lowercase ) for ending in KEYS_TO_IGNORE]
if any(lowercase ):
continue
_a = REMAINING_PATTERNS
_a = rename_state_dict_key(lowercase , lowercase )
if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings":
raise ValueError(F'could not find new key {new_k} in state dict. (converted from {k})' )
if any(True if i in k else False for i in ["dense", "query", "key", "value"] ):
_a = v.T
_a = torch.from_numpy(lowercase )
if k != "pegasus/embeddings/position_embeddings":
assert v.shape == state_dict[new_k].shape, F'{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'
_a = mapping["model.embed_positions.weight"]
_a = mapping.pop("model.embed_positions.weight" )
_a , _a = torch_model.load_state_dict(lowercase , strict=lowercase )
_a = [
k
for k in missing
if k
not in [
"final_logits_bias",
"model.encoder.embed_tokens.weight",
"model.decoder.embed_tokens.weight",
"lm_head.weight",
]
]
assert unexpected_missing == [], F'no matches found for the following torch keys {unexpected_missing}'
assert extra == [], F'no matches found for the following tf keys {extra}'
return torch_model
def _lowerCamelCase ( lowercase : List[Any] ) -> Dict:
_a = tf.train.list_variables(lowercase )
_a = {}
_a = ["global_step"]
for name, shape in tqdm(lowercase , desc="converting tf checkpoint to dict" ):
_a = any(pat in name for pat in ignore_name )
if skip_key:
continue
_a = tf.train.load_variable(lowercase , lowercase )
_a = array
return tf_weights
def _lowerCamelCase ( lowercase : str , lowercase : str , lowercase : dict ) -> Union[str, Any]:
_a = get_tf_weights_as_numpy(lowercase )
_a = convert_bigbird_pegasus(lowercase , lowercase )
torch_model.save_pretrained(lowercase )
if __name__ == "__main__":
lowerCAmelCase_ : str = argparse.ArgumentParser()
parser.add_argument('--tf_ckpt_path', type=str, help='passed to tf.train.list_variables')
parser.add_argument('--save_dir', default=None, type=str, help='Path to the output PyTorch model.')
lowerCAmelCase_ : Optional[Any] = parser.parse_args()
lowerCAmelCase_ : Optional[Any] = {}
convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
| 692 |
'''simple docstring'''
import os
import unittest
from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , unittest.TestCase ):
"""simple docstring"""
__a =PhobertTokenizer
__a =False
def UpperCamelCase__ ( self : int ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_a = ["T@@", "i", "I", "R@@", "r", "e@@"]
_a = dict(zip(__a , range(len(__a ) ) ) )
_a = ["#version: 0.2", "l à</w>"]
_a = {"unk_token": "<unk>"}
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
for token in vocab_tokens:
fp.write(f'{token} {vocab_tokens[token]}\n' )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(__a ) )
def UpperCamelCase__ ( self : str , **__a : List[str] ):
kwargs.update(self.special_tokens_map )
return PhobertTokenizer.from_pretrained(self.tmpdirname , **__a )
def UpperCamelCase__ ( self : Optional[Any] , __a : Optional[int] ):
_a = "Tôi là VinAI Research"
_a = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>"
return input_text, output_text
def UpperCamelCase__ ( self : Dict ):
_a = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
_a = "Tôi là VinAI Research"
_a = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split()
_a = tokenizer.tokenize(__a )
print(__a )
self.assertListEqual(__a , __a )
_a = tokens + [tokenizer.unk_token]
_a = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3]
self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , __a )
| 692 | 1 |
from itertools import count
def snake_case_ ( snake_case = 50 ) -> int:
lowercase__: List[Any] = [1] * min_block_length
for n in count(snake_case ):
fill_count_functions.append(1 )
for block_length in range(snake_case , n + 1 ):
for block_start in range(n - block_length ):
fill_count_functions[n] += fill_count_functions[
n - block_start - block_length - 1
]
fill_count_functions[n] += 1
if fill_count_functions[n] > 1_00_00_00:
break
return n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 335 |
import os
import re
import shutil
from argparse import ArgumentParser, Namespace
from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger
__lowerCAmelCase = '''<<<<<<< This should probably be modified because it mentions: '''
__lowerCAmelCase = '''=======
>>>>>>>
'''
__lowerCAmelCase = [
'''TextEncoderConfig''',
'''ByteTextEncoder''',
'''SubwordTextEncoder''',
'''encoder_config''',
'''maybe_build_from_corpus''',
'''manual_dir''',
]
__lowerCAmelCase = [
# (pattern, replacement)
# Order is important here for some replacements
(r'''tfds\.core''', r'''datasets'''),
(r'''tf\.io\.gfile\.GFile''', r'''open'''),
(r'''tf\.([\w\d]+)''', r'''datasets.Value(\'\1\')'''),
(r'''tfds\.features\.Text\(\)''', r'''datasets.Value(\'string\')'''),
(r'''tfds\.features\.Text\(''', r'''datasets.Value(\'string\'),'''),
(r'''features\s*=\s*tfds.features.FeaturesDict\(''', r'''features=datasets.Features('''),
(r'''tfds\.features\.FeaturesDict\(''', r'''dict('''),
(r'''The TensorFlow Datasets Authors''', r'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''),
(r'''tfds\.''', r'''datasets.'''),
(r'''dl_manager\.manual_dir''', r'''self.config.data_dir'''),
(r'''self\.builder_config''', r'''self.config'''),
]
def snake_case_ ( snake_case ) -> Union[str, Any]:
return ConvertCommand(args.tfds_path , args.datasets_directory )
class __a ( __UpperCamelCase ):
@staticmethod
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase__ ) -> Optional[int]:
'''simple docstring'''
lowercase__: List[str] = parser.add_parser(
'convert' , help='Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.' , )
train_parser.add_argument(
'--tfds_path' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.' , )
train_parser.add_argument(
'--datasets_directory' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='Path to the HuggingFace Datasets folder.' )
train_parser.set_defaults(func=lowerCAmelCase__ )
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , *lowerCAmelCase__ ) -> Any:
'''simple docstring'''
lowercase__: Tuple = get_logger('datasets-cli/converting' )
lowercase__: Any = tfds_path
lowercase__: str = datasets_directory
def SCREAMING_SNAKE_CASE__ ( self ) -> Union[str, Any]:
'''simple docstring'''
if os.path.isdir(self._tfds_path ):
lowercase__: int = os.path.abspath(self._tfds_path )
elif os.path.isfile(self._tfds_path ):
lowercase__: Optional[int] = os.path.dirname(self._tfds_path )
else:
raise ValueError('--tfds_path is neither a directory nor a file. Please check path.' )
lowercase__: str = os.path.abspath(self._datasets_directory )
self._logger.info(F'Converting datasets from {abs_tfds_path} to {abs_datasets_path}' )
lowercase__: Union[str, Any] = []
lowercase__: List[str] = []
lowercase__: str = {}
if os.path.isdir(self._tfds_path ):
lowercase__: List[Any] = os.listdir(lowerCAmelCase__ )
else:
lowercase__: Optional[Any] = [os.path.basename(self._tfds_path )]
for f_name in file_names:
self._logger.info(F'Looking at file {f_name}' )
lowercase__: List[str] = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
lowercase__: int = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
if not os.path.isfile(lowerCAmelCase__ ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
self._logger.info('Skipping file' )
continue
with open(lowerCAmelCase__ , encoding='utf-8' ) as f:
lowercase__: Any = f.readlines()
lowercase__: List[str] = []
lowercase__: List[Any] = False
lowercase__: Any = False
lowercase__: Dict = []
for line in lines:
lowercase__: Tuple = line
# Convert imports
if "import tensorflow.compat.v2 as tf" in out_line:
continue
elif "@tfds.core" in out_line:
continue
elif "builder=self" in out_line:
continue
elif "import tensorflow_datasets.public_api as tfds" in out_line:
lowercase__: List[Any] = 'import datasets\n'
elif "import tensorflow" in out_line:
# order is important here
lowercase__: Optional[Any] = ''
continue
elif "from absl import logging" in out_line:
lowercase__: str = 'from datasets import logging\n'
elif "getLogger" in out_line:
lowercase__: Dict = out_line.replace('getLogger' , 'get_logger' )
elif any(expression in out_line for expression in TO_HIGHLIGHT ):
lowercase__: Tuple = True
lowercase__: int = list(filter(lambda lowerCAmelCase__ : e in out_line , lowerCAmelCase__ ) )
out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowerCAmelCase__ ) + '\n' )
out_lines.append(lowerCAmelCase__ )
out_lines.append(lowerCAmelCase__ )
continue
else:
for pattern, replacement in TO_CONVERT:
lowercase__: Any = re.sub(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
# Take care of saving utilities (to later move them together with main script)
if "tensorflow_datasets" in out_line:
lowercase__: Tuple = re.match(R'from\stensorflow_datasets.*import\s([^\.\r\n]+)' , lowerCAmelCase__ )
tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(',' ) )
lowercase__: Dict = 'from . import ' + match.group(1 )
# Check we have not forget anything
if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
raise ValueError(F'Error converting {out_line.strip()}' )
if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
lowercase__: List[str] = True
out_lines.append(lowerCAmelCase__ )
if is_builder or "wmt" in f_name:
# We create a new directory for each dataset
lowercase__: Dict = f_name.replace('.py' , '' )
lowercase__: Optional[Any] = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
lowercase__: Any = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ )
os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ )
self._logger.info(F'Adding directory {output_dir}' )
imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} )
else:
# Utilities will be moved at the end
utils_files.append(lowerCAmelCase__ )
if needs_manual_update:
with_manual_update.append(lowerCAmelCase__ )
with open(lowerCAmelCase__ , 'w' , encoding='utf-8' ) as f:
f.writelines(lowerCAmelCase__ )
self._logger.info(F'Converted in {output_file}' )
for utils_file in utils_files:
try:
lowercase__: str = os.path.basename(lowerCAmelCase__ )
lowercase__: int = imports_to_builder_map[f_name.replace('.py' , '' )]
self._logger.info(F'Moving {dest_folder} to {utils_file}' )
shutil.copy(lowerCAmelCase__ , lowerCAmelCase__ )
except KeyError:
self._logger.error(F'Cannot find destination folder for {utils_file}. Please copy manually.' )
if with_manual_update:
for file_path in with_manual_update:
self._logger.warning(
F'You need to manually update file {file_path} to remove configurations using \'TextEncoderConfig\'.' )
| 335 | 1 |
def SCREAMING_SNAKE_CASE ( snake_case_ : str ):
snake_case__ : Optional[Any] = [0 for i in range(len(_lowerCAmelCase ) )]
# initialize interval's left pointer and right pointer
snake_case__ : Union[str, Any] = 0, 0
for i in range(1 , len(_lowerCAmelCase ) ):
# case when current index is inside the interval
if i <= right_pointer:
snake_case__ : Tuple = min(right_pointer - i + 1 , z_result[i - left_pointer] )
snake_case__ : List[Any] = min_edge
while go_next(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
snake_case__ : str = i, i + z_result[i] - 1
return z_result
def SCREAMING_SNAKE_CASE ( snake_case_ : int , snake_case_ : list[int] , snake_case_ : str ):
return i + z_result[i] < len(_lowerCAmelCase ) and s[z_result[i]] == s[i + z_result[i]]
def SCREAMING_SNAKE_CASE ( snake_case_ : str , snake_case_ : str ):
snake_case__ : Any = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
snake_case__ : Any = z_function(pattern + input_str )
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(_lowerCAmelCase ):
answer += 1
return answer
if __name__ == "__main__":
import doctest
doctest.testmod()
| 297 |
'''simple docstring'''
import unittest
from diffusers.pipelines.pipeline_utils import is_safetensors_compatible
class SCREAMING_SNAKE_CASE( unittest.TestCase ):
"""simple docstring"""
def A ( self : Tuple ) -> Optional[Any]:
UpperCAmelCase : Any = [
'''safety_checker/pytorch_model.bin''',
'''safety_checker/model.safetensors''',
'''vae/diffusion_pytorch_model.bin''',
'''vae/diffusion_pytorch_model.safetensors''',
'''text_encoder/pytorch_model.bin''',
'''text_encoder/model.safetensors''',
'''unet/diffusion_pytorch_model.bin''',
'''unet/diffusion_pytorch_model.safetensors''',
]
self.assertTrue(is_safetensors_compatible(__snake_case ) )
def A ( self : Tuple ) -> Tuple:
UpperCAmelCase : Optional[Any] = [
'''unet/diffusion_pytorch_model.bin''',
'''unet/diffusion_pytorch_model.safetensors''',
]
self.assertTrue(is_safetensors_compatible(__snake_case ) )
def A ( self : str ) -> str:
UpperCAmelCase : int = [
'''safety_checker/pytorch_model.bin''',
'''safety_checker/model.safetensors''',
'''vae/diffusion_pytorch_model.bin''',
'''vae/diffusion_pytorch_model.safetensors''',
'''text_encoder/pytorch_model.bin''',
'''text_encoder/model.safetensors''',
'''unet/diffusion_pytorch_model.bin''',
# Removed: 'unet/diffusion_pytorch_model.safetensors',
]
self.assertFalse(is_safetensors_compatible(__snake_case ) )
def A ( self : str ) -> Tuple:
UpperCAmelCase : Optional[Any] = [
'''text_encoder/pytorch_model.bin''',
'''text_encoder/model.safetensors''',
]
self.assertTrue(is_safetensors_compatible(__snake_case ) )
def A ( self : Tuple ) -> Optional[int]:
UpperCAmelCase : List[str] = [
'''safety_checker/pytorch_model.bin''',
'''safety_checker/model.safetensors''',
'''vae/diffusion_pytorch_model.bin''',
'''vae/diffusion_pytorch_model.safetensors''',
'''text_encoder/pytorch_model.bin''',
# Removed: 'text_encoder/model.safetensors',
'''unet/diffusion_pytorch_model.bin''',
'''unet/diffusion_pytorch_model.safetensors''',
]
self.assertFalse(is_safetensors_compatible(__snake_case ) )
def A ( self : int ) -> List[Any]:
UpperCAmelCase : Union[str, Any] = [
'''safety_checker/pytorch_model.fp16.bin''',
'''safety_checker/model.fp16.safetensors''',
'''vae/diffusion_pytorch_model.fp16.bin''',
'''vae/diffusion_pytorch_model.fp16.safetensors''',
'''text_encoder/pytorch_model.fp16.bin''',
'''text_encoder/model.fp16.safetensors''',
'''unet/diffusion_pytorch_model.fp16.bin''',
'''unet/diffusion_pytorch_model.fp16.safetensors''',
]
UpperCAmelCase : List[Any] = '''fp16'''
self.assertTrue(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
def A ( self : Union[str, Any] ) -> str:
UpperCAmelCase : Optional[int] = [
'''unet/diffusion_pytorch_model.fp16.bin''',
'''unet/diffusion_pytorch_model.fp16.safetensors''',
]
UpperCAmelCase : int = '''fp16'''
self.assertTrue(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
def A ( self : Dict ) -> Tuple:
# pass variant but use the non-variant filenames
UpperCAmelCase : str = [
'''unet/diffusion_pytorch_model.bin''',
'''unet/diffusion_pytorch_model.safetensors''',
]
UpperCAmelCase : int = '''fp16'''
self.assertTrue(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
def A ( self : Optional[int] ) -> List[str]:
UpperCAmelCase : str = [
'''safety_checker/pytorch_model.fp16.bin''',
'''safety_checker/model.fp16.safetensors''',
'''vae/diffusion_pytorch_model.fp16.bin''',
'''vae/diffusion_pytorch_model.fp16.safetensors''',
'''text_encoder/pytorch_model.fp16.bin''',
'''text_encoder/model.fp16.safetensors''',
'''unet/diffusion_pytorch_model.fp16.bin''',
# Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
]
UpperCAmelCase : Optional[int] = '''fp16'''
self.assertFalse(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
def A ( self : str ) -> Union[str, Any]:
UpperCAmelCase : List[str] = [
'''text_encoder/pytorch_model.fp16.bin''',
'''text_encoder/model.fp16.safetensors''',
]
UpperCAmelCase : List[str] = '''fp16'''
self.assertTrue(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
def A ( self : Optional[int] ) -> List[str]:
# pass variant but use the non-variant filenames
UpperCAmelCase : Optional[int] = [
'''text_encoder/pytorch_model.bin''',
'''text_encoder/model.safetensors''',
]
UpperCAmelCase : List[Any] = '''fp16'''
self.assertTrue(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
def A ( self : int ) -> Union[str, Any]:
UpperCAmelCase : Any = [
'''safety_checker/pytorch_model.fp16.bin''',
'''safety_checker/model.fp16.safetensors''',
'''vae/diffusion_pytorch_model.fp16.bin''',
'''vae/diffusion_pytorch_model.fp16.safetensors''',
'''text_encoder/pytorch_model.fp16.bin''',
# 'text_encoder/model.fp16.safetensors',
'''unet/diffusion_pytorch_model.fp16.bin''',
'''unet/diffusion_pytorch_model.fp16.safetensors''',
]
UpperCAmelCase : Dict = '''fp16'''
self.assertFalse(is_safetensors_compatible(__snake_case , variant=__snake_case ) )
| 127 | 0 |
import argparse
import json
import math
import os
import time
import traceback
import zipfile
from collections import Counter
import requests
def __a ( __lowerCAmelCase , __lowerCAmelCase=None ) -> Tuple:
SCREAMING_SNAKE_CASE : Dict = None
if token is not None:
SCREAMING_SNAKE_CASE : Union[str, Any] = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''}
SCREAMING_SNAKE_CASE : str = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100'''
SCREAMING_SNAKE_CASE : List[str] = requests.get(__lowerCAmelCase , headers=__lowerCAmelCase ).json()
SCREAMING_SNAKE_CASE : str = {}
try:
job_links.update({job['name']: job['html_url'] for job in result['jobs']} )
SCREAMING_SNAKE_CASE : str = math.ceil((result['total_count'] - 100) / 100 )
for i in range(__lowerCAmelCase ):
SCREAMING_SNAKE_CASE : Tuple = requests.get(url + F'''&page={i + 2}''' , headers=__lowerCAmelCase ).json()
job_links.update({job['name']: job['html_url'] for job in result['jobs']} )
return job_links
except Exception:
print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' )
return {}
def __a ( __lowerCAmelCase , __lowerCAmelCase=None ) -> Optional[int]:
SCREAMING_SNAKE_CASE : str = None
if token is not None:
SCREAMING_SNAKE_CASE : str = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''}
SCREAMING_SNAKE_CASE : Union[str, Any] = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100'''
SCREAMING_SNAKE_CASE : Dict = requests.get(__lowerCAmelCase , headers=__lowerCAmelCase ).json()
SCREAMING_SNAKE_CASE : str = {}
try:
artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']} )
SCREAMING_SNAKE_CASE : Any = math.ceil((result['total_count'] - 100) / 100 )
for i in range(__lowerCAmelCase ):
SCREAMING_SNAKE_CASE : Optional[int] = requests.get(url + F'''&page={i + 2}''' , headers=__lowerCAmelCase ).json()
artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']} )
return artifacts
except Exception:
print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' )
return {}
def __a ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str:
SCREAMING_SNAKE_CASE : int = None
if token is not None:
SCREAMING_SNAKE_CASE : Optional[int] = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''}
SCREAMING_SNAKE_CASE : List[str] = requests.get(__lowerCAmelCase , headers=__lowerCAmelCase , allow_redirects=__lowerCAmelCase )
SCREAMING_SNAKE_CASE : List[Any] = result.headers['Location']
SCREAMING_SNAKE_CASE : List[str] = requests.get(__lowerCAmelCase , allow_redirects=__lowerCAmelCase )
SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(__lowerCAmelCase , F'''{artifact_name}.zip''' )
with open(__lowerCAmelCase , 'wb' ) as fp:
fp.write(response.content )
def __a ( __lowerCAmelCase , __lowerCAmelCase=None ) -> str:
SCREAMING_SNAKE_CASE : Any = []
SCREAMING_SNAKE_CASE : int = []
SCREAMING_SNAKE_CASE : Tuple = None
with zipfile.ZipFile(__lowerCAmelCase ) as z:
for filename in z.namelist():
if not os.path.isdir(__lowerCAmelCase ):
# read the file
if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]:
with z.open(__lowerCAmelCase ) as f:
for line in f:
SCREAMING_SNAKE_CASE : Dict = line.decode('UTF-8' ).strip()
if filename == "failures_line.txt":
try:
# `error_line` is the place where `error` occurs
SCREAMING_SNAKE_CASE : List[str] = line[: line.index(': ' )]
SCREAMING_SNAKE_CASE : Tuple = line[line.index(': ' ) + len(': ' ) :]
errors.append([error_line, error] )
except Exception:
# skip un-related lines
pass
elif filename == "summary_short.txt" and line.startswith('FAILED ' ):
# `test` is the test method that failed
SCREAMING_SNAKE_CASE : Tuple = line[len('FAILED ' ) :]
failed_tests.append(__lowerCAmelCase )
elif filename == "job_name.txt":
SCREAMING_SNAKE_CASE : Optional[Any] = line
if len(__lowerCAmelCase ) != len(__lowerCAmelCase ):
raise ValueError(
F'''`errors` and `failed_tests` should have the same number of elements. Got {len(__lowerCAmelCase )} for `errors` '''
F'''and {len(__lowerCAmelCase )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some'''
' problem.' )
SCREAMING_SNAKE_CASE : Any = None
if job_name and job_links:
SCREAMING_SNAKE_CASE : str = job_links.get(__lowerCAmelCase , __lowerCAmelCase )
# A list with elements of the form (line of error, error, failed test)
SCREAMING_SNAKE_CASE : List[str] = [x + [y] + [job_link] for x, y in zip(__lowerCAmelCase , __lowerCAmelCase )]
return result
def __a ( __lowerCAmelCase , __lowerCAmelCase=None ) -> Any:
SCREAMING_SNAKE_CASE : Optional[Any] = []
SCREAMING_SNAKE_CASE : List[str] = [os.path.join(__lowerCAmelCase , __lowerCAmelCase ) for p in os.listdir(__lowerCAmelCase ) if p.endswith('.zip' )]
for p in paths:
errors.extend(get_errors_from_single_artifact(__lowerCAmelCase , job_links=__lowerCAmelCase ) )
return errors
def __a ( __lowerCAmelCase , __lowerCAmelCase=None ) -> Optional[int]:
SCREAMING_SNAKE_CASE : Union[str, Any] = Counter()
counter.update([x[1] for x in logs] )
SCREAMING_SNAKE_CASE : Optional[Any] = counter.most_common()
SCREAMING_SNAKE_CASE : Any = {}
for error, count in counts:
if error_filter is None or error not in error_filter:
SCREAMING_SNAKE_CASE : Union[str, Any] = {'count': count, 'failed_tests': [(x[2], x[0]) for x in logs if x[1] == error]}
SCREAMING_SNAKE_CASE : Optional[Any] = dict(sorted(r.items() , key=lambda __lowerCAmelCase : item[1]["count"] , reverse=__lowerCAmelCase ) )
return r
def __a ( __lowerCAmelCase ) -> Optional[Any]:
SCREAMING_SNAKE_CASE : str = test.split('::' )[0]
if test.startswith('tests/models/' ):
SCREAMING_SNAKE_CASE : int = test.split('/' )[2]
else:
SCREAMING_SNAKE_CASE : Optional[int] = None
return test
def __a ( __lowerCAmelCase , __lowerCAmelCase=None ) -> Dict:
SCREAMING_SNAKE_CASE : int = [(x[0], x[1], get_model(x[2] )) for x in logs]
SCREAMING_SNAKE_CASE : List[str] = [x for x in logs if x[2] is not None]
SCREAMING_SNAKE_CASE : str = {x[2] for x in logs}
SCREAMING_SNAKE_CASE : Optional[int] = {}
for test in tests:
SCREAMING_SNAKE_CASE : str = Counter()
# count by errors in `test`
counter.update([x[1] for x in logs if x[2] == test] )
SCREAMING_SNAKE_CASE : Dict = counter.most_common()
SCREAMING_SNAKE_CASE : int = {error: count for error, count in counts if (error_filter is None or error not in error_filter)}
SCREAMING_SNAKE_CASE : List[str] = sum(error_counts.values() )
if n_errors > 0:
SCREAMING_SNAKE_CASE : Any = {'count': n_errors, 'errors': error_counts}
SCREAMING_SNAKE_CASE : List[Any] = dict(sorted(r.items() , key=lambda __lowerCAmelCase : item[1]["count"] , reverse=__lowerCAmelCase ) )
return r
def __a ( __lowerCAmelCase ) -> List[str]:
SCREAMING_SNAKE_CASE : Tuple = '| no. | error | status |'
SCREAMING_SNAKE_CASE : List[str] = '|-:|:-|:-|'
SCREAMING_SNAKE_CASE : Union[str, Any] = [header, sep]
for error in reduced_by_error:
SCREAMING_SNAKE_CASE : Dict = reduced_by_error[error]['count']
SCREAMING_SNAKE_CASE : List[Any] = F'''| {count} | {error[:100]} | |'''
lines.append(__lowerCAmelCase )
return "\n".join(__lowerCAmelCase )
def __a ( __lowerCAmelCase ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE : Tuple = '| model | no. of errors | major error | count |'
SCREAMING_SNAKE_CASE : List[str] = '|-:|-:|-:|-:|'
SCREAMING_SNAKE_CASE : int = [header, sep]
for model in reduced_by_model:
SCREAMING_SNAKE_CASE : str = reduced_by_model[model]['count']
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = list(reduced_by_model[model]['errors'].items() )[0]
SCREAMING_SNAKE_CASE : List[str] = F'''| {model} | {count} | {error[:60]} | {_count} |'''
lines.append(__lowerCAmelCase )
return "\n".join(__lowerCAmelCase )
if __name__ == "__main__":
_lowerCamelCase : List[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""")
parser.add_argument(
"""--output_dir""",
type=str,
required=True,
help="""Where to store the downloaded artifacts and other result files.""",
)
parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""")
_lowerCamelCase : str = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
_lowerCamelCase : Dict = get_job_links(args.workflow_run_id, token=args.token)
_lowerCamelCase : str = {}
# To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee.
# For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`.
if _job_links:
for k, v in _job_links.items():
# This is how GitHub actions combine job names.
if " / " in k:
_lowerCamelCase : List[str] = k.find(""" / """)
_lowerCamelCase : Union[str, Any] = k[index + len(""" / """) :]
_lowerCamelCase : Tuple = v
with open(os.path.join(args.output_dir, """job_links.json"""), """w""", encoding="""UTF-8""") as fp:
json.dump(job_links, fp, ensure_ascii=False, indent=4)
_lowerCamelCase : Any = get_artifacts_links(args.workflow_run_id, token=args.token)
with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp:
json.dump(artifacts, fp, ensure_ascii=False, indent=4)
for idx, (name, url) in enumerate(artifacts.items()):
download_artifact(name, url, args.output_dir, args.token)
# Be gentle to GitHub
time.sleep(1)
_lowerCamelCase : List[Any] = get_all_errors(args.output_dir, job_links=job_links)
# `e[1]` is the error
_lowerCamelCase : List[Any] = Counter()
counter.update([e[1] for e in errors])
# print the top 30 most common test errors
_lowerCamelCase : Any = counter.most_common(30)
for item in most_common:
print(item)
with open(os.path.join(args.output_dir, """errors.json"""), """w""", encoding="""UTF-8""") as fp:
json.dump(errors, fp, ensure_ascii=False, indent=4)
_lowerCamelCase : str = reduce_by_error(errors)
_lowerCamelCase : Tuple = reduce_by_model(errors)
_lowerCamelCase : Optional[Any] = make_github_table(reduced_by_error)
_lowerCamelCase : Optional[Any] = make_github_table_per_model(reduced_by_model)
with open(os.path.join(args.output_dir, """reduced_by_error.txt"""), """w""", encoding="""UTF-8""") as fp:
fp.write(sa)
with open(os.path.join(args.output_dir, """reduced_by_model.txt"""), """w""", encoding="""UTF-8""") as fp:
fp.write(sa) | 308 |
import baseaa
import io
import json
import os
from copy import deepcopy
from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler
class lowercase :
'''simple docstring'''
def __init__( self : Tuple , snake_case : Union[str, Any] ):
'''simple docstring'''
if isinstance(snake_case , snake_case ):
# Don't modify user's data should they want to reuse it (e.g. in tests), because once we
# modified it, it will not be accepted here again, since `auto` values would have been overridden
SCREAMING_SNAKE_CASE : int = deepcopy(snake_case )
elif os.path.exists(snake_case ):
with io.open(snake_case , 'r' , encoding='utf-8' ) as f:
SCREAMING_SNAKE_CASE : List[str] = json.load(snake_case )
else:
try:
SCREAMING_SNAKE_CASE : Union[str, Any] = baseaa.urlsafe_baadecode(snake_case ).decode('utf-8' )
SCREAMING_SNAKE_CASE : Any = json.loads(snake_case )
except (UnicodeDecodeError, AttributeError, ValueError):
raise ValueError(
f'''Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}''' )
SCREAMING_SNAKE_CASE : Tuple = config
self.set_stage_and_offload()
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Tuple = self.get_value('zero_optimization.stage' , -1 )
# offload
SCREAMING_SNAKE_CASE : int = False
if self.is_zeroa() or self.is_zeroa():
SCREAMING_SNAKE_CASE : Union[str, Any] = set(['cpu', 'nvme'] )
SCREAMING_SNAKE_CASE : Tuple = set(
[
self.get_value('zero_optimization.offload_optimizer.device' ),
self.get_value('zero_optimization.offload_param.device' ),
] )
if len(offload_devices & offload_devices_valid ) > 0:
SCREAMING_SNAKE_CASE : List[Any] = True
def lowerCamelCase_ ( self : List[str] , snake_case : Any ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = self.config
# find the config node of interest if it exists
SCREAMING_SNAKE_CASE : List[str] = ds_key_long.split('.' )
SCREAMING_SNAKE_CASE : Union[str, Any] = nodes.pop()
for node in nodes:
SCREAMING_SNAKE_CASE : List[str] = config.get(snake_case )
if config is None:
return None, ds_key
return config, ds_key
def lowerCamelCase_ ( self : Dict , snake_case : Any , snake_case : Any=None ):
'''simple docstring'''
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.find_config_node(snake_case )
if config is None:
return default
return config.get(snake_case , snake_case )
def lowerCamelCase_ ( self : Union[str, Any] , snake_case : Union[str, Any] , snake_case : Tuple=False ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[str] = self.config
# find the config node of interest if it exists
SCREAMING_SNAKE_CASE : str = ds_key_long.split('.' )
for node in nodes:
SCREAMING_SNAKE_CASE : List[Any] = config
SCREAMING_SNAKE_CASE : List[Any] = config.get(snake_case )
if config is None:
if must_exist:
raise ValueError(f'''Can\'t find {ds_key_long} entry in the config: {self.config}''' )
else:
return
# if found remove it
if parent_config is not None:
parent_config.pop(snake_case )
def lowerCamelCase_ ( self : Optional[int] , snake_case : str ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[str] = self.get_value(snake_case )
return False if value is None else bool(snake_case )
def lowerCamelCase_ ( self : Dict , snake_case : Optional[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_value(snake_case )
return False if value is None else not bool(snake_case )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
return self._stage == 2
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
return self._stage == 3
def lowerCamelCase_ ( self : str ):
'''simple docstring'''
return self._offload
class lowercase :
'''simple docstring'''
def __init__( self : Optional[int] , snake_case : Dict ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = engine
def lowerCamelCase_ ( self : str , snake_case : Optional[int] , **snake_case : Any ):
'''simple docstring'''
self.engine.backward(snake_case , **snake_case )
# Deepspeed's `engine.step` performs the following operations:
# - gradient accumulation check
# - gradient clipping
# - optimizer step
# - zero grad
# - checking overflow
# - lr_scheduler step (only if engine.lr_scheduler is not None)
self.engine.step()
# and this plugin overrides the above calls with no-ops when Accelerate runs under
# Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
# training loop that works transparently under many training regimes.
class lowercase ( SCREAMING_SNAKE_CASE_):
'''simple docstring'''
def __init__( self : Any , snake_case : int ):
'''simple docstring'''
super().__init__(snake_case , device_placement=snake_case , scaler=snake_case )
SCREAMING_SNAKE_CASE : Dict = hasattr(self.optimizer , 'overflow' )
def lowerCamelCase_ ( self : Optional[int] , snake_case : Optional[Any]=None ):
'''simple docstring'''
pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
@property
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
if self.__has_overflow__:
return self.optimizer.overflow
return False
class lowercase ( SCREAMING_SNAKE_CASE_):
'''simple docstring'''
def __init__( self : Optional[Any] , snake_case : int , snake_case : Any ):
'''simple docstring'''
super().__init__(snake_case , snake_case )
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed
class lowercase :
'''simple docstring'''
def __init__( self : Tuple , snake_case : Optional[Any] , snake_case : Any=0.001 , snake_case : Tuple=0 , **snake_case : List[Any] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Union[str, Any] = params
SCREAMING_SNAKE_CASE : Optional[int] = lr
SCREAMING_SNAKE_CASE : Tuple = weight_decay
SCREAMING_SNAKE_CASE : int = kwargs
class lowercase :
'''simple docstring'''
def __init__( self : Optional[Any] , snake_case : int , snake_case : Optional[int]=None , snake_case : Any=0 , **snake_case : List[str] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : List[str] = optimizer
SCREAMING_SNAKE_CASE : List[Any] = total_num_steps
SCREAMING_SNAKE_CASE : Optional[Any] = warmup_num_steps
SCREAMING_SNAKE_CASE : int = kwargs | 308 | 1 |
'''simple docstring'''
import importlib
import os
import sys
# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append('''.''')
def _UpperCamelCase (_lowerCamelCase : Union[str, Any] )-> Dict:
'''simple docstring'''
__snake_case = test_file.split(os.path.sep )
if components[0:2] != ["tests", "models"]:
raise ValueError(
'''`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '''
f'''{test_file} instead.''' )
__snake_case = components[-1]
if not test_fn.endswith('''py''' ):
raise ValueError(f'''`test_file` should be a python file. Got {test_fn} instead.''' )
if not test_fn.startswith('''test_modeling_''' ):
raise ValueError(
f'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' )
__snake_case = components[:-1] + [test_fn.replace('''.py''' , '''''' )]
__snake_case = '''.'''.join(_lowerCamelCase )
return test_module_path
def _UpperCamelCase (_lowerCamelCase : Union[str, Any] )-> Dict:
'''simple docstring'''
__snake_case = get_module_path(_lowerCamelCase )
__snake_case = importlib.import_module(_lowerCamelCase )
return test_module
def _UpperCamelCase (_lowerCamelCase : int )-> List[str]:
'''simple docstring'''
__snake_case = []
__snake_case = get_test_module(_lowerCamelCase )
for attr in dir(_lowerCamelCase ):
if attr.endswith('''ModelTester''' ):
tester_classes.append(getattr(_lowerCamelCase , _lowerCamelCase ) )
# sort with class names
return sorted(_lowerCamelCase , key=lambda _lowerCamelCase : x.__name__ )
def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> List[Any]:
'''simple docstring'''
__snake_case = []
__snake_case = get_test_module(_lowerCamelCase )
for attr in dir(_lowerCamelCase ):
__snake_case = getattr(_lowerCamelCase , _lowerCamelCase )
# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
# `all_model_classes` is not empty (which also excludes other special classes).
__snake_case = getattr(_lowerCamelCase , '''all_model_classes''' , [] )
if len(_lowerCamelCase ) > 0:
test_classes.append(_lowerCamelCase )
# sort with class names
return sorted(_lowerCamelCase , key=lambda _lowerCamelCase : x.__name__ )
def _UpperCamelCase (_lowerCamelCase : List[str] )-> str:
'''simple docstring'''
__snake_case = get_test_classes(_lowerCamelCase )
__snake_case = set()
for test_class in test_classes:
model_classes.update(test_class.all_model_classes )
# sort with class names
return sorted(_lowerCamelCase , key=lambda _lowerCamelCase : x.__name__ )
def _UpperCamelCase (_lowerCamelCase : Tuple )-> Any:
'''simple docstring'''
__snake_case = test_class()
if hasattr(_lowerCamelCase , '''setUp''' ):
test.setUp()
__snake_case = None
if hasattr(_lowerCamelCase , '''model_tester''' ):
# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
if test.model_tester is not None:
__snake_case = test.model_tester.__class__
return model_tester
def _UpperCamelCase (_lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[Any] )-> str:
'''simple docstring'''
__snake_case = get_test_classes(_lowerCamelCase )
__snake_case = []
for test_class in test_classes:
if model_class in test_class.all_model_classes:
target_test_classes.append(_lowerCamelCase )
# sort with class names
return sorted(_lowerCamelCase , key=lambda _lowerCamelCase : x.__name__ )
def _UpperCamelCase (_lowerCamelCase : List[Any] , _lowerCamelCase : int )-> Optional[int]:
'''simple docstring'''
__snake_case = get_test_classes_for_model(_lowerCamelCase , _lowerCamelCase )
__snake_case = []
for test_class in test_classes:
__snake_case = get_model_tester_from_test_class(_lowerCamelCase )
if tester_class is not None:
tester_classes.append(_lowerCamelCase )
# sort with class names
return sorted(_lowerCamelCase , key=lambda _lowerCamelCase : x.__name__ )
def _UpperCamelCase (_lowerCamelCase : Union[str, Any] )-> Union[str, Any]:
'''simple docstring'''
__snake_case = get_test_classes(_lowerCamelCase )
__snake_case = {test_class: get_model_tester_from_test_class(_lowerCamelCase ) for test_class in test_classes}
return test_tester_mapping
def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> Union[str, Any]:
'''simple docstring'''
__snake_case = get_model_classes(_lowerCamelCase )
__snake_case = {
model_class: get_test_classes_for_model(_lowerCamelCase , _lowerCamelCase ) for model_class in model_classes
}
return model_test_mapping
def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> Dict:
'''simple docstring'''
__snake_case = get_model_classes(_lowerCamelCase )
__snake_case = {
model_class: get_tester_classes_for_model(_lowerCamelCase , _lowerCamelCase ) for model_class in model_classes
}
return model_to_tester_mapping
def _UpperCamelCase (_lowerCamelCase : Optional[Any] )-> str:
'''simple docstring'''
if isinstance(_lowerCamelCase , _lowerCamelCase ):
return o
elif isinstance(_lowerCamelCase , _lowerCamelCase ):
return o.__name__
elif isinstance(_lowerCamelCase , (list, tuple) ):
return [to_json(_lowerCamelCase ) for x in o]
elif isinstance(_lowerCamelCase , _lowerCamelCase ):
return {to_json(_lowerCamelCase ): to_json(_lowerCamelCase ) for k, v in o.items()}
else:
return o
| 24 |
def __UpperCamelCase ( _lowerCAmelCase ):
"""simple docstring"""
if p < 2:
raise ValueError("p should not be less than 2!" )
elif p == 2:
return True
UpperCAmelCase = 4
UpperCAmelCase = (1 << p) - 1
for _ in range(p - 2 ):
UpperCAmelCase = ((s * s) - 2) % m
return s == 0
if __name__ == "__main__":
print(lucas_lehmer_test(7))
print(lucas_lehmer_test(11))
| 333 | 0 |
from typing import Callable, Dict, Optional, Tuple
import torch
from torch import nn
from torch.distributions import (
AffineTransform,
Distribution,
Independent,
NegativeBinomial,
Normal,
StudentT,
TransformedDistribution,
)
class A_ ( __lowerCamelCase ):
'''simple docstring'''
def __init__( self , snake_case , snake_case=None , snake_case=None , snake_case=0 ):
lowercase = 1.0 if scale is None else scale
lowercase = 0.0 if loc is None else loc
super().__init__(snake_case , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=snake_case )] )
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return self.base_dist.mean * self.scale + self.loc
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return self.base_dist.variance * self.scale**2
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return self.variance.sqrt()
class A_ ( nn.Module ):
'''simple docstring'''
def __init__( self , snake_case , snake_case , snake_case , **snake_case ):
super().__init__(**snake_case )
lowercase = args_dim
lowercase = nn.ModuleList([nn.Linear(snake_case , snake_case ) for dim in args_dim.values()] )
lowercase = domain_map
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase = [proj(snake_case ) for proj in self.proj]
return self.domain_map(*snake_case )
class A_ ( nn.Module ):
'''simple docstring'''
def __init__( self , snake_case ):
super().__init__()
lowercase = function
def SCREAMING_SNAKE_CASE__ ( self , snake_case , *snake_case ):
return self.function(snake_case , *snake_case )
class A_ :
'''simple docstring'''
_UpperCamelCase : type
_UpperCamelCase : int
_UpperCamelCase : Dict[str, int]
def __init__( self , snake_case = 1 ):
lowercase = dim
lowercase = {k: dim * self.args_dim[k] for k in self.args_dim}
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if self.dim == 1:
return self.distribution_class(*snake_case )
else:
return Independent(self.distribution_class(*snake_case ) , 1 )
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None , snake_case = None , ):
lowercase = self._base_distribution(snake_case )
if loc is None and scale is None:
return distr
else:
return AffineTransformed(snake_case , loc=snake_case , scale=snake_case , event_dim=self.event_dim )
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return () if self.dim == 1 else (self.dim,)
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return len(self.event_shape )
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return 0.0
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
return ParameterProjection(
in_features=snake_case , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map ) , )
def SCREAMING_SNAKE_CASE__ ( self , *snake_case ):
raise NotImplementedError()
@staticmethod
def SCREAMING_SNAKE_CASE__ ( snake_case ):
return (x + torch.sqrt(torch.square(snake_case ) + 4.0 )) / 2.0
class A_ ( __lowerCamelCase ):
'''simple docstring'''
_UpperCamelCase : Dict[str, int] = {"df": 1, "loc": 1, "scale": 1}
_UpperCamelCase : type = StudentT
@classmethod
def SCREAMING_SNAKE_CASE__ ( cls , snake_case , snake_case , snake_case ):
lowercase = cls.squareplus(snake_case ).clamp_min(torch.finfo(scale.dtype ).eps )
lowercase = 2.0 + cls.squareplus(snake_case )
return df.squeeze(-1 ), loc.squeeze(-1 ), scale.squeeze(-1 )
class A_ ( __lowerCamelCase ):
'''simple docstring'''
_UpperCamelCase : Dict[str, int] = {"loc": 1, "scale": 1}
_UpperCamelCase : type = Normal
@classmethod
def SCREAMING_SNAKE_CASE__ ( cls , snake_case , snake_case ):
lowercase = cls.squareplus(snake_case ).clamp_min(torch.finfo(scale.dtype ).eps )
return loc.squeeze(-1 ), scale.squeeze(-1 )
class A_ ( __lowerCamelCase ):
'''simple docstring'''
_UpperCamelCase : Dict[str, int] = {"total_count": 1, "logits": 1}
_UpperCamelCase : type = NegativeBinomial
@classmethod
def SCREAMING_SNAKE_CASE__ ( cls , snake_case , snake_case ):
lowercase = cls.squareplus(snake_case )
return total_count.squeeze(-1 ), logits.squeeze(-1 )
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase , lowercase = distr_args
if self.dim == 1:
return self.distribution_class(total_count=snake_case , logits=snake_case )
else:
return Independent(self.distribution_class(total_count=snake_case , logits=snake_case ) , 1 )
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case = None , snake_case = None ):
lowercase , lowercase = distr_args
if scale is not None:
# See scaling property of Gamma.
logits += scale.log()
return self._base_distribution((total_count, logits) )
| 565 |
from abc import ABC, abstractmethod
from typing import List, Optional
class A_ ( __lowerCamelCase ):
'''simple docstring'''
def __init__( self ):
# test for the above condition
self.test()
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = 0
lowercase = False
while not completed:
if counter == 1:
self.reset()
lowercase = self.advance()
if not self.does_advance(snake_case ):
raise Exception(
'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' )
lowercase , lowercase , lowercase = self.update(snake_case )
counter += 1
if counter > 1_0000:
raise Exception('update() does not fulfill the constraint.' )
if self.remaining() != 0:
raise Exception('Custom Constraint is not defined correctly.' )
@abstractmethod
def SCREAMING_SNAKE_CASE__ ( self ):
raise NotImplementedError(
F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
raise NotImplementedError(
F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
raise NotImplementedError(
F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def SCREAMING_SNAKE_CASE__ ( self ):
raise NotImplementedError(
F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def SCREAMING_SNAKE_CASE__ ( self ):
raise NotImplementedError(
F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def SCREAMING_SNAKE_CASE__ ( self , snake_case=False ):
raise NotImplementedError(
F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
class A_ ( __lowerCamelCase ):
'''simple docstring'''
def __init__( self , snake_case ):
super(snake_case , self ).__init__()
if not isinstance(snake_case , snake_case ) or len(snake_case ) == 0:
raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.''' )
if any((not isinstance(snake_case , snake_case ) or token_id < 0) for token_id in token_ids ):
raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' )
lowercase = token_ids
lowercase = len(self.token_ids )
lowercase = -1 # the index of the currently fulfilled step
lowercase = False
def SCREAMING_SNAKE_CASE__ ( self ):
if self.completed:
return None
return self.token_ids[self.fulfilled_idx + 1]
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if not isinstance(snake_case , snake_case ):
raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(snake_case )}''' )
if self.completed:
return False
return token_id == self.token_ids[self.fulfilled_idx + 1]
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if not isinstance(snake_case , snake_case ):
raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(snake_case )}''' )
lowercase = False
lowercase = False
lowercase = False
if self.does_advance(snake_case ):
self.fulfilled_idx += 1
lowercase = True
if self.fulfilled_idx == (self.seqlen - 1):
lowercase = True
lowercase = completed
else:
# failed to make progress.
lowercase = True
self.reset()
return stepped, completed, reset
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = False
lowercase = 0
def SCREAMING_SNAKE_CASE__ ( self ):
return self.seqlen - (self.fulfilled_idx + 1)
def SCREAMING_SNAKE_CASE__ ( self , snake_case=False ):
lowercase = PhrasalConstraint(self.token_ids )
if stateful:
lowercase = self.seqlen
lowercase = self.fulfilled_idx
lowercase = self.completed
return new_constraint
class A_ :
'''simple docstring'''
def __init__( self , snake_case , snake_case=True ):
lowercase = max([len(snake_case ) for one in nested_token_ids] )
lowercase = {}
for token_ids in nested_token_ids:
lowercase = root
for tidx, token_id in enumerate(snake_case ):
if token_id not in level:
lowercase = {}
lowercase = level[token_id]
if no_subsets and self.has_subsets(snake_case , snake_case ):
raise ValueError(
'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
F''' {nested_token_ids}.''' )
lowercase = root
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase = self.trie
for current_token in current_seq:
lowercase = start[current_token]
lowercase = list(start.keys() )
return next_tokens
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase = self.next_tokens(snake_case )
return len(snake_case ) == 0
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
lowercase = list(root.values() )
if len(snake_case ) == 0:
return 1
else:
return sum([self.count_leaves(snake_case ) for nn in next_nodes] )
def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case ):
lowercase = self.count_leaves(snake_case )
return len(snake_case ) != leaf_count
class A_ ( __lowerCamelCase ):
'''simple docstring'''
def __init__( self , snake_case ):
super(snake_case , self ).__init__()
if not isinstance(snake_case , snake_case ) or len(snake_case ) == 0:
raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' )
if any(not isinstance(snake_case , snake_case ) for token_ids in nested_token_ids ):
raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' )
if any(
any((not isinstance(snake_case , snake_case ) or token_id < 0) for token_id in token_ids )
for token_ids in nested_token_ids ):
raise ValueError(
F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' )
lowercase = DisjunctiveTrie(snake_case )
lowercase = nested_token_ids
lowercase = self.trie.max_height
lowercase = []
lowercase = False
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = self.trie.next_tokens(self.current_seq )
if len(snake_case ) == 0:
return None
else:
return token_list
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if not isinstance(snake_case , snake_case ):
raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case )}''' )
lowercase = self.trie.next_tokens(self.current_seq )
return token_id in next_tokens
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if not isinstance(snake_case , snake_case ):
raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case )}''' )
lowercase = False
lowercase = False
lowercase = False
if self.does_advance(snake_case ):
self.current_seq.append(snake_case )
lowercase = True
else:
lowercase = True
self.reset()
lowercase = self.trie.reached_leaf(self.current_seq )
lowercase = completed
return stepped, completed, reset
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = False
lowercase = []
def SCREAMING_SNAKE_CASE__ ( self ):
if self.completed:
# since this can be completed without reaching max height
return 0
else:
return self.seqlen - len(self.current_seq )
def SCREAMING_SNAKE_CASE__ ( self , snake_case=False ):
lowercase = DisjunctiveConstraint(self.token_ids )
if stateful:
lowercase = self.seqlen
lowercase = self.current_seq
lowercase = self.completed
return new_constraint
class A_ :
'''simple docstring'''
def __init__( self , snake_case ):
lowercase = constraints
# max # of steps required to fulfill a given constraint
lowercase = max([c.seqlen for c in constraints] )
lowercase = len(snake_case )
lowercase = False
self.init_state()
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = []
lowercase = None
lowercase = [constraint.copy(stateful=snake_case ) for constraint in self.constraints]
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = 0
if self.inprogress_constraint:
# extra points for having a constraint mid-fulfilled
add += self.max_seqlen - self.inprogress_constraint.remaining()
return (len(self.complete_constraints ) * self.max_seqlen) + add
def SCREAMING_SNAKE_CASE__ ( self ):
lowercase = []
if self.inprogress_constraint is None:
for constraint in self.pending_constraints: # "pending" == "unfulfilled yet"
lowercase = constraint.advance()
if isinstance(snake_case , snake_case ):
token_list.append(snake_case )
elif isinstance(snake_case , snake_case ):
token_list.extend(snake_case )
else:
lowercase = self.inprogress_constraint.advance()
if isinstance(snake_case , snake_case ):
token_list.append(snake_case )
elif isinstance(snake_case , snake_case ):
token_list.extend(snake_case )
if len(snake_case ) == 0:
return None
else:
return token_list
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
self.init_state()
if token_ids is not None:
for token in token_ids:
# completes or steps **one** constraint
lowercase , lowercase = self.add(snake_case )
# the entire list of constraints are fulfilled
if self.completed:
break
def SCREAMING_SNAKE_CASE__ ( self , snake_case ):
if not isinstance(snake_case , snake_case ):
raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.''' )
lowercase , lowercase = False, False
if self.completed:
lowercase = True
lowercase = False
return complete, stepped
if self.inprogress_constraint is not None:
# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
# job, simply update the state
lowercase , lowercase , lowercase = self.inprogress_constraint.update(snake_case )
if reset:
# 1. If the next token breaks the progress, then we must restart.
# e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".
# But that doesn't mean we self.init_state(), since we only reset the state for this particular
# constraint, not the full list of constraints.
self.pending_constraints.append(self.inprogress_constraint.copy(stateful=snake_case ) )
lowercase = None
if complete:
# 2. If the next token completes the constraint, move it to completed list, set
# inprogress to None. If there are no pending constraints either, then this full list of constraints
# is complete.
self.complete_constraints.append(self.inprogress_constraint )
lowercase = None
if len(self.pending_constraints ) == 0:
# we're done!
lowercase = True
else:
# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
# of constraints?
for cidx, pending_constraint in enumerate(self.pending_constraints ):
if pending_constraint.does_advance(snake_case ):
lowercase , lowercase , lowercase = pending_constraint.update(snake_case )
if not stepped:
raise Exception(
'`constraint.update(token_id)` is not yielding incremental progress, '
'even though `constraint.does_advance(token_id)` is true.' )
if complete:
self.complete_constraints.append(snake_case )
lowercase = None
if not complete and stepped:
lowercase = pending_constraint
if complete or stepped:
# If we made any progress at all, then it's at least not a "pending constraint".
lowercase = (
self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
)
if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None:
# If there's no longer any pending after this and no inprogress either, then we must be
# complete.
lowercase = True
break # prevent accidentally stepping through multiple constraints with just one token.
return complete, stepped
def SCREAMING_SNAKE_CASE__ ( self , snake_case=True ):
lowercase = ConstraintListState(self.constraints ) # we actually never though self.constraints objects
# throughout this process. So it's at initialization state.
if stateful:
lowercase = [
constraint.copy(stateful=snake_case ) for constraint in self.complete_constraints
]
if self.inprogress_constraint is not None:
lowercase = self.inprogress_constraint.copy(stateful=snake_case )
lowercase = [constraint.copy() for constraint in self.pending_constraints]
return new_state
| 565 | 1 |
import unittest
import numpy as np
from transformers import RoFormerConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
if is_flax_available():
import jax.numpy as jnp
from transformers.models.roformer.modeling_flax_roformer import (
FlaxRoFormerForMaskedLM,
FlaxRoFormerForMultipleChoice,
FlaxRoFormerForQuestionAnswering,
FlaxRoFormerForSequenceClassification,
FlaxRoFormerForTokenClassification,
FlaxRoFormerModel,
)
class __A ( unittest.TestCase ):
def __init__( self :str , __snake_case :str , __snake_case :Tuple=13 , __snake_case :List[str]=7 , __snake_case :List[str]=True , __snake_case :Dict=True , __snake_case :str=True , __snake_case :Optional[int]=True , __snake_case :Union[str, Any]=99 , __snake_case :List[str]=32 , __snake_case :Tuple=5 , __snake_case :Optional[int]=4 , __snake_case :Any=37 , __snake_case :Any="gelu" , __snake_case :Dict=0.1 , __snake_case :Union[str, Any]=0.1 , __snake_case :Optional[Any]=5_12 , __snake_case :int=16 , __snake_case :List[Any]=2 , __snake_case :str=0.02 , __snake_case :Dict=4 , ):
'''simple docstring'''
__magic_name__ : int =parent
__magic_name__ : Dict =batch_size
__magic_name__ : List[str] =seq_length
__magic_name__ : Optional[int] =is_training
__magic_name__ : Any =use_attention_mask
__magic_name__ : List[str] =use_token_type_ids
__magic_name__ : Any =use_labels
__magic_name__ : List[Any] =vocab_size
__magic_name__ : Optional[Any] =hidden_size
__magic_name__ : Tuple =num_hidden_layers
__magic_name__ : List[str] =num_attention_heads
__magic_name__ : int =intermediate_size
__magic_name__ : Optional[int] =hidden_act
__magic_name__ : str =hidden_dropout_prob
__magic_name__ : int =attention_probs_dropout_prob
__magic_name__ : str =max_position_embeddings
__magic_name__ : List[str] =type_vocab_size
__magic_name__ : Tuple =type_sequence_label_size
__magic_name__ : List[str] =initializer_range
__magic_name__ : Any =num_choices
def A__ ( self :Optional[Any] ):
'''simple docstring'''
__magic_name__ : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ : Optional[int] =None
if self.use_attention_mask:
__magic_name__ : str =random_attention_mask([self.batch_size, self.seq_length] )
__magic_name__ : Union[str, Any] =None
if self.use_token_type_ids:
__magic_name__ : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__magic_name__ : Any =RoFormerConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__snake_case , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def A__ ( self :Dict ):
'''simple docstring'''
__magic_name__ : Dict =self.prepare_config_and_inputs()
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Tuple =config_and_inputs
__magic_name__ : Union[str, Any] ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
return config, inputs_dict
@require_flax
class __A ( UpperCamelCase__ , unittest.TestCase ):
UpperCamelCase = True
UpperCamelCase = (
(
FlaxRoFormerModel,
FlaxRoFormerForMaskedLM,
FlaxRoFormerForSequenceClassification,
FlaxRoFormerForTokenClassification,
FlaxRoFormerForMultipleChoice,
FlaxRoFormerForQuestionAnswering,
)
if is_flax_available()
else ()
)
def A__ ( self :Union[str, Any] ):
'''simple docstring'''
__magic_name__ : Tuple =FlaxRoFormerModelTester(self )
@slow
def A__ ( self :List[str] ):
'''simple docstring'''
for model_class_name in self.all_model_classes:
__magic_name__ : Optional[Any] =model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" , from_pt=__snake_case )
__magic_name__ : List[str] =model(np.ones((1, 1) ) )
self.assertIsNotNone(__snake_case )
@require_flax
class __A ( unittest.TestCase ):
@slow
def A__ ( self :Tuple ):
'''simple docstring'''
__magic_name__ : Union[str, Any] =FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" )
__magic_name__ : Tuple =jnp.array([[0, 1, 2, 3, 4, 5]] )
__magic_name__ : str =model(__snake_case )[0]
__magic_name__ : int =5_00_00
__magic_name__ : Dict =(1, 6, vocab_size)
self.assertEqual(output.shape , __snake_case )
__magic_name__ : List[Any] =jnp.array(
[[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] )
self.assertTrue(jnp.allclose(output[:, :3, :3] , __snake_case , atol=1E-4 ) )
| 21 |
def _lowerCAmelCase ( __magic_name__ :list ):
if any(not isinstance(__magic_name__ , __magic_name__ ) or x < 0 for x in sequence ):
raise TypeError('''Sequence must be list of non-negative integers''' )
for _ in range(len(__magic_name__ ) ):
for i, (rod_upper, rod_lower) in enumerate(zip(__magic_name__ , sequence[1:] ) ):
if rod_upper > rod_lower:
sequence[i] -= rod_upper - rod_lower
sequence[i + 1] += rod_upper - rod_lower
return sequence
if __name__ == "__main__":
assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
| 121 | 0 |
"""simple docstring"""
import re
from pathlib import Path
from unittest import TestCase
import pytest
@pytest.mark.integration
class a__ ( A__ ):
def lowerCamelCase_ ( self :List[Any] , _lowerCamelCase :str ):
'''simple docstring'''
with open(_lowerCamelCase , encoding='utf-8' ) as input_file:
UpperCamelCase_ : List[Any] =re.compile(r'(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)' )
UpperCamelCase_ : Any =input_file.read()
UpperCamelCase_ : Dict =regexp.search(_lowerCamelCase )
return match
def lowerCamelCase_ ( self :int , _lowerCamelCase :str ):
'''simple docstring'''
with open(_lowerCamelCase , encoding='utf-8' ) as input_file:
UpperCamelCase_ : Any =re.compile(r'#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()' , re.DOTALL )
UpperCamelCase_ : Dict =input_file.read()
# use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
UpperCamelCase_ : Union[str, Any] =regexp.finditer(_lowerCamelCase )
UpperCamelCase_ : str =[match for match in matches if match is not None and match.group(1 ) is not None]
return matches[0] if matches else None
def lowerCamelCase_ ( self :Tuple ):
'''simple docstring'''
UpperCamelCase_ : Dict =Path('./datasets' )
UpperCamelCase_ : Optional[Any] =list(dataset_paths.absolute().glob('**/*.py' ) )
for dataset in dataset_files:
if self._no_encoding_on_file_open(str(_lowerCamelCase ) ):
raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' )
def lowerCamelCase_ ( self :Optional[Any] ):
'''simple docstring'''
UpperCamelCase_ : str =Path('./datasets' )
UpperCamelCase_ : Optional[int] =list(dataset_paths.absolute().glob('**/*.py' ) )
for dataset in dataset_files:
if self._no_print_statements(str(_lowerCamelCase ) ):
raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
| 395 |
"""simple docstring"""
from __future__ import annotations
import math
def A_ ( __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
__SCREAMING_SNAKE_CASE = [num for num in range(3, 100_001, 2) if not is_prime(num)]
def A_ ( __lowercase ):
if not isinstance(__lowercase , __lowercase ):
raise ValueError('n must be an integer' )
if n <= 0:
raise ValueError('n must be >= 0' )
UpperCamelCase_ : int =[]
for num in range(len(__lowercase ) ):
UpperCamelCase_ : Any =0
while 2 * i * i <= odd_composites[num]:
UpperCamelCase_ : str =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 A_ ( ):
return compute_nums(1 )[0]
if __name__ == "__main__":
print(F"""{solution() = }""")
| 395 | 1 |
'''simple docstring'''
from abc import ABC, abstractmethod
from typing import Optional, Union
from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit
from ..utils.typing import NestedDataStructureLike, PathLike
class lowerCamelCase ( lowerCamelCase ):
'''simple docstring'''
def __init__( self : List[Any] , UpperCAmelCase__ : Optional[NestedDataStructureLike[PathLike]] = None , UpperCAmelCase__ : Optional[NamedSplit] = None , UpperCAmelCase__ : Optional[Features] = None , UpperCAmelCase__ : str = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , **UpperCAmelCase__ : str , ) ->Any:
UpperCAmelCase_ = path_or_paths
UpperCAmelCase_ = split if split or isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else '''train'''
UpperCAmelCase_ = features
UpperCAmelCase_ = cache_dir
UpperCAmelCase_ = keep_in_memory
UpperCAmelCase_ = streaming
UpperCAmelCase_ = num_proc
UpperCAmelCase_ = kwargs
@abstractmethod
def lowerCAmelCase__ ( self : Optional[Any] ) ->Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]:
pass
class lowerCamelCase ( lowerCamelCase ):
'''simple docstring'''
def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[Features] = None , UpperCAmelCase__ : str = None , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[int] = None , **UpperCAmelCase__ : List[Any] , ) ->int:
UpperCAmelCase_ = features
UpperCAmelCase_ = cache_dir
UpperCAmelCase_ = keep_in_memory
UpperCAmelCase_ = streaming
UpperCAmelCase_ = num_proc
UpperCAmelCase_ = kwargs
@abstractmethod
def lowerCAmelCase__ ( self : str ) ->Union[Dataset, IterableDataset]:
pass
| 390 | '''simple docstring'''
import argparse
import json
import os
import re
import torch
from transformers import BloomConfig, BloomModel
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
from transformers.utils import logging
logging.set_verbosity_info()
lowercase__ : Union[str, Any] = [
"word_embeddings_layernorm.weight",
"word_embeddings_layernorm.bias",
"input_layernorm.weight",
"input_layernorm.bias",
"post_attention_layernorm.weight",
"post_attention_layernorm.bias",
"self_attention.dense.bias",
"mlp.dense_4h_to_h.bias",
"ln_f.weight",
"ln_f.bias",
]
lowercase__ : Dict = [
"mlp.dense_4h_to_h.weight",
"self_attention.dense.weight",
]
def __lowerCamelCase ( _UpperCamelCase : int , _UpperCamelCase : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = {
'''word_embeddings.weight''': '''word_embeddings.weight''',
'''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''',
'''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''',
'''weight''': '''ln_f.weight''',
'''bias''': '''ln_f.bias''',
}
if key in layer_rename_map:
return layer_rename_map[key]
# Handle transformer blocks
UpperCAmelCase_ = int(re.match(R'''.*layer_(\d*).*''' , _UpperCamelCase )[1] )
layer_number -= 3
return F"""h.{layer_number}.""" + key
def __lowerCamelCase ( _UpperCamelCase : Optional[Any] ):
'''simple docstring'''
if dtype == torch.bool:
return 1 / 8
UpperCAmelCase_ = re.search(R'''[^\d](\d+)$''' , str(_UpperCamelCase ) )
if bit_search is None:
raise ValueError(F"""`dtype` is not a valid dtype: {dtype}.""" )
UpperCAmelCase_ = int(bit_search.groups()[0] )
return bit_size // 8
def __lowerCamelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : str , _UpperCamelCase : Tuple , _UpperCamelCase : Dict , _UpperCamelCase : Dict ):
'''simple docstring'''
if bloom_config_file == "":
UpperCAmelCase_ = BloomConfig()
else:
UpperCAmelCase_ = BloomConfig.from_json_file(_UpperCamelCase )
if shard_model:
UpperCAmelCase_ = os.listdir(_UpperCamelCase )
UpperCAmelCase_ = sorted(filter(lambda _UpperCamelCase : s.startswith('''layer''' ) and "model_00" in s , _UpperCamelCase ) )
UpperCAmelCase_ = {'''weight_map''': {}, '''metadata''': {}}
UpperCAmelCase_ = 0
UpperCAmelCase_ = None
UpperCAmelCase_ = BloomConfig()
for j, file in enumerate(_UpperCamelCase ):
print('''Processing file: {}'''.format(_UpperCamelCase ) )
UpperCAmelCase_ = None
for i in range(_UpperCamelCase ):
# load all TP files
UpperCAmelCase_ = file.replace('''model_00''' , F"""model_0{i}""" )
UpperCAmelCase_ = torch.load(os.path.join(_UpperCamelCase , _UpperCamelCase ) , map_location='''cpu''' )
# Rename keys in the transformers names
UpperCAmelCase_ = list(temp.keys() )
for key in keys:
UpperCAmelCase_ = temp.pop(_UpperCamelCase )
if tensors is None:
UpperCAmelCase_ = temp
else:
for key in tensors.keys():
if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
tensors[key] += temp[key]
else:
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
UpperCAmelCase_ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0
# We concatenate these weights accross TP ranks
UpperCAmelCase_ = torch.cat([tensors[key], temp[key]] , dim=_UpperCamelCase )
# Divide by the number of TP the weights we want to average
for key in tensors.keys():
if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
UpperCAmelCase_ = tensors[key] / pretraining_tp
torch.save(
_UpperCamelCase , os.path.join(
_UpperCamelCase , '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1 ).zfill(5 ) , str(len(_UpperCamelCase ) ).zfill(5 ) ) , ) , )
for key in tensors.keys():
UpperCAmelCase_ = tensors[key]
total_size += value.numel() * get_dtype_size(value.dtype )
if key not in index_dict["weight_map"]:
UpperCAmelCase_ = '''pytorch_model_{}-of-{}.bin'''.format(
str(j + 1 ).zfill(5 ) , str(len(_UpperCamelCase ) ).zfill(5 ) )
UpperCAmelCase_ = BloomConfig()
UpperCAmelCase_ = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
UpperCAmelCase_ = total_size
with open(_UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
with open(os.path.join(_UpperCamelCase , WEIGHTS_NAME + '''.index.json''' ) , '''w''' , encoding='''utf-8''' ) as f:
UpperCAmelCase_ = json.dumps(_UpperCamelCase , indent=2 , sort_keys=_UpperCamelCase ) + '''\n'''
f.write(_UpperCamelCase )
else:
UpperCAmelCase_ = BloomModel(_UpperCamelCase )
UpperCAmelCase_ = os.listdir(_UpperCamelCase )
UpperCAmelCase_ = sorted(filter(lambda _UpperCamelCase : s.startswith('''layer''' ) and "model_00" in s , _UpperCamelCase ) )
UpperCAmelCase_ = None
for i, file in enumerate(_UpperCamelCase ):
UpperCAmelCase_ = None
for i in range(_UpperCamelCase ):
# load all TP files
UpperCAmelCase_ = file.replace('''model_00''' , F"""model_0{i}""" )
UpperCAmelCase_ = torch.load(os.path.join(_UpperCamelCase , _UpperCamelCase ) , map_location='''cpu''' )
# Rename keys in the transformers names
UpperCAmelCase_ = list(temp.keys() )
for key in keys:
UpperCAmelCase_ = temp.pop(_UpperCamelCase )
if tensors is None:
UpperCAmelCase_ = temp
else:
for key in tensors.keys():
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
tensors[key] += temp[key]
else:
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
UpperCAmelCase_ = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0
# We concatenate these weights accross TP ranks
UpperCAmelCase_ = torch.cat([tensors[key], temp[key]] , dim=_UpperCamelCase )
# Divide by the number of TP the weights we want to average
for key in tensors.keys():
if any(key.endswith(_UpperCamelCase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
UpperCAmelCase_ = tensors[key] / pretraining_tp
UpperCAmelCase_ = model.load_state_dict(_UpperCamelCase , strict=_UpperCamelCase )
assert not other_keys.unexpected_keys, F"""The keys {other_keys.unexpected_keys} are unexpected"""
if missing_keys is None:
UpperCAmelCase_ = set(other_keys.missing_keys )
else:
UpperCAmelCase_ = missing_keys.intersection(set(other_keys.missing_keys ) )
assert not missing_keys, F"""The keys {missing_keys} are missing"""
# Save pytorch-model
os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase )
UpperCAmelCase_ = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
UpperCAmelCase_ = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F"""Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}""" )
if config.torch_dtype is not None:
UpperCAmelCase_ = model.to(config.torch_dtype )
torch.save(model.state_dict() , _UpperCamelCase )
print(F"""Save configuration file to {pytorch_config_dump_path}""" )
with open(_UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
lowercase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--bloom_checkpoint_path",
default=None,
type=str,
required=True,
help="Path to the Megatron-LM checkpoint path.",
)
parser.add_argument(
"--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument(
"--bloom_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--shard_model",
action="store_true",
help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint",
)
parser.add_argument(
"--pretraining_tp",
default=4,
type=int,
help="Pretraining TP rank that has been used when training the model in Megatron-LM \n",
)
lowercase__ : Any = parser.parse_args()
convert_bloom_checkpoint_to_pytorch(
args.bloom_checkpoint_path,
args.bloom_config_file,
args.pytorch_dump_folder_path,
args.shard_model,
args.pretraining_tp,
)
| 390 | 1 |
'''simple docstring'''
import inspect
import unittest
from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __SCREAMING_SNAKE_CASE :
def __init__( self , __UpperCamelCase , __UpperCamelCase=13 , __UpperCamelCase=32 , __UpperCamelCase=3 , __UpperCamelCase=4 , __UpperCamelCase=[10, 20, 30, 40] , __UpperCamelCase=[2, 2, 3, 2] , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=37 , __UpperCamelCase="gelu" , __UpperCamelCase=10 , __UpperCamelCase=0.02 , __UpperCamelCase=["stage2", "stage3", "stage4"] , __UpperCamelCase=[2, 3, 4] , __UpperCamelCase=None , ) -> Optional[Any]:
_a = parent
_a = batch_size
_a = image_size
_a = num_channels
_a = num_stages
_a = hidden_sizes
_a = depths
_a = is_training
_a = use_labels
_a = intermediate_size
_a = hidden_act
_a = num_labels
_a = initializer_range
_a = out_features
_a = out_indices
_a = scope
def a_ ( self ) -> Tuple:
_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 a_ ( self ) -> List[str]:
return ConvNextVaConfig(
num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=__UpperCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , )
def a_ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Tuple:
_a = ConvNextVaModel(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
_a = model(__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 a_ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> Union[str, Any]:
_a = ConvNextVaForImageClassification(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
_a = model(__UpperCamelCase , labels=__UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def a_ ( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> List[Any]:
_a = ConvNextVaBackbone(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
_a = model(__UpperCamelCase )
# verify hidden states
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] )
# verify channels
self.parent.assertEqual(len(model.channels ) , len(config.out_features ) )
self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] )
# verify backbone works with out_features=None
_a = None
_a = ConvNextVaBackbone(config=__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
_a = model(__UpperCamelCase )
# verify feature maps
self.parent.assertEqual(len(result.feature_maps ) , 1 )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] )
# verify channels
self.parent.assertEqual(len(model.channels ) , 1 )
self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] )
def a_ ( self ) -> Optional[int]:
_a = self.prepare_config_and_inputs()
_a , _a , _a = config_and_inputs
_a = {"pixel_values": pixel_values}
return config, inputs_dict
def a_ ( self ) -> int:
_a = self.prepare_config_and_inputs()
_a , _a , _a = config_and_inputs
_a = {"pixel_values": pixel_values, "labels": labels}
return config, inputs_dict
@require_torch
class __SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ):
UpperCAmelCase = (
(
ConvNextVaModel,
ConvNextVaForImageClassification,
ConvNextVaBackbone,
)
if is_torch_available()
else ()
)
UpperCAmelCase = (
{'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
if is_torch_available()
else {}
)
UpperCAmelCase = False
UpperCAmelCase = False
UpperCAmelCase = False
UpperCAmelCase = False
UpperCAmelCase = False
def a_ ( self ) -> Union[str, Any]:
_a = ConvNextVaModelTester(self )
_a = ConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase , hidden_size=37 )
def a_ ( self ) -> Union[str, Any]:
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 a_ ( self ) -> List[str]:
return
@unittest.skip(reason="ConvNextV2 does not use inputs_embeds" )
def a_ ( self ) -> Optional[Any]:
pass
@unittest.skip(reason="ConvNextV2 does not support input and output embeddings" )
def a_ ( self ) -> Optional[Any]:
pass
@unittest.skip(reason="ConvNextV2 does not use feedforward chunking" )
def a_ ( self ) -> str:
pass
def a_ ( self ) -> Optional[int]:
if not self.model_tester.is_training:
return
for model_class in self.all_model_classes:
_a , _a = self.model_tester.prepare_config_and_inputs_with_labels()
_a = True
if model_class.__name__ in [
*get_values(__UpperCamelCase ),
*get_values(__UpperCamelCase ),
]:
continue
_a = model_class(__UpperCamelCase )
model.to(__UpperCamelCase )
model.train()
_a = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
_a = model(**__UpperCamelCase ).loss
loss.backward()
def a_ ( self ) -> Any:
if not self.model_tester.is_training:
return
for model_class in self.all_model_classes:
_a , _a = self.model_tester.prepare_config_and_inputs_with_labels()
_a = False
_a = True
if (
model_class.__name__
in [*get_values(__UpperCamelCase ), *get_values(__UpperCamelCase )]
or not model_class.supports_gradient_checkpointing
):
continue
_a = model_class(__UpperCamelCase )
model.to(__UpperCamelCase )
model.gradient_checkpointing_enable()
model.train()
_a = self._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase )
_a = model(**__UpperCamelCase ).loss
loss.backward()
def a_ ( self ) -> Tuple:
_a , _a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_a = model_class(__UpperCamelCase )
_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] , __UpperCamelCase )
def a_ ( self ) -> str:
_a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCamelCase )
def a_ ( self ) -> Tuple:
def check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
_a = model_class(__UpperCamelCase )
model.to(__UpperCamelCase )
model.eval()
with torch.no_grad():
_a = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) )
_a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
_a = self.model_tester.num_stages
self.assertEqual(len(__UpperCamelCase ) , expected_num_stages + 1 )
# ConvNextV2'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] , )
_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(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
_a = True
check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
def a_ ( self ) -> int:
_a = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase )
@slow
def a_ ( self ) -> Dict:
for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_a = ConvNextVaModel.from_pretrained(__UpperCamelCase )
self.assertIsNotNone(__UpperCamelCase )
def __UpperCamelCase ( ) -> List[Any]:
'''simple docstring'''
_a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
@cached_property
def a_ ( self ) -> Optional[int]:
return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224" ) if is_vision_available() else None
@slow
def a_ ( self ) -> List[str]:
_a = ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224" ).to(__UpperCamelCase )
_a = self.default_image_processor
_a = prepare_img()
_a = preprocessor(images=__UpperCamelCase , return_tensors="pt" ).to(__UpperCamelCase )
# forward pass
with torch.no_grad():
_a = model(**__UpperCamelCase )
# verify the logits
_a = torch.Size((1, 1_000) )
self.assertEqual(outputs.logits.shape , __UpperCamelCase )
_a = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(__UpperCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __UpperCamelCase , atol=1e-4 ) )
| 276 |
'''simple docstring'''
from collections import defaultdict
from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst
def __UpperCamelCase ( ) -> Tuple:
'''simple docstring'''
_a , _a = 9, 14 # noqa: F841
_a = [
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[7, 8, 7],
[7, 6, 1],
[2, 8, 2],
[8, 6, 6],
[2, 3, 7],
[2, 5, 4],
[6, 5, 2],
[3, 5, 14],
[3, 4, 9],
[5, 4, 10],
[1, 7, 11],
]
_a = defaultdict(__lowerCamelCase )
for nodea, nodea, cost in edges:
adjancency[nodea].append([nodea, cost] )
adjancency[nodea].append([nodea, cost] )
_a = mst(__lowerCamelCase )
_a = [
[7, 6, 1],
[2, 8, 2],
[6, 5, 2],
[0, 1, 4],
[2, 5, 4],
[2, 3, 7],
[0, 7, 8],
[3, 4, 9],
]
for answer in expected:
_a = tuple(answer[:2] )
_a = tuple(edge[::-1] )
assert edge in result or reverse in result
| 276 | 1 |
import warnings
from typing import Dict, List, Optional, Tuple
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCAmelCase_ : Dict = logging.get_logger(__name__)
class __A ( UpperCamelCase__ ):
UpperCamelCase = ["""input_ids""", """attention_mask"""]
def __init__( self :Optional[int] , __snake_case :int="</s>" , __snake_case :List[Any]="<unk>" , __snake_case :Optional[int]="<pad>" , __snake_case :Any=1_25 , __snake_case :Optional[Any]=None , **__snake_case :Optional[int] , ):
'''simple docstring'''
if extra_ids > 0 and additional_special_tokens is None:
__magic_name__ : Tuple =[f"<extra_id_{i}>" for i in range(__snake_case )]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
__magic_name__ : List[Any] =len(set(filter(lambda __snake_case : bool("""extra_id""" in str(__snake_case ) ) , __snake_case ) ) )
if extra_tokens != extra_ids:
raise ValueError(
f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
""" provided to ByT5Tokenizer. In this case the additional_special_tokens must include the"""
""" extra_ids tokens""" )
__magic_name__ : Tuple =AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else pad_token
__magic_name__ : List[str] =AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else eos_token
__magic_name__ : int =AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else unk_token
super().__init__(
eos_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , extra_ids=__snake_case , additional_special_tokens=__snake_case , **__snake_case , )
__magic_name__ : Union[str, Any] =extra_ids
__magic_name__ : Tuple =2**8 # utf is 8 bits
# define special tokens dict
__magic_name__ : Dict[int, str] ={
self.pad_token: 0,
self.eos_token: 1,
self.unk_token: 2,
}
__magic_name__ : Optional[int] =len(self.special_tokens_encoder )
__magic_name__ : Any =len(__snake_case )
for i, token in enumerate(__snake_case ):
__magic_name__ : Union[str, Any] =self.vocab_size + i - n
__magic_name__ : Dict[str, int] ={v: k for k, v in self.special_tokens_encoder.items()}
@property
def A__ ( self :Optional[Any] ):
'''simple docstring'''
return self._utf_vocab_size + self._num_special_tokens + self._extra_ids
def A__ ( self :Tuple , __snake_case :List[int] , __snake_case :Optional[List[int]] = None , __snake_case :bool = False ):
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case )
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(__snake_case )) + [1]
return ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) + [1]
def A__ ( self :Union[str, Any] , __snake_case :List[int] ):
'''simple docstring'''
if len(__snake_case ) > 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 A__ ( self :Any , __snake_case :List[int] , __snake_case :Optional[List[int]] = None ):
'''simple docstring'''
__magic_name__ : Union[str, Any] =[self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos ) * [0]
return len(token_ids_a + eos + token_ids_a + eos ) * [0]
def A__ ( self :Union[str, Any] , __snake_case :List[int] , __snake_case :Optional[List[int]] = None ):
'''simple docstring'''
__magic_name__ : Optional[Any] =self._add_eos_if_not_present(__snake_case )
if token_ids_a is None:
return token_ids_a
else:
__magic_name__ : List[str] =self._add_eos_if_not_present(__snake_case )
return token_ids_a + token_ids_a
def A__ ( self :Tuple , __snake_case :str ):
'''simple docstring'''
__magic_name__ : Dict =[chr(__snake_case ) for i in text.encode("""utf-8""" )]
return tokens
def A__ ( self :int , __snake_case :List[str] ):
'''simple docstring'''
if token in self.special_tokens_encoder:
__magic_name__ : Dict =self.special_tokens_encoder[token]
elif token in self.added_tokens_encoder:
__magic_name__ : int =self.added_tokens_encoder[token]
elif len(__snake_case ) != 1:
__magic_name__ : Optional[Any] =self.unk_token_id
else:
__magic_name__ : Any =ord(__snake_case ) + self._num_special_tokens
return token_id
def A__ ( self :Optional[Any] , __snake_case :int ):
'''simple docstring'''
if index in self.special_tokens_decoder:
__magic_name__ : Any =self.special_tokens_decoder[index]
else:
__magic_name__ : int =chr(index - self._num_special_tokens )
return token
def A__ ( self :Union[str, Any] , __snake_case :int ):
'''simple docstring'''
__magic_name__ : Any =B""""""
for token in tokens:
if token in self.special_tokens_decoder:
__magic_name__ : int =self.special_tokens_decoder[token].encode("""utf-8""" )
elif token in self.added_tokens_decoder:
__magic_name__ : Union[str, Any] =self.special_tokens_decoder[token].encode("""utf-8""" )
elif token in self.special_tokens_encoder:
__magic_name__ : str =token.encode("""utf-8""" )
elif token in self.added_tokens_encoder:
__magic_name__ : Optional[int] =token.encode("""utf-8""" )
else:
__magic_name__ : Tuple =bytes([ord(__snake_case )] )
bstring += tok_string
__magic_name__ : str =bstring.decode("""utf-8""" , errors="""ignore""" )
return string
def A__ ( self :Tuple , __snake_case :str , __snake_case :Optional[str] = None ):
'''simple docstring'''
return ()
| 21 |
import unittest
from accelerate import debug_launcher
from accelerate.test_utils import require_cpu, test_ops, test_script
@require_cpu
class __A ( unittest.TestCase ):
def A__ ( self :Tuple ):
'''simple docstring'''
debug_launcher(test_script.main )
def A__ ( self :Dict ):
'''simple docstring'''
debug_launcher(test_ops.main )
| 21 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCAmelCase : List[str] =logging.get_logger(__name__)
lowerCAmelCase : Union[str, Any] ={
"microsoft/swinv2-tiny-patch4-window8-256": (
"https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json"
),
}
class __snake_case ( lowercase_ ):
'''simple docstring'''
_snake_case = '''swinv2'''
_snake_case = {
'''num_attention_heads''': '''num_heads''',
'''num_hidden_layers''': '''num_layers''',
}
def __init__( self : str , _UpperCamelCase : Dict=224 , _UpperCamelCase : List[Any]=4 , _UpperCamelCase : Tuple=3 , _UpperCamelCase : List[str]=96 , _UpperCamelCase : str=[2, 2, 6, 2] , _UpperCamelCase : Tuple=[3, 6, 12, 24] , _UpperCamelCase : List[str]=7 , _UpperCamelCase : str=4.0 , _UpperCamelCase : List[str]=True , _UpperCamelCase : Tuple=0.0 , _UpperCamelCase : Tuple=0.0 , _UpperCamelCase : Optional[int]=0.1 , _UpperCamelCase : Any="gelu" , _UpperCamelCase : List[Any]=False , _UpperCamelCase : Tuple=0.0_2 , _UpperCamelCase : Optional[int]=1E-5 , _UpperCamelCase : Dict=32 , **_UpperCamelCase : str , ) ->Optional[Any]:
"""simple docstring"""
super().__init__(**UpperCamelCase__)
_lowerCamelCase : Tuple = image_size
_lowerCamelCase : Dict = patch_size
_lowerCamelCase : Optional[Any] = num_channels
_lowerCamelCase : Union[str, Any] = embed_dim
_lowerCamelCase : Dict = depths
_lowerCamelCase : str = len(UpperCamelCase__)
_lowerCamelCase : int = num_heads
_lowerCamelCase : Optional[Any] = window_size
_lowerCamelCase : Any = mlp_ratio
_lowerCamelCase : Dict = qkv_bias
_lowerCamelCase : Dict = hidden_dropout_prob
_lowerCamelCase : Dict = attention_probs_dropout_prob
_lowerCamelCase : str = drop_path_rate
_lowerCamelCase : Union[str, Any] = hidden_act
_lowerCamelCase : Optional[int] = use_absolute_embeddings
_lowerCamelCase : List[Any] = layer_norm_eps
_lowerCamelCase : List[str] = initializer_range
_lowerCamelCase : Any = encoder_stride
# we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
_lowerCamelCase : Dict = int(embed_dim * 2 ** (len(UpperCamelCase__) - 1))
_lowerCamelCase : Optional[Any] = (0, 0, 0, 0)
| 710 | from __future__ import annotations
from math import pi
from typing import Protocol
import matplotlib.pyplot as plt
import numpy as np
class __snake_case ( __lowerCAmelCase ):
'''simple docstring'''
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , _UpperCamelCase : float) ->float:
"""simple docstring"""
return 0.0
def A__ ( __A , __A ):
'''simple docstring'''
_lowerCamelCase : int = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] )
_lowerCamelCase : Tuple = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] )
return lowest, highest
def A__ ( __A , __A ):
'''simple docstring'''
_lowerCamelCase : Tuple = 512
_lowerCamelCase : Tuple = [1] + [0] * (size - 1)
_lowerCamelCase : Optional[Any] = [filter_type.process(__A ) for item in inputs]
_lowerCamelCase : Optional[Any] = [0] * (samplerate - size) # zero-padding
outputs += filler
_lowerCamelCase : Tuple = np.abs(np.fft.fft(__A ) )
_lowerCamelCase : List[Any] = 20 * np.logaa(__A )
# Frequencies on log scale from 24 to nyquist frequency
plt.xlim(24 , samplerate / 2 - 1 )
plt.xlabel("""Frequency (Hz)""" )
plt.xscale("""log""" )
# Display within reasonable bounds
_lowerCamelCase : Any = get_bounds(__A , __A )
plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) )
plt.ylabel("""Gain (dB)""" )
plt.plot(__A )
plt.show()
def A__ ( __A , __A ):
'''simple docstring'''
_lowerCamelCase : Tuple = 512
_lowerCamelCase : Union[str, Any] = [1] + [0] * (size - 1)
_lowerCamelCase : int = [filter_type.process(__A ) for item in inputs]
_lowerCamelCase : Optional[Any] = [0] * (samplerate - size) # zero-padding
outputs += filler
_lowerCamelCase : Any = np.angle(np.fft.fft(__A ) )
# Frequencies on log scale from 24 to nyquist frequency
plt.xlim(24 , samplerate / 2 - 1 )
plt.xlabel("""Frequency (Hz)""" )
plt.xscale("""log""" )
plt.ylim(-2 * pi , 2 * pi )
plt.ylabel("""Phase shift (Radians)""" )
plt.plot(np.unwrap(__A , -2 * pi ) )
plt.show()
| 15 | 0 |
'''simple docstring'''
import json
import os
import subprocess
import unittest
from ast import literal_eval
import pytest
from parameterized import parameterized, parameterized_class
from . import is_sagemaker_available
if is_sagemaker_available():
from sagemaker import Session, TrainingJobAnalytics
from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , )
@pytest.mark.usefixtures('sm_env' )
@parameterized_class(
[
{
'framework': 'pytorch',
'script': 'run_glue_model_parallelism.py',
'model_name_or_path': 'roberta-large',
'instance_type': 'ml.p3dn.24xlarge',
'results': {'train_runtime': 16_00, 'eval_accuracy': 0.3, 'eval_loss': 1.2},
},
{
'framework': 'pytorch',
'script': 'run_glue.py',
'model_name_or_path': 'roberta-large',
'instance_type': 'ml.p3dn.24xlarge',
'results': {'train_runtime': 16_00, 'eval_accuracy': 0.3, 'eval_loss': 1.2},
},
] )
class __UpperCamelCase ( unittest.TestCase ):
def lowercase__ ( self ):
"""simple docstring"""
if self.framework == "pytorch":
subprocess.run(
f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split(), encoding='''utf-8''', check=lowerCAmelCase, )
assert hasattr(self, '''env''' )
def lowercase__ ( self, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ ={
'enabled': True,
'processes_per_host': 8,
}
lowerCamelCase_ ={
'enabled': True,
'parameters': {
'microbatches': 4,
'placement_strategy': 'spread',
'pipeline': 'interleaved',
'optimize': 'speed',
'partitions': 4,
'ddp': True,
},
}
lowerCamelCase_ ={'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options}
lowerCamelCase_ ='trainer' if self.script == 'run_glue.py' else 'smtrainer'
# creates estimator
return HuggingFace(
entry_point=self.script, source_dir=self.env.test_path, role=self.env.role, image_uri=self.env.image_uri, base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''', instance_count=lowerCAmelCase, instance_type=self.instance_type, debugger_hook_config=lowerCAmelCase, hyperparameters={
**self.env.hyperparameters,
'''model_name_or_path''': self.model_name_or_path,
'''max_steps''': 500,
}, metric_definitions=self.env.metric_definitions, distribution=lowerCAmelCase, py_version='''py36''', )
def lowercase__ ( self, lowerCAmelCase ):
"""simple docstring"""
TrainingJobAnalytics(lowerCAmelCase ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' )
@parameterized.expand([(1,)] )
def lowercase__ ( self, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ =self.create_estimator(lowerCAmelCase )
# run training
estimator.fit()
# result dataframe
lowerCamelCase_ =TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe()
# extract kpis
lowerCamelCase_ =list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] )
lowerCamelCase_ =list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] )
# get train time from SageMaker job, this includes starting, preprocessing, stopping
lowerCamelCase_ =(
Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''', 999_999 )
)
# assert kpis
assert train_runtime <= self.results["train_runtime"]
assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy )
assert all(t <= self.results['''eval_loss'''] for t in eval_loss )
# dump tests result into json file to share in PR
with open(f'''{estimator.latest_training_job.name}.json''', '''w''' ) as outfile:
json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss}, lowerCAmelCase )
| 676 |
def _lowercase ( __SCREAMING_SNAKE_CASE ) -> bool:
UpperCamelCase__ : set[int] = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
UpperCamelCase__ : set[int] = set()
return any(
node not in visited and depth_first_search(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
for node in graph )
def _lowercase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> bool:
visited.add(__SCREAMING_SNAKE_CASE )
rec_stk.add(__SCREAMING_SNAKE_CASE )
for node in graph[vertex]:
if node not in visited:
if depth_first_search(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(__SCREAMING_SNAKE_CASE )
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| 410 | 0 |
'''simple docstring'''
import logging
import os
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
from accelerate.utils.imports import (
is_abit_bnb_available,
is_abit_bnb_available,
is_bnb_available,
)
from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
find_tied_parameters,
get_balanced_memory,
infer_auto_device_map,
load_checkpoint_in_model,
offload_weight,
set_module_tensor_to_device,
)
if is_bnb_available():
import bitsandbytes as bnb
from copy import deepcopy
a_ : List[str] = logging.getLogger(__name__)
def _A (lowerCAmelCase__ :torch.nn.Module , lowerCAmelCase__ :BnbQuantizationConfig , lowerCAmelCase__ :Union[str, os.PathLike] = None , lowerCAmelCase__ :Optional[Dict[str, Union[int, str, torch.device]]] = None , lowerCAmelCase__ :Optional[List[str]] = None , lowerCAmelCase__ :Optional[Dict[Union[int, str], Union[int, str]]] = None , lowerCAmelCase__ :Optional[Union[str, os.PathLike]] = None , lowerCAmelCase__ :bool = False , ) -> List[str]:
'''simple docstring'''
_a = bnb_quantization_config.load_in_abit
_a = bnb_quantization_config.load_in_abit
if load_in_abit and not is_abit_bnb_available():
raise ImportError(
'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
' make sure you have the latest version of `bitsandbytes` installed.' )
if load_in_abit and not is_abit_bnb_available():
raise ValueError(
'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
'make sure you have the latest version of `bitsandbytes` installed.' )
_a = []
# custom device map
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(device_map.keys() ) > 1:
_a = [key for key, value in device_map.items() if value in ['disk', 'cpu']]
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
if bnb_quantization_config.skip_modules is None:
_a = get_keys_to_not_convert(lowerCAmelCase__ )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(lowerCAmelCase__ )
_a = bnb_quantization_config.skip_modules
# We add the modules we want to keep in full precision
if bnb_quantization_config.keep_in_fpaa_modules is None:
_a = []
_a = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(lowerCAmelCase__ )
# compatibility with peft
_a = load_in_abit
_a = load_in_abit
_a = get_parameter_device(lowerCAmelCase__ )
if model_device.type != "meta":
# quantization of an already loaded model
logger.warning(
'It is not recommended to quantize a loaded model. '
'The model should be instantiated under the `init_empty_weights` context manager.' )
_a = replace_with_bnb_layers(lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ )
# convert param to the right dtype
_a = bnb_quantization_config.torch_dtype
for name, param in model.state_dict().items():
if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ):
param.to(torch.floataa )
if param.dtype != torch.floataa:
_a = name.replace('.weight' , '' ).replace('.bias' , '' )
_a = getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(lowerCAmelCase__ ):
param.to(lowerCAmelCase__ )
if model_device.type == "cuda":
# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
model.cuda(torch.cuda.current_device() )
torch.cuda.empty_cache()
elif torch.cuda.is_available():
model.to(torch.cuda.current_device() )
else:
raise RuntimeError('No GPU found. A GPU is needed for quantization.' )
logger.info(
f'The model device type is {model_device.type}. However, cuda is needed for quantization.'
'We move the model to cuda.' )
return model
elif weights_location is None:
raise RuntimeError(
f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' )
else:
with init_empty_weights():
_a = replace_with_bnb_layers(
lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ )
_a = get_quantized_model_device_map(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , max_memory=lowerCAmelCase__ , no_split_module_classes=lowerCAmelCase__ , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
_a = True
_a = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] )
load_checkpoint_in_model(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowerCAmelCase__ , offload_state_dict=lowerCAmelCase__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(lowerCAmelCase__ , device_map=lowerCAmelCase__ , offload_dir=lowerCAmelCase__ )
def _A (lowerCAmelCase__ :Tuple , lowerCAmelCase__ :Dict , lowerCAmelCase__ :List[Any]=None , lowerCAmelCase__ :Optional[int]=None , lowerCAmelCase__ :List[Any]=None ) -> List[Any]:
'''simple docstring'''
if device_map is None:
if torch.cuda.is_available():
_a = {'': torch.cuda.current_device()}
else:
raise RuntimeError('No GPU found. A GPU is needed for quantization.' )
logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.' )
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
raise ValueError(
'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
'\'sequential\'.' )
_a = {}
special_dtypes.update(
{
name: bnb_quantization_config.torch_dtype
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.skip_modules )
} )
special_dtypes.update(
{
name: torch.floataa
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules )
} )
_a = {}
_a = special_dtypes
_a = no_split_module_classes
_a = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
_a = get_balanced_memory(
lowerCAmelCase__ , low_zero=(device_map == 'balanced_low_0') , max_memory=lowerCAmelCase__ , **lowerCAmelCase__ , )
_a = max_memory
_a = infer_auto_device_map(lowerCAmelCase__ , **lowerCAmelCase__ )
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
# check if don't have any quantized module on the cpu
_a = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
_a = {
key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
}
for device in ["cpu", "disk"]:
if device in device_map_without_some_modules.values():
if bnb_quantization_config.load_in_abit:
raise ValueError(
'\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n ' )
else:
logger.info(
'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit' )
del device_map_without_some_modules
return device_map
def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :Optional[Any]=None , lowerCAmelCase__ :Any=None ) -> Tuple:
'''simple docstring'''
if modules_to_not_convert is None:
_a = []
_a , _a = _replace_with_bnb_layers(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
if not has_been_replaced:
logger.warning(
'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
' Please double check your model architecture, or submit an issue on github if you think this is'
' a bug.' )
return model
def _A (lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :Union[str, Any]=None , lowerCAmelCase__ :Optional[Any]=None , ) -> List[Any]:
'''simple docstring'''
_a = False
for name, module in model.named_children():
if current_key_name is None:
_a = []
current_key_name.append(lowerCAmelCase__ )
if isinstance(lowerCAmelCase__ , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
_a = '.'.join(lowerCAmelCase__ )
_a = True
for key in modules_to_not_convert:
if (
(key in current_key_name_str) and (key + "." in current_key_name_str)
) or key == current_key_name_str:
_a = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
_a = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowerCAmelCase__ , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
_a = bnb.nn.Linearabit(
module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , )
else:
raise ValueError('load_in_8bit and load_in_4bit can\'t be both False' )
_a = module.weight.data
if module.bias is not None:
_a = module.bias.data
bnb_module.requires_grad_(lowerCAmelCase__ )
setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
_a = True
if len(list(module.children() ) ) > 0:
_a , _a = _replace_with_bnb_layers(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
_a = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _A (lowerCAmelCase__ :Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
with init_empty_weights():
_a = deepcopy(lowerCAmelCase__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
_a = find_tied_parameters(lowerCAmelCase__ )
# For compatibility with Accelerate < 0.18
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
_a = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
_a = sum(lowerCAmelCase__ , [] )
_a = len(lowerCAmelCase__ ) > 0
# Check if it is a base model
_a = False
if hasattr(lowerCAmelCase__ , 'base_model_prefix' ):
_a = not hasattr(lowerCAmelCase__ , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
_a = list(model.named_children() )
_a = [list_modules[-1][0]]
# add last module together with tied weights
_a = set(lowerCAmelCase__ ) - set(lowerCAmelCase__ )
_a = list(set(lowerCAmelCase__ ) ) + list(lowerCAmelCase__ )
# remove ".weight" from the keys
_a = ['.weight', '.bias']
_a = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
_a = name.replace(lowerCAmelCase__ , '' )
filtered_module_names.append(lowerCAmelCase__ )
return filtered_module_names
def _A (lowerCAmelCase__ :List[Any] ) -> List[str]:
'''simple docstring'''
for m in model.modules():
if isinstance(lowerCAmelCase__ , bnb.nn.Linearabit ):
return True
return False
def _A (lowerCAmelCase__ :nn.Module ) -> Union[str, Any]:
'''simple docstring'''
return next(parameter.parameters() ).device
def _A (lowerCAmelCase__ :Any , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Dict , lowerCAmelCase__ :Any , lowerCAmelCase__ :Any , lowerCAmelCase__ :Dict , lowerCAmelCase__ :Dict ) -> Tuple:
'''simple docstring'''
if fpaa_statistics is None:
set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , 0 , dtype=lowerCAmelCase__ , value=lowerCAmelCase__ )
_a = param_name
_a = model
if "." in tensor_name:
_a = tensor_name.split('.' )
for split in splits[:-1]:
_a = getattr(lowerCAmelCase__ , lowerCAmelCase__ )
if new_module is None:
raise ValueError(f'{module} has no attribute {split}.' )
_a = new_module
_a = splits[-1]
# offload weights
_a = False
offload_weight(module._parameters[tensor_name] , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ )
if hasattr(module._parameters[tensor_name] , 'SCB' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , lowerCAmelCase__ , index=lowerCAmelCase__ , )
else:
offload_weight(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ )
offload_weight(lowerCAmelCase__ , param_name.replace('weight' , 'SCB' ) , lowerCAmelCase__ , index=lowerCAmelCase__ )
set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , 'meta' , dtype=lowerCAmelCase__ , value=torch.empty(*param.size() ) )
| 532 |
'''simple docstring'''
class a :
def __init__( self , __magic_name__ ) -> Optional[int]:
_a = n
_a = [None] * self.n
_a = 0 # index of the first element
_a = 0
_a = 0
def __len__( self ) -> int:
return self.size
def __UpperCAmelCase ( self ) -> bool:
return self.size == 0
def __UpperCAmelCase ( self ) -> Optional[Any]:
return False if self.is_empty() else self.array[self.front]
def __UpperCAmelCase ( self , __magic_name__ ) -> Optional[Any]:
if self.size >= self.n:
raise Exception('QUEUE IS FULL' )
_a = data
_a = (self.rear + 1) % self.n
self.size += 1
return self
def __UpperCAmelCase ( self ) -> Any:
if self.size == 0:
raise Exception('UNDERFLOW' )
_a = self.array[self.front]
_a = None
_a = (self.front + 1) % self.n
self.size -= 1
return temp
| 532 | 1 |
'''simple docstring'''
import tempfile
import unittest
from make_student import create_student_by_copying_alternating_layers
from transformers import AutoConfig
from transformers.file_utils import cached_property
from transformers.testing_utils import require_torch
lowerCAmelCase : Tuple = 'sshleifer/bart-tiny-random'
lowerCAmelCase : Tuple = 'patrickvonplaten/t5-tiny-random'
@require_torch
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase):
@cached_property
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
return AutoConfig.from_pretrained(A_ )
def UpperCAmelCase_ ( self )-> Any:
'''simple docstring'''
UpperCamelCase , *UpperCamelCase = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=1 )
self.assertEqual(student.config.num_hidden_layers , 1 )
def UpperCAmelCase_ ( self )-> str:
'''simple docstring'''
UpperCamelCase , *UpperCamelCase = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=A_ )
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase , *UpperCamelCase = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=A_ )
self.assertEqual(student.config.encoder_layers , 1 )
self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers )
def UpperCAmelCase_ ( self )-> Optional[int]:
'''simple docstring'''
UpperCamelCase , *UpperCamelCase = create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=1 , d=1 )
self.assertEqual(student.config.encoder_layers , 1 )
self.assertEqual(student.config.decoder_layers , 1 )
def UpperCAmelCase_ ( self )-> int:
'''simple docstring'''
with self.assertRaises(A_ ):
create_student_by_copying_alternating_layers(A_ , tempfile.mkdtemp() , e=A_ , d=A_ )
| 3 |
'''simple docstring'''
import numpy as np
import torch
from torch.utils.data import DataLoader
from accelerate.utils.dataclasses import DistributedType
class a :
"""simple docstring"""
def __init__( self : Optional[Any] , snake_case_ : List[str]=2 , snake_case_ : Optional[int]=3 , snake_case_ : Union[str, Any]=6_4 , snake_case_ : Optional[Any]=None ):
'''simple docstring'''
snake_case__ : List[str] = np.random.default_rng(snake_case_ )
snake_case__ : int = length
snake_case__ : Tuple = rng.normal(size=(length,) ).astype(np.floataa )
snake_case__ : Optional[Any] = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa )
def __len__( self : List[Any] ):
'''simple docstring'''
return self.length
def __getitem__( self : List[str] , snake_case_ : int ):
'''simple docstring'''
return {"x": self.x[i], "y": self.y[i]}
class a ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : int , snake_case_ : str=0 , snake_case_ : Optional[Any]=0 , snake_case_ : Tuple=False ):
'''simple docstring'''
super().__init__()
snake_case__ : List[str] = torch.nn.Parameter(torch.tensor([2, 3] ).float() )
snake_case__ : Any = torch.nn.Parameter(torch.tensor([2, 3] ).float() )
snake_case__ : int = True
def __magic_name__ ( self : int , snake_case_ : str=None ):
'''simple docstring'''
if self.first_batch:
print(F"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" )
snake_case__ : str = False
return x * self.a[0] + self.b[0]
class a ( torch.nn.Module ):
"""simple docstring"""
def __init__( self : List[str] , snake_case_ : Tuple=0 , snake_case_ : int=0 , snake_case_ : int=False ):
'''simple docstring'''
super().__init__()
snake_case__ : Tuple = torch.nn.Parameter(torch.tensor(snake_case_ ).float() )
snake_case__ : int = torch.nn.Parameter(torch.tensor(snake_case_ ).float() )
snake_case__ : Union[str, Any] = True
def __magic_name__ ( self : Union[str, Any] , snake_case_ : List[str]=None ):
'''simple docstring'''
if self.first_batch:
print(F"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" )
snake_case__ : List[Any] = False
return x * self.a + self.b
def _a ( __lowerCAmelCase : Any , __lowerCAmelCase : int = 16 ):
"""simple docstring"""
from datasets import load_dataset
from transformers import AutoTokenizer
snake_case__ : List[str] = AutoTokenizer.from_pretrained('''bert-base-cased''' )
snake_case__ : Optional[int] = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''}
snake_case__ : List[Any] = load_dataset('''csv''' , data_files=__lowerCAmelCase )
snake_case__ : Union[str, Any] = datasets['''train'''].unique('''label''' )
snake_case__ : Optional[Any] = {v: i for i, v in enumerate(__lowerCAmelCase )}
def tokenize_function(__lowerCAmelCase : Optional[int] ):
# max_length=None => use the model max length (it's actually the default)
snake_case__ : Union[str, Any] = tokenizer(
examples['''sentence1'''] , examples['''sentence2'''] , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , padding='''max_length''' )
if "label" in examples:
snake_case__ : List[Any] = [label_to_id[l] for l in examples['''label''']]
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
snake_case__ : List[Any] = datasets.map(
__lowerCAmelCase , batched=__lowerCAmelCase , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , )
def collate_fn(__lowerCAmelCase : Optional[Any] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(__lowerCAmelCase , padding='''max_length''' , max_length=1_28 , return_tensors='''pt''' )
return tokenizer.pad(__lowerCAmelCase , padding='''longest''' , return_tensors='''pt''' )
# Instantiate dataloaders.
snake_case__ : str = DataLoader(tokenized_datasets['''train'''] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=2 )
snake_case__ : List[Any] = DataLoader(tokenized_datasets['''validation'''] , shuffle=__lowerCAmelCase , collate_fn=__lowerCAmelCase , batch_size=1 )
return train_dataloader, eval_dataloader
| 347 | 0 |
"""simple docstring"""
import gc
import unittest
from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
from diffusers.utils import is_flax_available, load_image, 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 _lowerCamelCase (unittest.TestCase ):
def __UpperCAmelCase ( self : int ):
"""simple docstring"""
super().tearDown()
gc.collect()
def __UpperCAmelCase ( self : Tuple ):
"""simple docstring"""
_lowercase , _lowercase : str = FlaxControlNetModel.from_pretrained(
'lllyasviel/sd-controlnet-canny' , from_pt=lowerCamelCase_ , dtype=jnp.bfloataa )
_lowercase , _lowercase : int = FlaxStableDiffusionControlNetPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , controlnet=lowerCamelCase_ , from_pt=lowerCamelCase_ , dtype=jnp.bfloataa )
_lowercase : Union[str, Any] = controlnet_params
_lowercase : List[Any] = 'bird'
_lowercase : str = jax.device_count()
_lowercase : List[Any] = pipe.prepare_text_inputs([prompts] * num_samples )
_lowercase : Any = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' )
_lowercase : List[Any] = pipe.prepare_image_inputs([canny_image] * num_samples )
_lowercase : str = jax.random.PRNGKey(0 )
_lowercase : Tuple = jax.random.split(lowerCamelCase_ , jax.device_count() )
_lowercase : List[Any] = replicate(lowerCamelCase_ )
_lowercase : Union[str, Any] = shard(lowerCamelCase_ )
_lowercase : Optional[int] = shard(lowerCamelCase_ )
_lowercase : List[Any] = pipe(
prompt_ids=lowerCamelCase_ , image=lowerCamelCase_ , params=lowerCamelCase_ , prng_seed=lowerCamelCase_ , num_inference_steps=5_0 , jit=lowerCamelCase_ , ).images
assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3)
_lowercase : Optional[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
_lowercase : int = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
_lowercase : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten() ) )
_lowercase : str = jnp.array(
[0.16_7969, 0.11_6699, 0.08_1543, 0.15_4297, 0.13_2812, 0.10_8887, 0.16_9922, 0.16_9922, 0.20_5078] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
def __UpperCAmelCase ( self : List[Any] ):
"""simple docstring"""
_lowercase , _lowercase : Dict = FlaxControlNetModel.from_pretrained(
'lllyasviel/sd-controlnet-openpose' , from_pt=lowerCamelCase_ , dtype=jnp.bfloataa )
_lowercase , _lowercase : Union[str, Any] = FlaxStableDiffusionControlNetPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , controlnet=lowerCamelCase_ , from_pt=lowerCamelCase_ , dtype=jnp.bfloataa )
_lowercase : Optional[Any] = controlnet_params
_lowercase : Optional[int] = 'Chef in the kitchen'
_lowercase : Optional[Any] = jax.device_count()
_lowercase : Optional[Any] = pipe.prepare_text_inputs([prompts] * num_samples )
_lowercase : int = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png' )
_lowercase : Dict = pipe.prepare_image_inputs([pose_image] * num_samples )
_lowercase : Dict = jax.random.PRNGKey(0 )
_lowercase : Dict = jax.random.split(lowerCamelCase_ , jax.device_count() )
_lowercase : Optional[Any] = replicate(lowerCamelCase_ )
_lowercase : int = shard(lowerCamelCase_ )
_lowercase : Dict = shard(lowerCamelCase_ )
_lowercase : Any = pipe(
prompt_ids=lowerCamelCase_ , image=lowerCamelCase_ , params=lowerCamelCase_ , prng_seed=lowerCamelCase_ , num_inference_steps=5_0 , jit=lowerCamelCase_ , ).images
assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3)
_lowercase : List[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
_lowercase : Optional[Any] = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
_lowercase : str = jnp.asarray(jax.device_get(image_slice.flatten() ) )
_lowercase : int = jnp.array(
[[0.27_1484, 0.26_1719, 0.27_5391, 0.27_7344, 0.27_9297, 0.29_1016, 0.29_4922, 0.30_2734, 0.30_2734]] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
| 283 | """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,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
class _lowerCamelCase (__lowerCamelCase ):
_snake_case = ["pixel_values"]
def __init__( self : Optional[int] , lowerCamelCase_ : bool = True , lowerCamelCase_ : Optional[Dict[str, int]] = None , lowerCamelCase_ : PILImageResampling = PILImageResampling.BILINEAR , lowerCamelCase_ : bool = True , lowerCamelCase_ : Dict[str, int] = None , lowerCamelCase_ : bool = True , lowerCamelCase_ : Union[int, float] = 1 / 2_5_5 , lowerCamelCase_ : bool = True , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , **lowerCamelCase_ : int , ):
"""simple docstring"""
super().__init__(**lowerCamelCase_ )
_lowercase : Optional[Any] = size if size is not None else {'shortest_edge': 2_5_6}
_lowercase : Optional[int] = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ )
_lowercase : List[str] = crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
_lowercase : Any = get_size_dict(lowerCamelCase_ )
_lowercase : Optional[int] = do_resize
_lowercase : Optional[int] = size
_lowercase : Union[str, Any] = resample
_lowercase : Optional[Any] = do_center_crop
_lowercase : Union[str, Any] = crop_size
_lowercase : Any = do_rescale
_lowercase : Tuple = rescale_factor
_lowercase : Optional[int] = do_normalize
_lowercase : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_lowercase : Any = image_std if image_std is not None else IMAGENET_STANDARD_STD
def __UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : Tuple , ):
"""simple docstring"""
_lowercase : Optional[Any] = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
_lowercase : Dict = get_resize_output_image_size(lowerCamelCase_ , size=size['shortest_edge'] , default_to_square=lowerCamelCase_ )
return resize(lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ )
def __UpperCAmelCase ( self : Dict , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : str , ):
"""simple docstring"""
_lowercase : Tuple = get_size_dict(lowerCamelCase_ )
return center_crop(lowerCamelCase_ , size=(size['height'], size['width']) , data_format=lowerCamelCase_ , **lowerCamelCase_ )
def __UpperCAmelCase ( self : Any , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : float , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : Optional[Any] ):
"""simple docstring"""
return rescale(lowerCamelCase_ , scale=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ )
def __UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : np.ndarray , lowerCamelCase_ : Union[float, List[float]] , lowerCamelCase_ : Union[float, List[float]] , lowerCamelCase_ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ : List[Any] , ):
"""simple docstring"""
return normalize(lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ )
def __UpperCAmelCase ( self : List[Any] , lowerCamelCase_ : ImageInput , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Dict[str, int] = None , lowerCamelCase_ : PILImageResampling = None , lowerCamelCase_ : bool = None , lowerCamelCase_ : Dict[str, int] = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[float] = None , lowerCamelCase_ : Optional[bool] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[float, List[float]]] = None , lowerCamelCase_ : Optional[Union[str, TensorType]] = None , lowerCamelCase_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase_ : int , ):
"""simple docstring"""
_lowercase : Optional[Any] = do_resize if do_resize is not None else self.do_resize
_lowercase : List[Any] = size if size is not None else self.size
_lowercase : Union[str, Any] = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ )
_lowercase : Any = resample if resample is not None else self.resample
_lowercase : Tuple = do_center_crop if do_center_crop is not None else self.do_center_crop
_lowercase : List[Any] = crop_size if crop_size is not None else self.crop_size
_lowercase : Tuple = get_size_dict(lowerCamelCase_ )
_lowercase : List[Any] = do_rescale if do_rescale is not None else self.do_rescale
_lowercase : int = rescale_factor if rescale_factor is not None else self.rescale_factor
_lowercase : int = do_normalize if do_normalize is not None else self.do_normalize
_lowercase : str = image_mean if image_mean is not None else self.image_mean
_lowercase : List[Any] = image_std if image_std is not None else self.image_std
_lowercase : Union[str, Any] = make_list_of_images(lowerCamelCase_ )
if not valid_images(lowerCamelCase_ ):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.' )
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.' )
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.' )
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.' )
# All transformations expect numpy arrays.
_lowercase : Optional[Any] = [to_numpy_array(lowerCamelCase_ ) for image in images]
if do_resize:
_lowercase : Optional[Any] = [self.resize(image=lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ ) for image in images]
if do_center_crop:
_lowercase : List[Any] = [self.center_crop(image=lowerCamelCase_ , size=lowerCamelCase_ ) for image in images]
if do_rescale:
_lowercase : str = [self.rescale(image=lowerCamelCase_ , scale=lowerCamelCase_ ) for image in images]
if do_normalize:
_lowercase : Any = [self.normalize(image=lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ ) for image in images]
_lowercase : int = [to_channel_dimension_format(lowerCamelCase_ , lowerCamelCase_ ) for image in images]
_lowercase : Tuple = {'pixel_values': images}
return BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ )
| 283 | 1 |
"""simple docstring"""
import numpy as np
def lowerCamelCase (a_ :np.array) -> np.array:
return 1 / (1 + np.exp(-vector))
def lowerCamelCase (a_ :np.array) -> np.array:
return vector * sigmoid(1.7_02 * vector)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 677 |
"""simple docstring"""
import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List
import git
import torch
from torch.utils.data import Dataset
from transformers import BartTokenizer, RagTokenizer, TaTokenizer
def lowerCamelCase (a_ :List[Any] , a_ :Union[str, Any] , a_ :Tuple , a_ :List[str] , a_ :str=True , a_ :str="pt") -> List[str]:
lowercase :Optional[int] = {'''add_prefix_space''': True} if isinstance(a_ , a_) and not line.startswith(''' ''') else {}
lowercase :Optional[int] = padding_side
return tokenizer(
[line] , max_length=a_ , padding='''max_length''' if pad_to_max_length else None , truncation=a_ , return_tensors=a_ , add_special_tokens=a_ , **a_ , )
def lowerCamelCase (a_ :str , a_ :Tuple , a_ :Optional[Any]=None , ) -> Tuple:
lowercase :Optional[Any] = input_ids.ne(a_).any(dim=0)
if attention_mask is None:
return input_ids[:, keep_column_mask]
else:
return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class __magic_name__ ( __UpperCAmelCase ):
def __init__( self : Union[str, Any] , snake_case__ : Union[str, Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : str="train" , snake_case__ : Optional[Any]=None , snake_case__ : Tuple=None , snake_case__ : Any=None , snake_case__ : Dict="" , ):
'''simple docstring'''
super().__init__()
lowercase :Tuple = Path(snake_case__ ).joinpath(type_path + '''.source''' )
lowercase :Union[str, Any] = Path(snake_case__ ).joinpath(type_path + '''.target''' )
lowercase :List[Any] = self.get_char_lens(self.src_file )
lowercase :Tuple = max_source_length
lowercase :Optional[int] = max_target_length
assert min(self.src_lens ) > 0, f"""found empty line in {self.src_file}"""
lowercase :Any = tokenizer
lowercase :Tuple = prefix
if n_obs is not None:
lowercase :List[str] = self.src_lens[:n_obs]
lowercase :List[Any] = src_lang
lowercase :str = tgt_lang
def __len__( self : Any ):
'''simple docstring'''
return len(self.src_lens )
def __getitem__( self : str , snake_case__ : Any ):
'''simple docstring'''
lowercase :Optional[int] = index + 1 # linecache starts at 1
lowercase :Optional[Any] = self.prefix + linecache.getline(str(self.src_file ) , snake_case__ ).rstrip('''\n''' )
lowercase :Dict = linecache.getline(str(self.tgt_file ) , snake_case__ ).rstrip('''\n''' )
assert source_line, f"""empty source line for index {index}"""
assert tgt_line, f"""empty tgt line for index {index}"""
# Need to add eos token manually for T5
if isinstance(self.tokenizer , snake_case__ ):
source_line += self.tokenizer.eos_token
tgt_line += self.tokenizer.eos_token
# Pad source and target to the right
lowercase :Dict = (
self.tokenizer.question_encoder if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer
)
lowercase :Optional[int] = self.tokenizer.generator if isinstance(self.tokenizer , snake_case__ ) else self.tokenizer
lowercase :Optional[int] = encode_line(snake_case__ , snake_case__ , self.max_source_length , '''right''' )
lowercase :Tuple = encode_line(snake_case__ , snake_case__ , self.max_target_length , '''right''' )
lowercase :List[str] = source_inputs['''input_ids'''].squeeze()
lowercase :Optional[Any] = target_inputs['''input_ids'''].squeeze()
lowercase :List[str] = source_inputs['''attention_mask'''].squeeze()
return {
"input_ids": source_ids,
"attention_mask": src_mask,
"decoder_input_ids": target_ids,
}
@staticmethod
def __snake_case ( snake_case__ : Optional[int] ):
'''simple docstring'''
return [len(snake_case__ ) for x in Path(snake_case__ ).open().readlines()]
def __snake_case ( self : Tuple , snake_case__ : Union[str, Any] ):
'''simple docstring'''
lowercase :Optional[Any] = torch.stack([x['''input_ids'''] for x in batch] )
lowercase :Tuple = torch.stack([x['''attention_mask'''] for x in batch] )
lowercase :Tuple = torch.stack([x['''decoder_input_ids'''] for x in batch] )
lowercase :str = (
self.tokenizer.generator.pad_token_id
if isinstance(self.tokenizer , snake_case__ )
else self.tokenizer.pad_token_id
)
lowercase :Optional[int] = (
self.tokenizer.question_encoder.pad_token_id
if isinstance(self.tokenizer , snake_case__ )
else self.tokenizer.pad_token_id
)
lowercase :List[Any] = trim_batch(snake_case__ , snake_case__ )
lowercase , lowercase :List[str] = trim_batch(snake_case__ , snake_case__ , attention_mask=snake_case__ )
lowercase :Optional[int] = {
'''input_ids''': source_ids,
'''attention_mask''': source_mask,
'''decoder_input_ids''': y,
}
return batch
UpperCAmelCase = getLogger(__name__)
def lowerCamelCase (a_ :List[List]) -> Tuple:
return list(itertools.chain.from_iterable(a_))
def lowerCamelCase (a_ :str) -> None:
lowercase :List[str] = get_git_info()
save_json(a_ , os.path.join(a_ , '''git_log.json'''))
def lowerCamelCase (a_ :Optional[int] , a_ :Optional[int] , a_ :Optional[Any]=4 , **a_ :Optional[Any]) -> str:
with open(a_ , '''w''') as f:
json.dump(a_ , a_ , indent=a_ , **a_)
def lowerCamelCase (a_ :Dict) -> Union[str, Any]:
with open(a_) as f:
return json.load(a_)
def lowerCamelCase () -> List[str]:
lowercase :Dict = git.Repo(search_parent_directories=a_)
lowercase :int = {
'''repo_id''': str(a_),
'''repo_sha''': str(repo.head.object.hexsha),
'''repo_branch''': str(repo.active_branch),
'''hostname''': str(socket.gethostname()),
}
return repo_infos
def lowerCamelCase (a_ :Callable , a_ :Iterable) -> List:
return list(map(a_ , a_))
def lowerCamelCase (a_ :Optional[Any] , a_ :str) -> Any:
with open(a_ , '''wb''') as f:
return pickle.dump(a_ , a_)
def lowerCamelCase (a_ :List[str]) -> List[str]:
def remove_articles(a_ :Union[str, Any]):
return re.sub(R'''\b(a|an|the)\b''' , ''' ''' , a_)
def white_space_fix(a_ :Tuple):
return " ".join(text.split())
def remove_punc(a_ :int):
lowercase :List[Any] = set(string.punctuation)
return "".join(ch for ch in text if ch not in exclude)
def lower(a_ :int):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(a_))))
def lowerCamelCase (a_ :List[str] , a_ :Any) -> List[str]:
lowercase :Dict = normalize_answer(a_).split()
lowercase :int = normalize_answer(a_).split()
lowercase :List[Any] = Counter(a_) & Counter(a_)
lowercase :Optional[int] = sum(common.values())
if num_same == 0:
return 0
lowercase :str = 1.0 * num_same / len(a_)
lowercase :Tuple = 1.0 * num_same / len(a_)
lowercase :Tuple = (2 * precision * recall) / (precision + recall)
return fa
def lowerCamelCase (a_ :Tuple , a_ :Optional[Any]) -> List[Any]:
return normalize_answer(a_) == normalize_answer(a_)
def lowerCamelCase (a_ :List[str] , a_ :List[str]) -> Dict:
assert len(a_) == len(a_)
lowercase :Any = 0
for hypo, pred in zip(a_ , a_):
em += exact_match_score(a_ , a_)
if len(a_) > 0:
em /= len(a_)
return {"em": em}
def lowerCamelCase (a_ :Union[str, Any]) -> Optional[Any]:
return model_prefix.startswith('''rag''')
def lowerCamelCase (a_ :List[str] , a_ :Tuple , a_ :List[str]) -> Any:
lowercase :List[str] = {p: p for p in extra_params}
# T5 models don't have `dropout` param, they have `dropout_rate` instead
lowercase :str = '''dropout_rate'''
for p in extra_params:
if getattr(a_ , a_ , a_):
if not hasattr(a_ , a_) and not hasattr(a_ , equivalent_param[p]):
logger.info('''config doesn\'t have a `{}` attribute'''.format(a_))
delattr(a_ , a_)
continue
lowercase :List[str] = p if hasattr(a_ , a_) else equivalent_param[p]
setattr(a_ , a_ , getattr(a_ , a_))
delattr(a_ , a_)
return hparams, config
| 677 | 1 |
"""simple docstring"""
from collections import UserDict
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if is_tf_available():
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
UpperCAmelCase = logging.get_logger(__name__)
@add_end_docstrings(SCREAMING_SNAKE_CASE__)
class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__):
def __init__( self : int , **__UpperCamelCase : Dict ) -> Union[str, Any]:
super().__init__(**snake_case__ )
requires_backends(self , '''vision''' )
self.check_model_type(
TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
if self.framework == '''tf'''
else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING )
def __call__( self : str , __UpperCamelCase : int , **__UpperCamelCase : Any ) -> List[str]:
return super().__call__(snake_case__ , **snake_case__ )
def _UpperCamelCase ( self : List[str] , **__UpperCamelCase : Any ) -> Optional[int]:
_UpperCamelCase = {}
if "candidate_labels" in kwargs:
_UpperCamelCase = kwargs["candidate_labels"]
if "hypothesis_template" in kwargs:
_UpperCamelCase = kwargs["hypothesis_template"]
return preprocess_params, {}, {}
def _UpperCamelCase ( self : List[Any] , __UpperCamelCase : int , __UpperCamelCase : int=None , __UpperCamelCase : List[str]="This is a photo of {}." ) -> Optional[int]:
_UpperCamelCase = load_image(snake_case__ )
_UpperCamelCase = self.image_processor(images=[image] , return_tensors=self.framework )
_UpperCamelCase = candidate_labels
_UpperCamelCase = [hypothesis_template.format(snake_case__ ) for x in candidate_labels]
_UpperCamelCase = self.tokenizer(snake_case__ , return_tensors=self.framework , padding=snake_case__ )
_UpperCamelCase = [text_inputs]
return inputs
def _UpperCamelCase ( self : Any , __UpperCamelCase : List[str] ) -> Optional[Any]:
_UpperCamelCase = model_inputs.pop('''candidate_labels''' )
_UpperCamelCase = model_inputs.pop('''text_inputs''' )
if isinstance(text_inputs[0] , snake_case__ ):
_UpperCamelCase = text_inputs[0]
else:
# Batching case.
_UpperCamelCase = text_inputs[0][0]
_UpperCamelCase = self.model(**snake_case__ , **snake_case__ )
_UpperCamelCase = {
"candidate_labels": candidate_labels,
"logits": outputs.logits_per_image,
}
return model_outputs
def _UpperCamelCase ( self : Dict , __UpperCamelCase : str ) -> Optional[Any]:
_UpperCamelCase = model_outputs.pop('''candidate_labels''' )
_UpperCamelCase = model_outputs["logits"][0]
if self.framework == "pt":
_UpperCamelCase = logits.softmax(dim=-1 ).squeeze(-1 )
_UpperCamelCase = probs.tolist()
if not isinstance(snake_case__ , snake_case__ ):
_UpperCamelCase = [scores]
elif self.framework == "tf":
_UpperCamelCase = stable_softmax(snake_case__ , axis=-1 )
_UpperCamelCase = probs.numpy().tolist()
else:
raise ValueError(F'''Unsupported framework: {self.framework}''' )
_UpperCamelCase = [
{"score": score, "label": candidate_label}
for score, candidate_label in sorted(zip(snake_case__ , snake_case__ ) , key=lambda __UpperCamelCase : -x[0] )
]
return result
| 719 | """simple docstring"""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer
UpperCAmelCase = logging.get_logger(__name__)
UpperCAmelCase = {"""vocab_file""": """vocab.txt"""}
UpperCAmelCase = {
"""vocab_file""": {
"""YituTech/conv-bert-base""": """https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt""",
"""YituTech/conv-bert-medium-small""": (
"""https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt"""
),
"""YituTech/conv-bert-small""": """https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt""",
}
}
UpperCAmelCase = {
"""YituTech/conv-bert-base""": 512,
"""YituTech/conv-bert-medium-small""": 512,
"""YituTech/conv-bert-small""": 512,
}
UpperCAmelCase = {
"""YituTech/conv-bert-base""": {"""do_lower_case""": True},
"""YituTech/conv-bert-medium-small""": {"""do_lower_case""": True},
"""YituTech/conv-bert-small""": {"""do_lower_case""": True},
}
class UpperCAmelCase_ ( _lowercase):
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = PRETRAINED_VOCAB_FILES_MAP
snake_case__ = PRETRAINED_INIT_CONFIGURATION
snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = ConvBertTokenizer
def __init__( self : Union[str, Any] , __UpperCamelCase : Dict=None , __UpperCamelCase : Dict=None , __UpperCamelCase : List[str]=True , __UpperCamelCase : Optional[int]="[UNK]" , __UpperCamelCase : Tuple="[SEP]" , __UpperCamelCase : Tuple="[PAD]" , __UpperCamelCase : Tuple="[CLS]" , __UpperCamelCase : Any="[MASK]" , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : List[Any]=None , **__UpperCamelCase : Optional[Any] , ) -> Any:
super().__init__(
__UpperCamelCase , tokenizer_file=__UpperCamelCase , do_lower_case=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , pad_token=__UpperCamelCase , cls_token=__UpperCamelCase , mask_token=__UpperCamelCase , tokenize_chinese_chars=__UpperCamelCase , strip_accents=__UpperCamelCase , **__UpperCamelCase , )
_UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('''lowercase''' , __UpperCamelCase ) != do_lower_case
or normalizer_state.get('''strip_accents''' , __UpperCamelCase ) != strip_accents
or normalizer_state.get('''handle_chinese_chars''' , __UpperCamelCase ) != tokenize_chinese_chars
):
_UpperCamelCase = getattr(__UpperCamelCase , normalizer_state.pop('''type''' ) )
_UpperCamelCase = do_lower_case
_UpperCamelCase = strip_accents
_UpperCamelCase = tokenize_chinese_chars
_UpperCamelCase = normalizer_class(**__UpperCamelCase )
_UpperCamelCase = do_lower_case
def _UpperCamelCase ( self : Tuple , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : Any=None ) -> str:
_UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def _UpperCamelCase ( self : List[str] , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None ) -> List[int]:
_UpperCamelCase = [self.sep_token_id]
_UpperCamelCase = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def _UpperCamelCase ( self : str , __UpperCamelCase : str , __UpperCamelCase : Optional[str] = None ) -> Tuple[str]:
_UpperCamelCase = self._tokenizer.model.save(__UpperCamelCase , name=__UpperCamelCase )
return tuple(__UpperCamelCase )
| 342 | 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
__UpperCamelCase : Tuple = logging.get_logger(__name__)
class a ( a__ ):
snake_case__ = ['''input_features''', '''is_longer''']
def __init__( self , _snake_case=64 , _snake_case=4_80_00 , _snake_case=4_80 , _snake_case=10 , _snake_case=10_24 , _snake_case=0.0 , _snake_case=False , _snake_case = 0 , _snake_case = 1_40_00 , _snake_case = None , _snake_case = "fusion" , _snake_case = "repeatpad" , **_snake_case , ):
"""simple docstring"""
super().__init__(
feature_size=_snake_case , sampling_rate=_snake_case , padding_value=_snake_case , return_attention_mask=_snake_case , **_snake_case , )
lowerCAmelCase = top_db
lowerCAmelCase = truncation
lowerCAmelCase = padding
lowerCAmelCase = fft_window_size
lowerCAmelCase = (fft_window_size >> 1) + 1
lowerCAmelCase = hop_length
lowerCAmelCase = max_length_s
lowerCAmelCase = max_length_s * sampling_rate
lowerCAmelCase = sampling_rate
lowerCAmelCase = frequency_min
lowerCAmelCase = frequency_max
lowerCAmelCase = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=_snake_case , min_frequency=_snake_case , max_frequency=_snake_case , sampling_rate=_snake_case , norm=_snake_case , mel_scale='htk' , )
lowerCAmelCase = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=_snake_case , min_frequency=_snake_case , max_frequency=_snake_case , sampling_rate=_snake_case , norm='slaney' , mel_scale='slaney' , )
def UpperCamelCase__ ( self ):
"""simple docstring"""
lowerCAmelCase = copy.deepcopy(self.__dict__ )
lowerCAmelCase = 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 UpperCamelCase__ ( self , _snake_case , _snake_case = None ):
"""simple docstring"""
lowerCAmelCase = spectrogram(
_snake_case , window_function(self.fft_window_size , 'hann' ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=_snake_case , log_mel='dB' , )
return log_mel_spectrogram.T
def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case ):
"""simple docstring"""
lowerCAmelCase = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 )
if len(ranges[1] ) == 0:
# if the audio is too short, we just use the first chunk
lowerCAmelCase = [0]
if len(ranges[2] ) == 0:
# if the audio is too short, we just use the first chunk
lowerCAmelCase = [0]
# randomly choose index for each part
lowerCAmelCase = np.random.choice(ranges[0] )
lowerCAmelCase = np.random.choice(ranges[1] )
lowerCAmelCase = np.random.choice(ranges[2] )
lowerCAmelCase = mel[idx_front : idx_front + chunk_frames, :]
lowerCAmelCase = mel[idx_middle : idx_middle + chunk_frames, :]
lowerCAmelCase = mel[idx_back : idx_back + chunk_frames, :]
lowerCAmelCase = torch.tensor(mel[None, None, :] )
lowerCAmelCase = torch.nn.functional.interpolate(
_snake_case , size=[chunk_frames, 64] , mode='bilinear' , align_corners=_snake_case )
lowerCAmelCase = mel_shrink[0][0].numpy()
lowerCAmelCase = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 )
return mel_fusion
def UpperCamelCase__ ( self , _snake_case , _snake_case , _snake_case , _snake_case ):
"""simple docstring"""
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
lowerCAmelCase = True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
lowerCAmelCase = len(_snake_case ) - max_length
lowerCAmelCase = np.random.randint(0 , overflow + 1 )
lowerCAmelCase = waveform[idx : idx + max_length]
lowerCAmelCase = self._np_extract_fbank_features(_snake_case , self.mel_filters_slaney )[None, :]
elif truncation == "fusion":
lowerCAmelCase = self._np_extract_fbank_features(_snake_case , self.mel_filters )
lowerCAmelCase = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
lowerCAmelCase = mel.shape[0]
if chunk_frames == total_frames:
# there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
# In this case, we just use the whole audio.
lowerCAmelCase = np.stack([mel, mel, mel, mel] , axis=0 )
lowerCAmelCase = False
else:
lowerCAmelCase = self._random_mel_fusion(_snake_case , _snake_case , _snake_case )
lowerCAmelCase = True
else:
raise NotImplementedError(F'data_truncating {truncation} not implemented' )
else:
lowerCAmelCase = False
# only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
if waveform.shape[0] < max_length:
if padding == "repeat":
lowerCAmelCase = int(max_length / len(_snake_case ) )
lowerCAmelCase = np.stack(np.tile(_snake_case , n_repeat + 1 ) )[:max_length]
if padding == "repeatpad":
lowerCAmelCase = int(max_length / len(_snake_case ) )
lowerCAmelCase = np.stack(np.tile(_snake_case , _snake_case ) )
lowerCAmelCase = np.pad(_snake_case , (0, max_length - waveform.shape[0]) , mode='constant' , constant_values=0 )
if truncation == "fusion":
lowerCAmelCase = self._np_extract_fbank_features(_snake_case , self.mel_filters )
lowerCAmelCase = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 )
else:
lowerCAmelCase = self._np_extract_fbank_features(_snake_case , self.mel_filters_slaney )[None, :]
return input_mel, longer
def __call__( self , _snake_case , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , **_snake_case , ):
"""simple docstring"""
lowerCAmelCase = truncation if truncation is not None else self.truncation
lowerCAmelCase = padding if padding else self.padding
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a'
F' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input'
F' was sampled with {self.sampling_rate} and not {sampling_rate}.' )
else:
logger.warning(
'It is strongly recommended to pass the `sampling_rate` argument to this function. '
'Failing to do so can result in silent errors that might be hard to debug.' )
lowerCAmelCase = isinstance(_snake_case , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(F'Only mono-channel audio is supported for input to {self}' )
lowerCAmelCase = is_batched_numpy or (
isinstance(_snake_case , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
lowerCAmelCase = [np.asarray(_snake_case , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(_snake_case , np.ndarray ):
lowerCAmelCase = np.asarray(_snake_case , dtype=np.floataa )
elif isinstance(_snake_case , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
lowerCAmelCase = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
lowerCAmelCase = [np.asarray(_snake_case )]
# convert to mel spectrogram, truncate and pad if needed.
lowerCAmelCase = [
self._get_input_mel(_snake_case , max_length if max_length else self.nb_max_samples , _snake_case , _snake_case )
for waveform in raw_speech
]
lowerCAmelCase = []
lowerCAmelCase = []
for mel, longer in padded_inputs:
input_mel.append(_snake_case )
is_longer.append(_snake_case )
if truncation == "fusion" and sum(_snake_case ) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
lowerCAmelCase = np.random.randint(0 , len(_snake_case ) )
lowerCAmelCase = True
if isinstance(input_mel[0] , _snake_case ):
lowerCAmelCase = [np.asarray(_snake_case , dtype=np.floataa ) for feature in input_mel]
# is_longer is a list of bool
lowerCAmelCase = [[longer] for longer in is_longer]
lowerCAmelCase = {'input_features': input_mel, 'is_longer': is_longer}
lowerCAmelCase = BatchFeature(_snake_case )
if return_tensors is not None:
lowerCAmelCase = input_features.convert_to_tensors(_snake_case )
return input_features
| 4 |
"""simple docstring"""
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 a ( a__ , a__ , unittest.TestCase ):
snake_case__ = IFInpaintingPipeline
snake_case__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''}
snake_case__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
snake_case__ = PipelineTesterMixin.required_optional_params - {'''latents'''}
def UpperCamelCase__ ( self ):
"""simple docstring"""
return self._get_dummy_components()
def UpperCamelCase__ ( self , _snake_case , _snake_case=0 ):
"""simple docstring"""
if str(_snake_case ).startswith('mps' ):
lowerCAmelCase = torch.manual_seed(_snake_case )
else:
lowerCAmelCase = torch.Generator(device=_snake_case ).manual_seed(_snake_case )
lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(_snake_case ) ).to(_snake_case )
lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(_snake_case ) ).to(_snake_case )
lowerCAmelCase = {
'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 UpperCamelCase__ ( self ):
"""simple docstring"""
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )
def UpperCamelCase__ ( self ):
"""simple docstring"""
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' )
def UpperCamelCase__ ( self ):
"""simple docstring"""
super().test_save_load_floataa(expected_max_diff=1E-1 )
def UpperCamelCase__ ( self ):
"""simple docstring"""
self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )
def UpperCamelCase__ ( self ):
"""simple docstring"""
self._test_save_load_local()
def UpperCamelCase__ ( self ):
"""simple docstring"""
self._test_inference_batch_single_identical(
expected_max_diff=1E-2 , )
| 4 | 1 |
"""simple docstring"""
from collections.abc import Iterator, MutableMapping
from dataclasses import dataclass
from typing import Generic, TypeVar
UpperCamelCase__ = TypeVar('''KEY''')
UpperCamelCase__ = TypeVar('''VAL''')
@dataclass(frozen=UpperCamelCase_ , slots=UpperCamelCase_ )
class a__ ( Generic[KEY, VAL] ):
snake_case__ = 4_2
snake_case__ = 4_2
class a__ ( _Item ):
def __init__( self : Dict) -> None:
"""simple docstring"""
super().__init__(__a ,__a)
def __bool__( self : Any) -> bool:
"""simple docstring"""
return False
UpperCamelCase__ = _DeletedItem()
class a__ ( MutableMapping[KEY, VAL] ):
def __init__( self : Union[str, Any] ,a__ : List[str] = 8 ,a__ : int = 0.75) -> None:
"""simple docstring"""
_lowerCAmelCase:Any = initial_block_size
_lowerCAmelCase:list[_Item | None] = [None] * initial_block_size
assert 0.0 < capacity_factor < 1.0
_lowerCAmelCase:List[str] = capacity_factor
_lowerCAmelCase:Dict = 0
def __UpperCamelCase ( self : Optional[Any] ,a__ : List[str]) -> int:
"""simple docstring"""
return hash(__a) % len(self._buckets)
def __UpperCamelCase ( self : str ,a__ : Tuple) -> int:
"""simple docstring"""
return (ind + 1) % len(self._buckets)
def __UpperCamelCase ( self : int ,a__ : Optional[Any] ,a__ : List[Any] ,a__ : str) -> bool:
"""simple docstring"""
_lowerCAmelCase:List[str] = self._buckets[ind]
if not stored:
_lowerCAmelCase:Optional[Any] = _Item(__a ,__a)
self._len += 1
return True
elif stored.key == key:
_lowerCAmelCase:Dict = _Item(__a ,__a)
return True
else:
return False
def __UpperCamelCase ( self : int) -> bool:
"""simple docstring"""
_lowerCAmelCase:str = len(self._buckets) * self._capacity_factor
return len(self) >= int(__a)
def __UpperCamelCase ( self : List[str]) -> bool:
"""simple docstring"""
if len(self._buckets) <= self._initial_block_size:
return False
_lowerCAmelCase:str = len(self._buckets) * self._capacity_factor / 2
return len(self) < limit
def __UpperCamelCase ( self : int ,a__ : str) -> None:
"""simple docstring"""
_lowerCAmelCase:Optional[int] = self._buckets
_lowerCAmelCase:Dict = [None] * new_size
_lowerCAmelCase:Optional[Any] = 0
for item in old_buckets:
if item:
self._add_item(item.key ,item.val)
def __UpperCamelCase ( self : Tuple) -> None:
"""simple docstring"""
self._resize(len(self._buckets) * 2)
def __UpperCamelCase ( self : str) -> None:
"""simple docstring"""
self._resize(len(self._buckets) // 2)
def __UpperCamelCase ( self : int ,a__ : Tuple) -> Iterator[int]:
"""simple docstring"""
_lowerCAmelCase:List[Any] = self._get_bucket_index(__a)
for _ in range(len(self._buckets)):
yield ind
_lowerCAmelCase:Union[str, Any] = self._get_next_ind(__a)
def __UpperCamelCase ( self : List[str] ,a__ : str ,a__ : Optional[int]) -> None:
"""simple docstring"""
for ind in self._iterate_buckets(__a):
if self._try_set(__a ,__a ,__a):
break
def __setitem__( self : Dict ,a__ : Union[str, Any] ,a__ : str) -> None:
"""simple docstring"""
if self._is_full():
self._size_up()
self._add_item(__a ,__a)
def __delitem__( self : str ,a__ : Optional[Any]) -> None:
"""simple docstring"""
for ind in self._iterate_buckets(__a):
_lowerCAmelCase:Optional[int] = self._buckets[ind]
if item is None:
raise KeyError(__a)
if item is _deleted:
continue
if item.key == key:
_lowerCAmelCase:int = _deleted
self._len -= 1
break
if self._is_sparse():
self._size_down()
def __getitem__( self : Union[str, Any] ,a__ : List[Any]) -> VAL:
"""simple docstring"""
for ind in self._iterate_buckets(__a):
_lowerCAmelCase:Union[str, Any] = self._buckets[ind]
if item is None:
break
if item is _deleted:
continue
if item.key == key:
return item.val
raise KeyError(__a)
def __len__( self : Dict) -> int:
"""simple docstring"""
return self._len
def __iter__( self : List[str]) -> Iterator[KEY]:
"""simple docstring"""
yield from (item.key for item in self._buckets if item)
def __repr__( self : Optional[Any]) -> str:
"""simple docstring"""
_lowerCAmelCase:str = ' ,'.join(
F'{item.key}: {item.val}' for item in self._buckets if item)
return F'HashMap({val_string})'
| 717 |
"""simple docstring"""
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch
import math
from typing import Union
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import randn_tensor
from .scheduling_utils import SchedulerMixin
class a__ ( UpperCamelCase_ , UpperCamelCase_ ):
snake_case__ = 1
@register_to_config
def __init__( self : Union[str, Any] ,a__ : List[str]=2000 ,a__ : Tuple=0.1 ,a__ : Union[str, Any]=20 ,a__ : int=1E-3) -> Any:
"""simple docstring"""
_lowerCAmelCase:Optional[Any] = None
_lowerCAmelCase:List[Any] = None
_lowerCAmelCase:Dict = None
def __UpperCamelCase ( self : int ,a__ : Any ,a__ : Union[str, torch.device] = None) -> List[str]:
"""simple docstring"""
_lowerCAmelCase:str = torch.linspace(1 ,self.config.sampling_eps ,a__ ,device=a__)
def __UpperCamelCase ( self : Union[str, Any] ,a__ : str ,a__ : List[Any] ,a__ : Union[str, Any] ,a__ : Any=None) -> Tuple:
"""simple docstring"""
if self.timesteps is None:
raise ValueError(
'''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''')
# TODO(Patrick) better comments + non-PyTorch
# postprocess model score
_lowerCAmelCase:Union[str, Any] = (
-0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min
)
_lowerCAmelCase:Dict = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff))
_lowerCAmelCase:Optional[Any] = std.flatten()
while len(std.shape) < len(score.shape):
_lowerCAmelCase:str = std.unsqueeze(-1)
_lowerCAmelCase:Optional[int] = -score / std
# compute
_lowerCAmelCase:Optional[Any] = -1.0 / len(self.timesteps)
_lowerCAmelCase:Union[str, Any] = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min)
_lowerCAmelCase:Any = beta_t.flatten()
while len(beta_t.shape) < len(x.shape):
_lowerCAmelCase:List[str] = beta_t.unsqueeze(-1)
_lowerCAmelCase:Tuple = -0.5 * beta_t * x
_lowerCAmelCase:str = torch.sqrt(a__)
_lowerCAmelCase:Union[str, Any] = drift - diffusion**2 * score
_lowerCAmelCase:List[str] = x + drift * dt
# add noise
_lowerCAmelCase:Any = randn_tensor(x.shape ,layout=x.layout ,generator=a__ ,device=x.device ,dtype=x.dtype)
_lowerCAmelCase:Union[str, Any] = x_mean + diffusion * math.sqrt(-dt) * noise
return x, x_mean
def __len__( self : int) -> Tuple:
"""simple docstring"""
return self.config.num_train_timesteps
| 439 | 0 |
'''simple docstring'''
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MgpstrProcessor, ViTImageProcessor
@require_torch
@require_vision
class UpperCAmelCase__ ( unittest.TestCase ):
"""simple docstring"""
__UpperCAmelCase : Dict = ViTImageProcessor if is_vision_available() else None
@property
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def __lowercase ( self : List[str] ):
'''simple docstring'''
_a : Any = (3, 32, 128)
_a : List[Any] = tempfile.mkdtemp()
# fmt: off
_a : int = ['[GO]', '[s]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# fmt: on
_a : Tuple = dict(zip(_a ,range(len(_a ) ) ) )
_a : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] )
with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp:
fp.write(json.dumps(_a ) + '\n' )
_a : Optional[int] = {
'do_normalize': False,
'do_resize': True,
'image_processor_type': 'ViTImageProcessor',
'resample': 3,
'size': {'height': 32, 'width': 128},
}
_a : List[str] = os.path.join(self.tmpdirname ,_a )
with open(self.image_processor_file ,'w' ,encoding='utf-8' ) as fp:
json.dump(_a ,_a )
def __lowercase ( self : List[Any] ,**_a : Union[str, Any] ):
'''simple docstring'''
return MgpstrTokenizer.from_pretrained(self.tmpdirname ,**_a )
def __lowercase ( self : str ,**_a : Optional[int] ):
'''simple docstring'''
return ViTImageProcessor.from_pretrained(self.tmpdirname ,**_a )
def __lowercase ( self : List[str] ):
'''simple docstring'''
shutil.rmtree(self.tmpdirname )
def __lowercase ( self : List[str] ):
'''simple docstring'''
_a : List[Any] = np.random.randint(255 ,size=(3, 30, 400) ,dtype=np.uinta )
_a : str = Image.fromarray(np.moveaxis(_a ,0 ,-1 ) )
return image_input
def __lowercase ( self : str ):
'''simple docstring'''
_a : Tuple = self.get_tokenizer()
_a : Tuple = self.get_image_processor()
_a : Dict = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
processor.save_pretrained(self.tmpdirname )
_a : Any = MgpstrProcessor.from_pretrained(self.tmpdirname ,use_fast=_a )
self.assertEqual(processor.char_tokenizer.get_vocab() ,tokenizer.get_vocab() )
self.assertIsInstance(processor.char_tokenizer ,_a )
self.assertEqual(processor.image_processor.to_json_string() ,image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor ,_a )
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
_a : int = self.get_tokenizer()
_a : Optional[int] = self.get_image_processor()
_a : List[Any] = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
processor.save_pretrained(self.tmpdirname )
_a : Any = self.get_tokenizer(bos_token='(BOS)' ,eos_token='(EOS)' )
_a : Optional[int] = self.get_image_processor(do_normalize=_a ,padding_value=1.0 )
_a : List[str] = MgpstrProcessor.from_pretrained(
self.tmpdirname ,bos_token='(BOS)' ,eos_token='(EOS)' ,do_normalize=_a ,padding_value=1.0 )
self.assertEqual(processor.char_tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.char_tokenizer ,_a )
self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor ,_a )
def __lowercase ( self : Tuple ):
'''simple docstring'''
_a : Optional[Any] = self.get_image_processor()
_a : Any = self.get_tokenizer()
_a : List[Any] = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
_a : List[str] = self.prepare_image_inputs()
_a : Tuple = image_processor(_a ,return_tensors='np' )
_a : Tuple = processor(images=_a ,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 __lowercase ( self : List[Any] ):
'''simple docstring'''
_a : Dict = self.get_image_processor()
_a : int = self.get_tokenizer()
_a : List[Any] = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
_a : str = 'test'
_a : int = processor(text=_a )
_a : List[Any] = tokenizer(_a )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] ,encoded_processor[key] )
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
_a : List[str] = self.get_image_processor()
_a : int = self.get_tokenizer()
_a : int = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
_a : Optional[Any] = 'test'
_a : str = self.prepare_image_inputs()
_a : Dict = processor(text=_a ,images=_a )
self.assertListEqual(list(inputs.keys() ) ,['pixel_values', 'labels'] )
# test if it raises when no input is passed
with pytest.raises(_a ):
processor()
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
_a : Tuple = self.get_image_processor()
_a : Any = self.get_tokenizer()
_a : Tuple = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
_a : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]]
_a : str = processor.char_decode(_a )
_a : List[Any] = tokenizer.batch_decode(_a )
_a : Optional[int] = [seq.replace(' ' ,'' ) for seq in decoded_tok]
self.assertListEqual(_a ,_a )
def __lowercase ( self : Union[str, Any] ):
'''simple docstring'''
_a : Union[str, Any] = self.get_image_processor()
_a : List[Any] = self.get_tokenizer()
_a : List[Any] = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
_a : Optional[int] = None
_a : List[Any] = self.prepare_image_inputs()
_a : Dict = processor(text=_a ,images=_a )
self.assertListEqual(list(inputs.keys() ) ,processor.model_input_names )
def __lowercase ( self : Optional[int] ):
'''simple docstring'''
_a : Tuple = self.get_image_processor()
_a : Dict = self.get_tokenizer()
_a : Union[str, Any] = MgpstrProcessor(tokenizer=_a ,image_processor=_a )
_a : Optional[Any] = torch.randn(1 ,27 ,38 )
_a : List[str] = torch.randn(1 ,27 ,5_0257 )
_a : int = torch.randn(1 ,27 ,3_0522 )
_a : int = processor.batch_decode([char_input, bpe_input, wp_input] )
self.assertListEqual(list(results.keys() ) ,['generated_text', 'scores', 'char_preds', 'bpe_preds', 'wp_preds'] )
| 229 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__lowerCAmelCase = {
"""configuration_clap""": [
"""CLAP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ClapAudioConfig""",
"""ClapConfig""",
"""ClapTextConfig""",
],
"""processing_clap""": ["""ClapProcessor"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase = [
"""CLAP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ClapModel""",
"""ClapPreTrainedModel""",
"""ClapTextModel""",
"""ClapTextModelWithProjection""",
"""ClapAudioModel""",
"""ClapAudioModelWithProjection""",
]
__lowerCAmelCase = ["""ClapFeatureExtractor"""]
if TYPE_CHECKING:
from .configuration_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioConfig,
ClapConfig,
ClapTextConfig,
)
from .processing_clap import ClapProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clap import ClapFeatureExtractor
from .modeling_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioModel,
ClapAudioModelWithProjection,
ClapModel,
ClapPreTrainedModel,
ClapTextModel,
ClapTextModelWithProjection,
)
else:
import sys
__lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 229 | 1 |
"""simple docstring"""
import os
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
'''simple docstring'''
def snake_case ( self : Optional[int] )-> Dict:
lowerCamelCase__ : List[str] =tempfile.mkdtemp()
lowerCamelCase__ : List[str] =5
# Realm tok
lowerCamelCase__ : Optional[int] =[
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''test''',
'''question''',
'''this''',
'''is''',
'''the''',
'''first''',
'''second''',
'''third''',
'''fourth''',
'''fifth''',
'''record''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
lowerCamelCase__ : Optional[int] =os.path.join(self.tmpdirname, '''realm_tokenizer''' )
os.makedirs(lowerCamelCase, exist_ok=lowerCamelCase )
lowerCamelCase__ : Dict =os.path.join(lowerCamelCase, VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file, '''w''', encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
lowerCamelCase__ : Dict =os.path.join(self.tmpdirname, '''realm_block_records''' )
os.makedirs(lowerCamelCase, exist_ok=lowerCamelCase )
def snake_case ( self : str )-> RealmTokenizer:
return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname, '''realm_tokenizer''' ) )
def snake_case ( self : str )-> List[Any]:
shutil.rmtree(self.tmpdirname )
def snake_case ( self : Optional[int] )-> Union[str, Any]:
lowerCamelCase__ : List[str] =RealmConfig(num_block_records=self.num_block_records )
return config
def snake_case ( self : Tuple )-> int:
lowerCamelCase__ : Union[str, Any] =Dataset.from_dict(
{
'''id''': ['''0''', '''1'''],
'''question''': ['''foo''', '''bar'''],
'''answers''': [['''Foo''', '''Bar'''], ['''Bar''']],
} )
return dataset
def snake_case ( self : Dict )-> Tuple:
lowerCamelCase__ : Any =np.array(
[
b'''This is the first record''',
b'''This is the second record''',
b'''This is the third record''',
b'''This is the fourth record''',
b'''This is the fifth record''',
b'''This is a longer longer longer record''',
], dtype=lowerCamelCase, )
return block_records
def snake_case ( self : Optional[Any] )-> Any:
lowerCamelCase__ : List[str] =RealmRetriever(
block_records=self.get_dummy_block_records(), tokenizer=self.get_tokenizer(), )
return retriever
def snake_case ( self : List[str] )-> Optional[Any]:
lowerCamelCase__ : Dict =self.get_config()
lowerCamelCase__ : List[Any] =self.get_dummy_retriever()
lowerCamelCase__ : Any =retriever.tokenizer
lowerCamelCase__ : Union[str, Any] =np.array([0, 3], dtype='''long''' )
lowerCamelCase__ : Optional[int] =tokenizer(['''Test question'''] ).input_ids
lowerCamelCase__ : List[str] =tokenizer(
['''the fourth'''], add_special_tokens=lowerCamelCase, return_token_type_ids=lowerCamelCase, return_attention_mask=lowerCamelCase, ).input_ids
lowerCamelCase__ : Dict =config.reader_seq_len
lowerCamelCase__ : Tuple =retriever(
lowerCamelCase, lowerCamelCase, answer_ids=lowerCamelCase, max_length=lowerCamelCase, return_tensors='''np''' )
self.assertEqual(len(lowerCamelCase ), 2 )
self.assertEqual(len(lowerCamelCase ), 2 )
self.assertEqual(len(lowerCamelCase ), 2 )
self.assertEqual(concat_inputs.input_ids.shape, (2, 10) )
self.assertEqual(concat_inputs.attention_mask.shape, (2, 10) )
self.assertEqual(concat_inputs.token_type_ids.shape, (2, 10) )
self.assertEqual(concat_inputs.special_tokens_mask.shape, (2, 10) )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ), ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''], )
self.assertEqual(
tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ), ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''], )
def snake_case ( self : Optional[Any] )-> List[Any]:
lowerCamelCase__ : Any =self.get_config()
lowerCamelCase__ : Dict =self.get_dummy_retriever()
lowerCamelCase__ : Any =retriever.tokenizer
lowerCamelCase__ : Optional[Any] =np.array([0, 3, 5], dtype='''long''' )
lowerCamelCase__ : int =tokenizer(['''Test question'''] ).input_ids
lowerCamelCase__ : Optional[Any] =tokenizer(
['''the fourth''', '''longer longer'''], add_special_tokens=lowerCamelCase, return_token_type_ids=lowerCamelCase, return_attention_mask=lowerCamelCase, ).input_ids
lowerCamelCase__ : Union[str, Any] =config.reader_seq_len
lowerCamelCase__ : List[Any] =retriever(
lowerCamelCase, lowerCamelCase, answer_ids=lowerCamelCase, max_length=lowerCamelCase, return_tensors='''np''' )
self.assertEqual([False, True, True], lowerCamelCase )
self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]], lowerCamelCase )
self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]], lowerCamelCase )
def snake_case ( self : int )-> Tuple:
lowerCamelCase__ : List[str] =self.get_dummy_retriever()
retriever.save_pretrained(os.path.join(self.tmpdirname, '''realm_block_records''' ) )
# Test local path
lowerCamelCase__ : Any =retriever.from_pretrained(os.path.join(self.tmpdirname, '''realm_block_records''' ) )
self.assertEqual(retriever.block_records[0], b'''This is the first record''' )
# Test mocked remote path
with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download:
lowerCamelCase__ : Optional[int] =os.path.join(
os.path.join(self.tmpdirname, '''realm_block_records''' ), _REALM_BLOCK_RECORDS_FILENAME )
lowerCamelCase__ : Dict =RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' )
self.assertEqual(retriever.block_records[0], b'''This is the first record''' )
| 709 |
"""simple docstring"""
import argparse
from tax import checkpoints
from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM
def snake_case__ ( __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : Tuple ):
"""simple docstring"""
lowerCamelCase__ : Union[str, Any] =AutoConfig.from_pretrained(__lowerCamelCase )
lowerCamelCase__ : Any =FlaxAutoModelForSeqaSeqLM.from_config(config=__lowerCamelCase )
lowerCamelCase__ : Union[str, Any] =checkpoints.load_tax_checkpoint(__lowerCamelCase )
lowerCamelCase__ : Union[str, Any] ='''wi_0''' in tax_model['''target''']['''encoder''']['''layers_0''']['''mlp''']
if config.model_type == "t5":
lowerCamelCase__ : List[str] ='''SelfAttention'''
if config.model_type == "longt5" and config.encoder_attention_type == "local":
lowerCamelCase__ : List[Any] ='''LocalSelfAttention'''
elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
lowerCamelCase__ : Optional[Any] ='''TransientGlobalSelfAttention'''
else:
raise ValueError(
'''Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`'''
''' attribute with a value from [\'local\', \'transient-global].''' )
# Encoder
for layer_index in range(config.num_layers ):
lowerCamelCase__ : List[Any] =f'''layers_{str(__lowerCamelCase )}'''
# Self-Attention
lowerCamelCase__ : List[str] =tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''key''']['''kernel''']
lowerCamelCase__ : Optional[int] =tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''out''']['''kernel''']
lowerCamelCase__ : List[str] =tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''query''']['''kernel''']
lowerCamelCase__ : List[Any] =tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''value''']['''kernel''']
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
lowerCamelCase__ : str =tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''T5LayerNorm_0''']['''scale''']
# Layer Normalization
lowerCamelCase__ : List[Any] =tax_model['''target''']['''encoder'''][layer_name]['''pre_attention_layer_norm''']['''scale''']
if split_mlp_wi:
lowerCamelCase__ : Optional[Any] =tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel''']
lowerCamelCase__ : Dict =tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel''']
else:
lowerCamelCase__ : List[str] =tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi''']['''kernel''']
lowerCamelCase__ : Union[str, Any] =tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wo''']['''kernel''']
# Layer Normalization
lowerCamelCase__ : Tuple =tax_model['''target''']['''encoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale''']
# Assigning
lowerCamelCase__ : str =flax_model.params['''encoder''']['''block'''][str(__lowerCamelCase )]['''layer''']
lowerCamelCase__ : int =tax_attention_key
lowerCamelCase__ : Optional[int] =tax_attention_out
lowerCamelCase__ : List[Any] =tax_attention_query
lowerCamelCase__ : Optional[Any] =tax_attention_value
lowerCamelCase__ : List[str] =tax_attention_layer_norm
# Global input layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
lowerCamelCase__ : Optional[int] =tax_global_layer_norm
if split_mlp_wi:
lowerCamelCase__ : Optional[int] =tax_mlp_wi_a
lowerCamelCase__ : Optional[int] =tax_mlp_wi_a
else:
lowerCamelCase__ : Union[str, Any] =tax_mlp_wi
lowerCamelCase__ : str =tax_mlp_wo
lowerCamelCase__ : Optional[Any] =tax_mlp_layer_norm
lowerCamelCase__ : Optional[int] =flax_model_encoder_layer_block
# Only for layer 0:
lowerCamelCase__ : Union[str, Any] =tax_model['''target''']['''encoder''']['''relpos_bias''']['''rel_embedding'''].T
lowerCamelCase__ : str =tax_encoder_rel_embedding
# Side/global relative position_bias + layer norm
if config.model_type == "longt5" and config.encoder_attention_type == "transient-global":
lowerCamelCase__ : Optional[int] =tax_model['''target''']['''encoder''']['''side_relpos_bias''']['''rel_embedding'''].T
lowerCamelCase__ : Optional[int] =tax_encoder_global_rel_embedding
# Assigning
lowerCamelCase__ : int =tax_model['''target''']['''encoder''']['''encoder_norm''']['''scale''']
lowerCamelCase__ : List[Any] =tax_encoder_norm
# Decoder
for layer_index in range(config.num_layers ):
lowerCamelCase__ : Dict =f'''layers_{str(__lowerCamelCase )}'''
# Self-Attention
lowerCamelCase__ : Dict =tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''key''']['''kernel''']
lowerCamelCase__ : List[Any] =tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''out''']['''kernel''']
lowerCamelCase__ : Optional[int] =tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''query''']['''kernel''']
lowerCamelCase__ : Union[str, Any] =tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''value''']['''kernel''']
# Layer Normalization
lowerCamelCase__ : int =tax_model['''target''']['''decoder'''][layer_name]['''pre_self_attention_layer_norm'''][
'''scale'''
]
# Encoder-Decoder-Attention
lowerCamelCase__ : int =tax_model['''target''']['''decoder'''][layer_name]['''encoder_decoder_attention''']
lowerCamelCase__ : List[Any] =tax_enc_dec_attention_module['''key''']['''kernel''']
lowerCamelCase__ : Any =tax_enc_dec_attention_module['''out''']['''kernel''']
lowerCamelCase__ : Dict =tax_enc_dec_attention_module['''query''']['''kernel''']
lowerCamelCase__ : List[str] =tax_enc_dec_attention_module['''value''']['''kernel''']
# Layer Normalization
lowerCamelCase__ : Dict =tax_model['''target''']['''decoder'''][layer_name]['''pre_cross_attention_layer_norm''']['''scale''']
# MLP
if split_mlp_wi:
lowerCamelCase__ : str =tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel''']
lowerCamelCase__ : Any =tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel''']
else:
lowerCamelCase__ : List[Any] =tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi''']['''kernel''']
lowerCamelCase__ : Optional[Any] =tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wo''']['''kernel''']
# Layer Normalization
lowerCamelCase__ : str =tax_model['''target''']['''decoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale''']
# Assigning
lowerCamelCase__ : str =flax_model.params['''decoder''']['''block'''][str(__lowerCamelCase )]['''layer''']
lowerCamelCase__ : Union[str, Any] =tax_attention_key
lowerCamelCase__ : str =tax_attention_out
lowerCamelCase__ : Optional[int] =tax_attention_query
lowerCamelCase__ : Dict =tax_attention_value
lowerCamelCase__ : List[str] =tax_pre_attention_layer_norm
lowerCamelCase__ : List[Any] =tax_enc_dec_attention_key
lowerCamelCase__ : Any =tax_enc_dec_attention_out
lowerCamelCase__ : Any =tax_enc_dec_attention_query
lowerCamelCase__ : Optional[int] =tax_enc_dec_attention_value
lowerCamelCase__ : Dict =tax_cross_layer_norm
if split_mlp_wi:
lowerCamelCase__ : Tuple =tax_mlp_wi_a
lowerCamelCase__ : int =tax_mlp_wi_a
else:
lowerCamelCase__ : List[Any] =tax_mlp_wi
lowerCamelCase__ : Dict =tax_mlp_wo
lowerCamelCase__ : Tuple =txa_mlp_layer_norm
lowerCamelCase__ : Optional[Any] =flax_model_decoder_layer_block
# Decoder Normalization
lowerCamelCase__ : Dict =tax_model['''target''']['''decoder''']['''decoder_norm''']['''scale''']
lowerCamelCase__ : int =txa_decoder_norm
# Only for layer 0:
lowerCamelCase__ : Tuple =tax_model['''target''']['''decoder''']['''relpos_bias''']['''rel_embedding'''].T
lowerCamelCase__ : Tuple =tax_decoder_rel_embedding
# Token Embeddings
lowerCamelCase__ : Union[str, Any] =tax_model['''target''']['''token_embedder''']['''embedding''']
lowerCamelCase__ : Dict =txa_token_embeddings
# LM Head (only in v1.1 and LongT5 checkpoints)
if "logits_dense" in tax_model["target"]["decoder"]:
lowerCamelCase__ : int =tax_model['''target''']['''decoder''']['''logits_dense''']['''kernel''']
flax_model.save_pretrained(__lowerCamelCase )
print('''T5X Model was sucessfully converted!''' )
if __name__ == "__main__":
_lowercase : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--t5x_checkpoint_path", default=None, type=str, required=True, help="Path the T5X checkpoint."
)
parser.add_argument("--config_name", default=None, type=str, required=True, help="Config name of LongT5/T5 model.")
parser.add_argument(
"--flax_dump_folder_path", default=None, type=str, required=True, help="Path to the output FLAX model."
)
_lowercase : List[Any] = parser.parse_args()
convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
| 625 | 0 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel
if is_vision_available():
from transformers import MaskaFormerImageProcessor
if is_vision_available():
from PIL import Image
class A__ :
"""simple docstring"""
def __init__( self : str , lowerCamelCase__ : str , lowerCamelCase__ : str=2 , lowerCamelCase__ : Dict=True , lowerCamelCase__ : List[str]=False , lowerCamelCase__ : Tuple=10 , lowerCamelCase__ : int=3 , lowerCamelCase__ : Tuple=32 * 8 , lowerCamelCase__ : Union[str, Any]=32 * 8 , lowerCamelCase__ : List[Any]=4 , lowerCamelCase__ : Optional[int]=64 , ):
a__ : List[str] = parent
a__ : List[Any] = batch_size
a__ : Any = is_training
a__ : Optional[Any] = use_auxiliary_loss
a__ : Dict = num_queries
a__ : Any = num_channels
a__ : List[Any] = min_size
a__ : Dict = max_size
a__ : Dict = num_labels
a__ : str = hidden_dim
a__ : int = hidden_dim
def _UpperCamelCase( self : Union[str, Any] ):
a__ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
lowerCamelCase__ )
a__ : List[str] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=lowerCamelCase__ )
a__ : List[str] = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=lowerCamelCase__ ) > 0.5
).float()
a__ : Optional[int] = (torch.rand((self.batch_size, self.num_labels) , device=lowerCamelCase__ ) > 0.5).long()
a__ : Tuple = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def _UpperCamelCase( self : Union[str, Any] ):
a__ : Dict = MaskaFormerConfig(
hidden_size=self.hidden_dim , )
a__ : str = self.num_queries
a__ : Tuple = self.num_labels
a__ : Optional[int] = [1, 1, 1, 1]
a__ : Dict = self.num_channels
a__ : int = 64
a__ : Optional[Any] = 128
a__ : Optional[int] = self.hidden_dim
a__ : Dict = self.hidden_dim
a__ : Optional[Any] = self.hidden_dim
return config
def _UpperCamelCase( self : Optional[Any] ):
a__, a__, a__, a__, a__ : Union[str, Any] = self.prepare_config_and_inputs()
a__ : Dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
return config, inputs_dict
def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : List[Any] ):
a__ : Any = output.encoder_hidden_states
a__ : Optional[Any] = output.pixel_decoder_hidden_states
a__ : str = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(lowerCamelCase__ ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(lowerCamelCase__ ) , len(config.backbone_config.depths ) )
self.parent.assertTrue(len(lowerCamelCase__ ) , config.decoder_layers )
def _UpperCamelCase( self : List[str] , lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[int]=False ):
with torch.no_grad():
a__ : List[str] = MaskaFormerModel(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
a__ : int = model(pixel_values=lowerCamelCase__ , pixel_mask=lowerCamelCase__ )
a__ : List[str] = model(lowerCamelCase__ , output_hidden_states=lowerCamelCase__ )
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(lowerCamelCase__ , lowerCamelCase__ )
def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : int , lowerCamelCase__ : List[str] , lowerCamelCase__ : Dict ):
a__ : str = MaskaFormerForUniversalSegmentation(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
def comm_check_on_output(lowerCamelCase__ : Optional[Any] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
a__ : Tuple = model(pixel_values=lowerCamelCase__ , pixel_mask=lowerCamelCase__ )
a__ : int = model(lowerCamelCase__ )
comm_check_on_output(lowerCamelCase__ )
a__ : Optional[Any] = model(
pixel_values=lowerCamelCase__ , pixel_mask=lowerCamelCase__ , mask_labels=lowerCamelCase__ , class_labels=lowerCamelCase__ )
comm_check_on_output(lowerCamelCase__ )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape , torch.Size([1] ) )
@require_torch
class A__ ( A__ , A__ , unittest.TestCase ):
"""simple docstring"""
_lowercase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
_lowercase = {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}
_lowercase = False
_lowercase = False
_lowercase = False
_lowercase = False
def _UpperCamelCase( self : List[Any] ):
a__ : Dict = MaskaFormerModelTester(self )
a__ : List[str] = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ )
def _UpperCamelCase( self : List[Any] ):
self.config_tester.run_common_tests()
def _UpperCamelCase( self : int ):
a__, a__ : Dict = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskaformer_model(lowerCamelCase__ , **lowerCamelCase__ , output_hidden_states=lowerCamelCase__ )
def _UpperCamelCase( self : List[str] ):
a__ : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowerCamelCase__ )
@unittest.skip(reason="Mask2Former does not use inputs_embeds" )
def _UpperCamelCase( self : str ):
pass
@unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" )
def _UpperCamelCase( self : Optional[Any] ):
pass
@unittest.skip(reason="Mask2Former is not a generative model" )
def _UpperCamelCase( self : Dict ):
pass
@unittest.skip(reason="Mask2Former does not use token embeddings" )
def _UpperCamelCase( self : Union[str, Any] ):
pass
@require_torch_multi_gpu
@unittest.skip(
reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`" )
def _UpperCamelCase( self : Tuple ):
pass
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def _UpperCamelCase( self : int ):
pass
def _UpperCamelCase( self : Optional[int] ):
a__, a__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ : Dict = model_class(lowerCamelCase__ )
a__ : Optional[Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a__ : List[str] = [*signature.parameters.keys()]
a__ : Optional[Any] = ["pixel_values"]
self.assertListEqual(arg_names[:1] , lowerCamelCase__ )
@slow
def _UpperCamelCase( self : Any ):
for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
a__ : Union[str, Any] = MaskaFormerModel.from_pretrained(lowerCamelCase__ )
self.assertIsNotNone(lowerCamelCase__ )
def _UpperCamelCase( self : int ):
a__ : int = (self.model_tester.min_size,) * 2
a__ : Tuple = {
"pixel_values": torch.randn((2, 3, *size) , device=lowerCamelCase__ ),
"mask_labels": torch.randn((2, 10, *size) , device=lowerCamelCase__ ),
"class_labels": torch.zeros(2 , 10 , device=lowerCamelCase__ ).long(),
}
a__ : int = self.model_tester.get_config()
a__ : Any = MaskaFormerForUniversalSegmentation(lowerCamelCase__ ).to(lowerCamelCase__ )
a__ : Optional[int] = model(**lowerCamelCase__ )
self.assertTrue(outputs.loss is not None )
def _UpperCamelCase( self : Optional[Any] ):
a__, a__ : Dict = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskaformer_model(lowerCamelCase__ , **lowerCamelCase__ , output_hidden_states=lowerCamelCase__ )
def _UpperCamelCase( self : Optional[Any] ):
a__, a__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ : Optional[Any] = model_class(lowerCamelCase__ ).to(lowerCamelCase__ )
a__ : Any = model(**lowerCamelCase__ , output_attentions=lowerCamelCase__ )
self.assertTrue(outputs.attentions is not None )
def _UpperCamelCase( self : Optional[Any] ):
if not self.model_tester.is_training:
return
a__ : Union[str, Any] = self.all_model_classes[1]
a__, a__, a__, a__, a__ : List[str] = self.model_tester.prepare_config_and_inputs()
a__ : Tuple = model_class(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.train()
a__ : int = model(lowerCamelCase__ , mask_labels=lowerCamelCase__ , class_labels=lowerCamelCase__ ).loss
loss.backward()
def _UpperCamelCase( self : Optional[int] ):
a__ : str = self.all_model_classes[1]
a__, a__, a__, a__, a__ : int = self.model_tester.prepare_config_and_inputs()
a__ : Optional[Any] = True
a__ : str = True
a__ : Any = model_class(lowerCamelCase__ ).to(lowerCamelCase__ )
model.train()
a__ : Union[str, Any] = model(lowerCamelCase__ , mask_labels=lowerCamelCase__ , class_labels=lowerCamelCase__ )
a__ : Dict = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
a__ : Optional[Any] = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
a__ : List[Any] = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
a__ : List[str] = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=lowerCamelCase__ )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
UpperCamelCase : Any = 1E-4
def UpperCamelCase_ ( ) -> str:
a__ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_vision
@slow
class A__ ( unittest.TestCase ):
"""simple docstring"""
@cached_property
def _UpperCamelCase( self : str ):
return "facebook/mask2former-swin-small-coco-instance"
@cached_property
def _UpperCamelCase( self : str ):
return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None
def _UpperCamelCase( self : Dict ):
a__ : Dict = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ )
a__ : List[Any] = self.default_image_processor
a__ : List[Any] = prepare_img()
a__ : Optional[Any] = image_processor(lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ )
a__ : Dict = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(lowerCamelCase__ , (1, 3, 384, 384) )
with torch.no_grad():
a__ : str = model(**lowerCamelCase__ )
a__ : str = torch.tensor(
[[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(lowerCamelCase__ )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) )
a__ : List[str] = torch.tensor(
[[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(lowerCamelCase__ )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) )
a__ : Tuple = torch.tensor(
[[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(lowerCamelCase__ )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) )
def _UpperCamelCase( self : List[Any] ):
a__ : str = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ).eval()
a__ : List[Any] = self.default_image_processor
a__ : str = prepare_img()
a__ : Union[str, Any] = image_processor(lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ )
a__ : str = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(lowerCamelCase__ , (1, 3, 384, 384) )
with torch.no_grad():
a__ : Union[str, Any] = model(**lowerCamelCase__ )
# masks_queries_logits
a__ : Tuple = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) )
a__ : Optional[int] = [
[-8.7839, -9.0056, -8.8121],
[-7.4104, -7.0313, -6.5401],
[-6.6105, -6.3427, -6.4675],
]
a__ : int = torch.tensor(lowerCamelCase__ ).to(lowerCamelCase__ )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) )
# class_queries_logits
a__ : Any = outputs.class_queries_logits
self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) )
a__ : List[str] = torch.tensor(
[
[1.8324, -8.0835, -4.1922],
[0.8450, -9.0050, -3.6053],
[0.3045, -7.7293, -3.0275],
] ).to(lowerCamelCase__ )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) )
def _UpperCamelCase( self : str ):
a__ : Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ).eval()
a__ : List[Any] = self.default_image_processor
a__ : Union[str, Any] = image_processor(
[np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , )
a__ : Any = inputs["pixel_values"].to(lowerCamelCase__ )
a__ : List[Any] = [el.to(lowerCamelCase__ ) for el in inputs["mask_labels"]]
a__ : List[Any] = [el.to(lowerCamelCase__ ) for el in inputs["class_labels"]]
with torch.no_grad():
a__ : List[Any] = model(**lowerCamelCase__ )
self.assertTrue(outputs.loss is not None )
| 37 |
import os
from datetime import datetime as dt
from github import Github
__lowerCAmelCase : List[Any] =[
'good first issue',
'good second issue',
'good difficult issue',
'enhancement',
'new pipeline/model',
'new scheduler',
'wip',
]
def _UpperCamelCase ( ):
__SCREAMING_SNAKE_CASE : Tuple = Github(os.environ['''GITHUB_TOKEN'''] )
__SCREAMING_SNAKE_CASE : Union[str, Any] = g.get_repo('''huggingface/diffusers''' )
__SCREAMING_SNAKE_CASE : Union[str, Any] = repo.get_issues(state='''open''' )
for issue in open_issues:
__SCREAMING_SNAKE_CASE : Optional[int] = sorted(issue.get_comments() , key=lambda lowercase__ : i.created_at , reverse=lowercase__ )
__SCREAMING_SNAKE_CASE : List[Any] = comments[0] if len(lowercase__ ) > 0 else None
if (
last_comment is not None
and last_comment.user.login == "github-actions[bot]"
and (dt.utcnow() - issue.updated_at).days > 7
and (dt.utcnow() - issue.created_at).days >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Closes the issue after 7 days of inactivity since the Stalebot notification.
issue.edit(state='''closed''' )
elif (
"stale" in issue.get_labels()
and last_comment is not None
and last_comment.user.login != "github-actions[bot]"
):
# Opens the issue if someone other than Stalebot commented.
issue.edit(state='''open''' )
issue.remove_from_labels('''stale''' )
elif (
(dt.utcnow() - issue.updated_at).days > 23
and (dt.utcnow() - issue.created_at).days >= 30
and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
):
# Post a Stalebot notification after 23 days of inactivity.
issue.create_comment(
'''This issue has been automatically marked as stale because it has not had '''
'''recent activity. If you think this still needs to be addressed '''
'''please comment on this thread.\n\nPlease note that issues that do not follow the '''
'''[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) '''
'''are likely to be ignored.''' )
issue.add_to_labels('''stale''' )
if __name__ == "__main__":
main()
| 696 | 0 |
from __future__ import annotations
from typing import Any
def __lowercase ( _SCREAMING_SNAKE_CASE ) -> int:
'''simple docstring'''
if not postfix_notation:
return 0
SCREAMING_SNAKE_CASE = {"""+""", """-""", """*""", """/"""}
SCREAMING_SNAKE_CASE = []
for token in postfix_notation:
if token in operations:
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = stack.pop(), stack.pop()
if token == "+":
stack.append(a + b )
elif token == "-":
stack.append(a - b )
elif token == "*":
stack.append(a * b )
else:
if a * b < 0 and a % b != 0:
stack.append(a // b + 1 )
else:
stack.append(a // b )
else:
stack.append(int(_SCREAMING_SNAKE_CASE ) )
return stack.pop()
if __name__ == "__main__":
import doctest
doctest.testmod()
| 116 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel
if is_vision_available():
from transformers import MaskaFormerImageProcessor
if is_vision_available():
from PIL import Image
class UpperCamelCase__ :
'''simple docstring'''
def __init__( self : Tuple ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Optional[int]=True ,lowerCamelCase__ : int=False ,lowerCamelCase__ : List[str]=10 ,lowerCamelCase__ : int=3 ,lowerCamelCase__ : Optional[Any]=32 * 8 ,lowerCamelCase__ : Tuple=32 * 8 ,lowerCamelCase__ : Tuple=4 ,lowerCamelCase__ : int=64 ,) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = parent
SCREAMING_SNAKE_CASE = batch_size
SCREAMING_SNAKE_CASE = is_training
SCREAMING_SNAKE_CASE = use_auxiliary_loss
SCREAMING_SNAKE_CASE = num_queries
SCREAMING_SNAKE_CASE = num_channels
SCREAMING_SNAKE_CASE = min_size
SCREAMING_SNAKE_CASE = max_size
SCREAMING_SNAKE_CASE = num_labels
SCREAMING_SNAKE_CASE = hidden_dim
SCREAMING_SNAKE_CASE = hidden_dim
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to(
lowerCamelCase__ )
SCREAMING_SNAKE_CASE = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=lowerCamelCase__ )
SCREAMING_SNAKE_CASE = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=lowerCamelCase__ ) > 0.5
).float()
SCREAMING_SNAKE_CASE = (torch.rand((self.batch_size, self.num_labels) ,device=lowerCamelCase__ ) > 0.5).long()
SCREAMING_SNAKE_CASE = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE = MaskaFormerConfig(
hidden_size=self.hidden_dim ,)
SCREAMING_SNAKE_CASE = self.num_queries
SCREAMING_SNAKE_CASE = self.num_labels
SCREAMING_SNAKE_CASE = [1, 1, 1, 1]
SCREAMING_SNAKE_CASE = self.num_channels
SCREAMING_SNAKE_CASE = 64
SCREAMING_SNAKE_CASE = 128
SCREAMING_SNAKE_CASE = self.hidden_dim
SCREAMING_SNAKE_CASE = self.hidden_dim
SCREAMING_SNAKE_CASE = self.hidden_dim
return config
def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE = {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE__ ( self : List[str] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Dict ) -> str:
'''simple docstring'''
SCREAMING_SNAKE_CASE = output.encoder_hidden_states
SCREAMING_SNAKE_CASE = output.pixel_decoder_hidden_states
SCREAMING_SNAKE_CASE = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(lowerCamelCase__ ) ,len(config.backbone_config.depths ) )
self.parent.assertTrue(len(lowerCamelCase__ ) ,len(config.backbone_config.depths ) )
self.parent.assertTrue(len(lowerCamelCase__ ) ,config.decoder_layers )
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Any ,lowerCamelCase__ : int ,lowerCamelCase__ : Optional[int]=False ) -> int:
'''simple docstring'''
with torch.no_grad():
SCREAMING_SNAKE_CASE = MaskaFormerModel(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
SCREAMING_SNAKE_CASE = model(pixel_values=lowerCamelCase__ ,pixel_mask=lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ )
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,)
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(output.encoder_last_hidden_state is not None )
if output_hidden_states:
self.check_output_hidden_state(lowerCamelCase__ ,lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Any ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = MaskaFormerForUniversalSegmentation(config=lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.eval()
def comm_check_on_output(lowerCamelCase__ : Optional[int] ):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None )
self.parent.assertTrue(result.encoder_last_hidden_state is not None )
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,)
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) )
with torch.no_grad():
SCREAMING_SNAKE_CASE = model(pixel_values=lowerCamelCase__ ,pixel_mask=lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )
comm_check_on_output(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(
pixel_values=lowerCamelCase__ ,pixel_mask=lowerCamelCase__ ,mask_labels=lowerCamelCase__ ,class_labels=lowerCamelCase__ )
comm_check_on_output(lowerCamelCase__ )
self.parent.assertTrue(result.loss is not None )
self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) )
@require_torch
class UpperCamelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ):
'''simple docstring'''
__snake_case : Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
__snake_case : Optional[Any] = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {}
__snake_case : Dict = False
__snake_case : Tuple = False
__snake_case : Union[str, Any] = False
__snake_case : Optional[Any] = False
def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = MaskaFormerModelTester(self )
SCREAMING_SNAKE_CASE = ConfigTester(self ,config_class=lowerCamelCase__ ,has_text_modality=lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : int ) -> Dict:
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskaformer_model(lowerCamelCase__ ,**lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowerCamelCase__ )
@unittest.skip(reason="""Mask2Former does not use inputs_embeds""" )
def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int:
'''simple docstring'''
pass
@unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" )
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Tuple:
'''simple docstring'''
pass
@unittest.skip(reason="""Mask2Former is not a generative model""" )
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Dict:
'''simple docstring'''
pass
@unittest.skip(reason="""Mask2Former does not use token embeddings""" )
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> List[Any]:
'''simple docstring'''
pass
@require_torch_multi_gpu
@unittest.skip(
reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" )
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any:
'''simple docstring'''
pass
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" )
def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> Tuple:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE = model_class(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE = ["""pixel_values"""]
self.assertListEqual(arg_names[:1] ,lowerCamelCase__ )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any:
'''simple docstring'''
for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
SCREAMING_SNAKE_CASE = MaskaFormerModel.from_pretrained(lowerCamelCase__ )
self.assertIsNotNone(lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = (self.model_tester.min_size,) * 2
SCREAMING_SNAKE_CASE = {
"""pixel_values""": torch.randn((2, 3, *size) ,device=lowerCamelCase__ ),
"""mask_labels""": torch.randn((2, 10, *size) ,device=lowerCamelCase__ ),
"""class_labels""": torch.zeros(2 ,10 ,device=lowerCamelCase__ ).long(),
}
SCREAMING_SNAKE_CASE = self.model_tester.get_config()
SCREAMING_SNAKE_CASE = MaskaFormerForUniversalSegmentation(lowerCamelCase__ ).to(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ )
self.assertTrue(outputs.loss is not None )
def SCREAMING_SNAKE_CASE__ ( self : int ) -> List[str]:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskaformer_model(lowerCamelCase__ ,**lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ )
def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Optional[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE = model_class(lowerCamelCase__ ).to(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ ,output_attentions=lowerCamelCase__ )
self.assertTrue(outputs.attentions is not None )
def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> List[str]:
'''simple docstring'''
if not self.model_tester.is_training:
return
SCREAMING_SNAKE_CASE = self.all_model_classes[1]
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE = model_class(lowerCamelCase__ )
model.to(lowerCamelCase__ )
model.train()
SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,mask_labels=lowerCamelCase__ ,class_labels=lowerCamelCase__ ).loss
loss.backward()
def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = self.all_model_classes[1]
SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = model_class(lowerCamelCase__ ).to(lowerCamelCase__ )
model.train()
SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,mask_labels=lowerCamelCase__ ,class_labels=lowerCamelCase__ )
SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
SCREAMING_SNAKE_CASE = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=lowerCamelCase__ )
self.assertIsNotNone(encoder_hidden_states.grad )
self.assertIsNotNone(pixel_decoder_hidden_states.grad )
self.assertIsNotNone(transformer_decoder_hidden_states.grad )
self.assertIsNotNone(attentions.grad )
SCREAMING_SNAKE_CASE_ = 1e-4
def __lowercase ( ) -> Any:
'''simple docstring'''
SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
return image
@require_vision
@slow
class UpperCamelCase__ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]:
'''simple docstring'''
return "facebook/mask2former-swin-small-coco-instance"
@cached_property
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None
def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = self.default_image_processor
SCREAMING_SNAKE_CASE = prepare_img()
SCREAMING_SNAKE_CASE = image_processor(lowerCamelCase__ ,return_tensors="""pt""" ).to(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = inputs["""pixel_values"""].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(lowerCamelCase__ ,(1, 3, 384, 384) )
with torch.no_grad():
SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ )
SCREAMING_SNAKE_CASE = torch.tensor(
[[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]] ).to(lowerCamelCase__ )
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] ,lowerCamelCase__ ,atol=lowerCamelCase__ ) )
SCREAMING_SNAKE_CASE = torch.tensor(
[[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]] ).to(lowerCamelCase__ )
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,lowerCamelCase__ ,atol=lowerCamelCase__ ) )
SCREAMING_SNAKE_CASE = torch.tensor(
[[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]] ).to(lowerCamelCase__ )
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,lowerCamelCase__ ,atol=lowerCamelCase__ ) )
def SCREAMING_SNAKE_CASE__ ( self : int ) -> int:
'''simple docstring'''
SCREAMING_SNAKE_CASE = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ).eval()
SCREAMING_SNAKE_CASE = self.default_image_processor
SCREAMING_SNAKE_CASE = prepare_img()
SCREAMING_SNAKE_CASE = image_processor(lowerCamelCase__ ,return_tensors="""pt""" ).to(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = inputs["""pixel_values"""].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 )
# check size
self.assertEqual(lowerCamelCase__ ,(1, 3, 384, 384) )
with torch.no_grad():
SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ )
# masks_queries_logits
SCREAMING_SNAKE_CASE = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) )
SCREAMING_SNAKE_CASE = [
[-8.7839, -9.0056, -8.8121],
[-7.4104, -7.0313, -6.5401],
[-6.6105, -6.3427, -6.4675],
]
SCREAMING_SNAKE_CASE = torch.tensor(lowerCamelCase__ ).to(lowerCamelCase__ )
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,lowerCamelCase__ ,atol=lowerCamelCase__ ) )
# class_queries_logits
SCREAMING_SNAKE_CASE = outputs.class_queries_logits
self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) )
SCREAMING_SNAKE_CASE = torch.tensor(
[
[1.8324, -8.0835, -4.1922],
[0.8450, -9.0050, -3.6053],
[0.3045, -7.7293, -3.0275],
] ).to(lowerCamelCase__ )
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,lowerCamelCase__ ,atol=lowerCamelCase__ ) )
def SCREAMING_SNAKE_CASE__ ( self : int ) -> Optional[int]:
'''simple docstring'''
SCREAMING_SNAKE_CASE = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ).eval()
SCREAMING_SNAKE_CASE = self.default_image_processor
SCREAMING_SNAKE_CASE = image_processor(
[np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] ,segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] ,return_tensors="""pt""" ,)
SCREAMING_SNAKE_CASE = inputs["""pixel_values"""].to(lowerCamelCase__ )
SCREAMING_SNAKE_CASE = [el.to(lowerCamelCase__ ) for el in inputs["""mask_labels"""]]
SCREAMING_SNAKE_CASE = [el.to(lowerCamelCase__ ) for el in inputs["""class_labels"""]]
with torch.no_grad():
SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ )
self.assertTrue(outputs.loss is not None )
| 116 | 1 |
from pickle import UnpicklingError
import jax
import jax.numpy as jnp
import numpy as np
from flax.serialization import from_bytes
from flax.traverse_util import flatten_dict
from ..utils import logging
lowerCamelCase__ : List[str] = logging.get_logger(__name__)
def UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] ) -> Union[str, Any]:
try:
with open(__UpperCAmelCase , 'rb' ) as flax_state_f:
SCREAMING_SNAKE_CASE_ = from_bytes(__UpperCAmelCase , flax_state_f.read() )
except UnpicklingError as e:
try:
with open(__UpperCAmelCase ) as f:
if f.read().startswith('version' ):
raise OSError(
'You seem to have cloned a repository without having git-lfs installed. Please'
' install git-lfs and run `git lfs install` followed by `git lfs pull` in the'
' folder you cloned.' )
else:
raise ValueError from e
except (UnicodeDecodeError, ValueError):
raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. " )
return load_flax_weights_in_pytorch_model(__UpperCAmelCase , __UpperCAmelCase )
def UpperCAmelCase_ ( __UpperCAmelCase : str , __UpperCAmelCase : Optional[int] ) -> Dict:
try:
import torch # noqa: F401
except ImportError:
logger.error(
'Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see'
' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation'
' instructions.' )
raise
# check if we have bf16 weights
SCREAMING_SNAKE_CASE_ = flatten_dict(jax.tree_util.tree_map(lambda __UpperCAmelCase : x.dtype == jnp.bfloataa , __UpperCAmelCase ) ).values()
if any(__UpperCAmelCase ):
# convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16
# and bf16 is not fully supported in PT yet.
logger.warning(
'Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` '
'before loading those in PyTorch model.' )
SCREAMING_SNAKE_CASE_ = jax.tree_util.tree_map(
lambda __UpperCAmelCase : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , __UpperCAmelCase )
SCREAMING_SNAKE_CASE_ = ''
SCREAMING_SNAKE_CASE_ = flatten_dict(__UpperCAmelCase , sep='.' )
SCREAMING_SNAKE_CASE_ = pt_model.state_dict()
# keep track of unexpected & missing keys
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = set(pt_model_dict.keys() )
for flax_key_tuple, flax_tensor in flax_state_dict.items():
SCREAMING_SNAKE_CASE_ = flax_key_tuple.split('.' )
if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4:
SCREAMING_SNAKE_CASE_ = flax_key_tuple_array[:-1] + ['weight']
SCREAMING_SNAKE_CASE_ = jnp.transpose(__UpperCAmelCase , (3, 2, 0, 1) )
elif flax_key_tuple_array[-1] == "kernel":
SCREAMING_SNAKE_CASE_ = flax_key_tuple_array[:-1] + ['weight']
SCREAMING_SNAKE_CASE_ = flax_tensor.T
elif flax_key_tuple_array[-1] == "scale":
SCREAMING_SNAKE_CASE_ = flax_key_tuple_array[:-1] + ['weight']
if "time_embedding" not in flax_key_tuple_array:
for i, flax_key_tuple_string in enumerate(__UpperCAmelCase ):
SCREAMING_SNAKE_CASE_ = (
flax_key_tuple_string.replace('_0' , '.0' )
.replace('_1' , '.1' )
.replace('_2' , '.2' )
.replace('_3' , '.3' )
.replace('_4' , '.4' )
.replace('_5' , '.5' )
.replace('_6' , '.6' )
.replace('_7' , '.7' )
.replace('_8' , '.8' )
.replace('_9' , '.9' )
)
SCREAMING_SNAKE_CASE_ = '.'.join(__UpperCAmelCase )
if flax_key in pt_model_dict:
if flax_tensor.shape != pt_model_dict[flax_key].shape:
raise ValueError(
f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected "
f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." )
else:
# add weight to pytorch dict
SCREAMING_SNAKE_CASE_ = np.asarray(__UpperCAmelCase ) if not isinstance(__UpperCAmelCase , np.ndarray ) else flax_tensor
SCREAMING_SNAKE_CASE_ = torch.from_numpy(__UpperCAmelCase )
# remove from missing keys
missing_keys.remove(__UpperCAmelCase )
else:
# weight is not expected by PyTorch model
unexpected_keys.append(__UpperCAmelCase )
pt_model.load_state_dict(__UpperCAmelCase )
# re-transform missing_keys to list
SCREAMING_SNAKE_CASE_ = list(__UpperCAmelCase )
if len(__UpperCAmelCase ) > 0:
logger.warning(
'Some weights of the Flax model were not used when initializing the PyTorch model'
f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"
f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture"
' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This'
f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect"
' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a'
' FlaxBertForSequenceClassification model).' )
if len(__UpperCAmelCase ) > 0:
logger.warning(
f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly"
f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"
' use it for predictions and inference.' )
return pt_model | 31 |
'''simple docstring'''
import unittest
import numpy as np
import requests
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
lowerCAmelCase = False
if is_vision_available():
from PIL import Image
from transformers import PixaStructImageProcessor
class lowerCAmelCase_ ( unittest.TestCase ):
def __init__( self , _UpperCamelCase , _UpperCamelCase=7 , _UpperCamelCase=3 , _UpperCamelCase=18 , _UpperCamelCase=30 , _UpperCamelCase=400 , _UpperCamelCase=None , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=None , )-> Dict:
_A = size if size is not None else {'height': 20, 'width': 20}
_A = parent
_A = batch_size
_A = num_channels
_A = image_size
_A = min_resolution
_A = max_resolution
_A = size
_A = do_normalize
_A = do_convert_rgb
_A = [512, 1024, 2048, 4096]
_A = patch_size if patch_size is not None else {'height': 16, 'width': 16}
def UpperCamelCase ( self )-> Dict:
return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}
def UpperCamelCase ( self )-> Tuple:
_A = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
_A = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert('RGB' )
return raw_image
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , )
@require_torch
@require_vision
class lowerCAmelCase_ ( UpperCAmelCase , unittest.TestCase ):
__UpperCAmelCase =PixaStructImageProcessor if is_vision_available() else None
def UpperCamelCase ( self )-> Optional[int]:
_A = PixaStructImageProcessingTester(self )
@property
def UpperCamelCase ( self )-> Tuple:
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCamelCase ( self )-> List[Any]:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_UpperCamelCase , 'do_normalize' ) )
self.assertTrue(hasattr(_UpperCamelCase , 'do_convert_rgb' ) )
def UpperCamelCase ( self )-> Any:
_A = self.image_processor_tester.prepare_dummy_image()
_A = self.image_processing_class(**self.image_processor_dict )
_A = 2048
_A = image_processor(_UpperCamelCase , return_tensors='pt' , max_patches=_UpperCamelCase )
self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) )
def UpperCamelCase ( self )-> int:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCamelCase )
for image in image_inputs:
self.assertIsInstance(_UpperCamelCase , Image.Image )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
_UpperCamelCase , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def UpperCamelCase ( self )-> List[str]:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCamelCase )
for image in image_inputs:
self.assertIsInstance(_UpperCamelCase , Image.Image )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
* self.image_processor_tester.num_channels
) + 2
_A = True
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
with self.assertRaises(_UpperCamelCase ):
_A = image_processor(
image_inputs[0] , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
_A = 'Hello'
_A = image_processor(
image_inputs[0] , return_tensors='pt' , max_patches=_UpperCamelCase , header_text=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
_UpperCamelCase , return_tensors='pt' , max_patches=_UpperCamelCase , header_text=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def UpperCamelCase ( self )-> Optional[int]:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCamelCase , numpify=_UpperCamelCase )
for image in image_inputs:
self.assertIsInstance(_UpperCamelCase , np.ndarray )
_A = (
(self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
_UpperCamelCase , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
def UpperCamelCase ( self )-> Union[str, Any]:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCamelCase , torchify=_UpperCamelCase )
for image in image_inputs:
self.assertIsInstance(_UpperCamelCase , torch.Tensor )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
* self.image_processor_tester.num_channels
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
_UpperCamelCase , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
@unittest.skipIf(
not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , )
@require_torch
@require_vision
class lowerCAmelCase_ ( UpperCAmelCase , unittest.TestCase ):
__UpperCAmelCase =PixaStructImageProcessor if is_vision_available() else None
def UpperCamelCase ( self )-> str:
_A = PixaStructImageProcessingTester(self , num_channels=4 )
_A = 3
@property
def UpperCamelCase ( self )-> str:
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCamelCase ( self )-> Any:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_UpperCamelCase , 'do_normalize' ) )
self.assertTrue(hasattr(_UpperCamelCase , 'do_convert_rgb' ) )
def UpperCamelCase ( self )-> Optional[Any]:
# Initialize image_processor
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCamelCase )
for image in image_inputs:
self.assertIsInstance(_UpperCamelCase , Image.Image )
# Test not batched input
_A = (
(self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
* (self.image_processor_tester.num_channels - 1)
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
_A = image_processor(
image_inputs[0] , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (1, max_patch, expected_hidden_dim) , )
# Test batched
_A = image_processor(
_UpperCamelCase , return_tensors='pt' , max_patches=_UpperCamelCase ).flattened_patches
self.assertEqual(
encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
| 292 | 0 |
'''simple docstring'''
from ....configuration_utils import PretrainedConfig
from ....utils import logging
A: Tuple = logging.get_logger(__name__)
A: List[Any] = {
"speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json",
# See all M-CTC-T models at https://huggingface.co/models?filter=mctct
}
class __magic_name__ ( UpperCAmelCase_ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = 'mctct'
def __init__( self , _lowercase=8065 , _lowercase=1536 , _lowercase=36 , _lowercase=6144 , _lowercase=4 , _lowercase=384 , _lowercase=920 , _lowercase=1E-5 , _lowercase=0.3 , _lowercase="relu" , _lowercase=0.02 , _lowercase=0.3 , _lowercase=0.3 , _lowercase=1 , _lowercase=0 , _lowercase=2 , _lowercase=1 , _lowercase=0.3 , _lowercase=1 , _lowercase=(7,) , _lowercase=(3,) , _lowercase=80 , _lowercase=1 , _lowercase=None , _lowercase="sum" , _lowercase=False , **_lowercase , ) -> Optional[Any]:
super().__init__(**_lowercase , pad_token_id=_lowercase , bos_token_id=_lowercase , eos_token_id=_lowercase )
lowercase_ : Union[str, Any] = vocab_size
lowercase_ : List[Any] = hidden_size
lowercase_ : Union[str, Any] = num_hidden_layers
lowercase_ : str = intermediate_size
lowercase_ : List[Any] = num_attention_heads
lowercase_ : Optional[int] = attention_head_dim
lowercase_ : Optional[Any] = max_position_embeddings
lowercase_ : Optional[int] = layer_norm_eps
lowercase_ : List[Any] = layerdrop
lowercase_ : str = hidden_act
lowercase_ : List[str] = initializer_range
lowercase_ : List[Any] = hidden_dropout_prob
lowercase_ : int = attention_probs_dropout_prob
lowercase_ : Dict = pad_token_id
lowercase_ : Dict = bos_token_id
lowercase_ : Dict = eos_token_id
lowercase_ : Dict = conv_glu_dim
lowercase_ : int = conv_dropout
lowercase_ : List[Any] = num_conv_layers
lowercase_ : List[Any] = input_feat_per_channel
lowercase_ : List[Any] = input_channels
lowercase_ : List[Any] = conv_channels
lowercase_ : List[Any] = ctc_loss_reduction
lowercase_ : List[Any] = ctc_zero_infinity
# prevents config testing fail with exporting to json
lowercase_ : Optional[Any] = list(_lowercase )
lowercase_ : Optional[int] = list(_lowercase )
if len(self.conv_kernel ) != self.num_conv_layers:
raise ValueError(
'Configuration for convolutional module is incorrect. '
'It is required that `len(config.conv_kernel)` == `config.num_conv_layers` '
f"but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, "
f"`config.num_conv_layers = {self.num_conv_layers}`." )
| 7 |
'''simple docstring'''
from __future__ import annotations
def _UpperCAmelCase ( a : int = 4 ) -> list[list[int]]:
"""simple docstring"""
lowercase_ : Tuple = abs(a ) or 4
return [[1 + x + y * row_size for x in range(a )] for y in range(a )]
def _UpperCAmelCase ( a : list[list[int]] ) -> list[list[int]]:
"""simple docstring"""
return reverse_row(transpose(a ) )
# OR.. transpose(reverse_column(matrix))
def _UpperCAmelCase ( a : list[list[int]] ) -> list[list[int]]:
"""simple docstring"""
return reverse_row(reverse_column(a ) )
# OR.. reverse_column(reverse_row(matrix))
def _UpperCAmelCase ( a : list[list[int]] ) -> list[list[int]]:
"""simple docstring"""
return reverse_column(transpose(a ) )
# OR.. transpose(reverse_row(matrix))
def _UpperCAmelCase ( a : list[list[int]] ) -> list[list[int]]:
"""simple docstring"""
lowercase_ : Any = [list(a ) for x in zip(*a )]
return matrix
def _UpperCAmelCase ( a : list[list[int]] ) -> list[list[int]]:
"""simple docstring"""
lowercase_ : List[str] = matrix[::-1]
return matrix
def _UpperCAmelCase ( a : list[list[int]] ) -> list[list[int]]:
"""simple docstring"""
lowercase_ : str = [x[::-1] for x in matrix]
return matrix
def _UpperCAmelCase ( a : list[list[int]] ) -> None:
"""simple docstring"""
for i in matrix:
print(*a )
if __name__ == "__main__":
A: Dict = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 90 counterclockwise:\n")
print_matrix(rotate_aa(matrix))
A: List[Any] = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 180:\n")
print_matrix(rotate_aaa(matrix))
A: List[str] = make_matrix()
print("\norigin:\n")
print_matrix(matrix)
print("\nrotate 270 counterclockwise:\n")
print_matrix(rotate_aaa(matrix))
| 7 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__UpperCAmelCase : Union[str, Any] = {
'configuration_xlm_roberta': [
'XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP',
'XLMRobertaConfig',
'XLMRobertaOnnxConfig',
],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : List[str] = ['XLMRobertaTokenizer']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : Optional[Any] = ['XLMRobertaTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : Optional[Any] = [
'XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST',
'XLMRobertaForCausalLM',
'XLMRobertaForMaskedLM',
'XLMRobertaForMultipleChoice',
'XLMRobertaForQuestionAnswering',
'XLMRobertaForSequenceClassification',
'XLMRobertaForTokenClassification',
'XLMRobertaModel',
'XLMRobertaPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : Dict = [
'TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFXLMRobertaForCausalLM',
'TFXLMRobertaForMaskedLM',
'TFXLMRobertaForMultipleChoice',
'TFXLMRobertaForQuestionAnswering',
'TFXLMRobertaForSequenceClassification',
'TFXLMRobertaForTokenClassification',
'TFXLMRobertaModel',
'TFXLMRobertaPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCAmelCase : int = [
'FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST',
'FlaxXLMRobertaForMaskedLM',
'FlaxXLMRobertaForCausalLM',
'FlaxXLMRobertaForMultipleChoice',
'FlaxXLMRobertaForQuestionAnswering',
'FlaxXLMRobertaForSequenceClassification',
'FlaxXLMRobertaForTokenClassification',
'FlaxXLMRobertaModel',
'FlaxXLMRobertaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_xlm_roberta import (
XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
XLMRobertaConfig,
XLMRobertaOnnxConfig,
)
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlm_roberta import XLMRobertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_xlm_roberta import (
XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
XLMRobertaForCausalLM,
XLMRobertaForMaskedLM,
XLMRobertaForMultipleChoice,
XLMRobertaForQuestionAnswering,
XLMRobertaForSequenceClassification,
XLMRobertaForTokenClassification,
XLMRobertaModel,
XLMRobertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_xlm_roberta import (
TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFXLMRobertaForCausalLM,
TFXLMRobertaForMaskedLM,
TFXLMRobertaForMultipleChoice,
TFXLMRobertaForQuestionAnswering,
TFXLMRobertaForSequenceClassification,
TFXLMRobertaForTokenClassification,
TFXLMRobertaModel,
TFXLMRobertaPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_xlm_roberta import (
FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
FlaxXLMRobertaForCausalLM,
FlaxXLMRobertaForMaskedLM,
FlaxXLMRobertaForMultipleChoice,
FlaxXLMRobertaForQuestionAnswering,
FlaxXLMRobertaForSequenceClassification,
FlaxXLMRobertaForTokenClassification,
FlaxXLMRobertaModel,
FlaxXLMRobertaPreTrainedModel,
)
else:
import sys
__UpperCAmelCase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 471 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
__UpperCAmelCase : List[Any] = logging.get_logger(__name__)
def lowerCamelCase_ ( UpperCamelCase_ , UpperCamelCase_ ):
_a : Union[str, Any] = b.T
_a : List[str] = np.sum(np.square(UpperCamelCase_ ) , axis=1 )
_a : List[str] = np.sum(np.square(UpperCamelCase_ ) , axis=0 )
_a : Optional[int] = np.matmul(UpperCamelCase_ , UpperCamelCase_ )
_a : Optional[Any] = aa[:, None] - 2 * ab + ba[None, :]
return d
def lowerCamelCase_ ( UpperCamelCase_ , UpperCamelCase_ ):
_a : int = x.reshape(-1 , 3 )
_a : Any = squared_euclidean_distance(UpperCamelCase_ , UpperCamelCase_ )
return np.argmin(UpperCamelCase_ , axis=1 )
class lowerCamelCase ( SCREAMING_SNAKE_CASE ):
UpperCAmelCase : Dict = ['pixel_values']
def __init__( self : List[Any] , __snake_case : Optional[Union[List[List[int]], np.ndarray]] = None , __snake_case : bool = True , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : bool = True , __snake_case : bool = True , **__snake_case : str , ) -> None:
super().__init__(**__snake_case )
_a : int = size if size is not None else {'''height''': 256, '''width''': 256}
_a : Union[str, Any] = get_size_dict(__snake_case )
_a : Tuple = np.array(__snake_case ) if clusters is not None else None
_a : List[Any] = do_resize
_a : List[str] = size
_a : List[Any] = resample
_a : Optional[Any] = do_normalize
_a : Dict = do_color_quantize
def snake_case_ ( self : Dict , __snake_case : np.ndarray , __snake_case : Dict[str, int] , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : List[Any] , ) -> np.ndarray:
_a : List[str] = get_size_dict(__snake_case )
if "height" not in size or "width" not in size:
raise ValueError(f"""Size dictionary must contain both height and width keys. Got {size.keys()}""" )
return resize(
__snake_case , size=(size['''height'''], size['''width''']) , resample=__snake_case , data_format=__snake_case , **__snake_case )
def snake_case_ ( self : Optional[int] , __snake_case : np.ndarray , __snake_case : Optional[Union[str, ChannelDimension]] = None , ) -> np.ndarray:
_a : List[Any] = rescale(image=__snake_case , scale=1 / 127.5 , data_format=__snake_case )
_a : List[Any] = image - 1
return image
def snake_case_ ( self : Optional[Any] , __snake_case : ImageInput , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = None , __snake_case : bool = None , __snake_case : Optional[bool] = None , __snake_case : Optional[Union[List[List[int]], np.ndarray]] = None , __snake_case : Optional[Union[str, TensorType]] = None , __snake_case : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **__snake_case : List[Any] , ) -> PIL.Image.Image:
_a : Any = do_resize if do_resize is not None else self.do_resize
_a : Optional[int] = size if size is not None else self.size
_a : List[Any] = get_size_dict(__snake_case )
_a : List[str] = resample if resample is not None else self.resample
_a : List[str] = do_normalize if do_normalize is not None else self.do_normalize
_a : Union[str, Any] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize
_a : List[Any] = clusters if clusters is not None else self.clusters
_a : int = np.array(__snake_case )
_a : Optional[int] = make_list_of_images(__snake_case )
if not valid_images(__snake_case ):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''' )
if do_resize and size is None or resample is None:
raise ValueError('''Size and resample must be specified if do_resize is True.''' )
if do_color_quantize and clusters is None:
raise ValueError('''Clusters must be specified if do_color_quantize is True.''' )
# All transformations expect numpy arrays.
_a : Any = [to_numpy_array(__snake_case ) for image in images]
if do_resize:
_a : Optional[int] = [self.resize(image=__snake_case , size=__snake_case , resample=__snake_case ) for image in images]
if do_normalize:
_a : Dict = [self.normalize(image=__snake_case ) for image in images]
if do_color_quantize:
_a : Optional[int] = [to_channel_dimension_format(__snake_case , ChannelDimension.LAST ) for image in images]
# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
_a : List[Any] = np.array(__snake_case )
_a : Optional[int] = color_quantize(__snake_case , __snake_case ).reshape(images.shape[:-1] )
# flatten to (batch_size, height*width)
_a : int = images.shape[0]
_a : int = images.reshape(__snake_case , -1 )
# We need to convert back to a list of images to keep consistent behaviour across processors.
_a : Dict = list(__snake_case )
else:
_a : Optional[Any] = [to_channel_dimension_format(__snake_case , __snake_case ) for image in images]
_a : int = {'''input_ids''': images}
return BatchFeature(data=__snake_case , tensor_type=__snake_case )
| 471 | 1 |
from ..utils import is_flax_available, is_torch_available
if is_torch_available():
from .autoencoder_kl import AutoencoderKL
from .controlnet import ControlNetModel
from .dual_transformer_ad import DualTransformeraDModel
from .modeling_utils import ModelMixin
from .prior_transformer import PriorTransformer
from .ta_film_transformer import TaFilmDecoder
from .transformer_ad import TransformeraDModel
from .unet_ad import UNetaDModel
from .unet_ad import UNetaDModel
from .unet_ad_condition import UNetaDConditionModel
from .unet_ad_condition import UNetaDConditionModel
from .vq_model import VQModel
if is_flax_available():
from .controlnet_flax import FlaxControlNetModel
from .unet_ad_condition_flax import FlaxUNetaDConditionModel
from .vae_flax import FlaxAutoencoderKL
| 683 |
from typing import Any
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ):
_validation(
snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , )
# Creates data structures and fill initial step
lowerCAmelCase_ : dict = {}
lowerCAmelCase_ : dict = {}
for state in states_space:
lowerCAmelCase_ : List[Any] = observations_space[0]
lowerCAmelCase_ : int = (
initial_probabilities[state] * emission_probabilities[state][observation]
)
lowerCAmelCase_ : Dict = None
# Fills the data structure with the probabilities of
# different transitions and pointers to previous states
for o in range(1 , len(snake_case__)):
lowerCAmelCase_ : List[Any] = observations_space[o]
lowerCAmelCase_ : Optional[Any] = observations_space[o - 1]
for state in states_space:
# Calculates the argmax for probability function
lowerCAmelCase_ : List[Any] = ""
lowerCAmelCase_ : Tuple = -1
for k_state in states_space:
lowerCAmelCase_ : int = (
probabilities[(k_state, prior_observation)]
* transition_probabilities[k_state][state]
* emission_probabilities[state][observation]
)
if probability > max_probability:
lowerCAmelCase_ : List[str] = probability
lowerCAmelCase_ : Optional[Any] = k_state
# Update probabilities and pointers dicts
lowerCAmelCase_ : Union[str, Any] = (
probabilities[(arg_max, prior_observation)]
* transition_probabilities[arg_max][state]
* emission_probabilities[state][observation]
)
lowerCAmelCase_ : Any = arg_max
# The final observation
lowerCAmelCase_ : List[Any] = observations_space[len(snake_case__) - 1]
# argmax for given final observation
lowerCAmelCase_ : List[str] = ""
lowerCAmelCase_ : List[str] = -1
for k_state in states_space:
lowerCAmelCase_ : List[str] = probabilities[(k_state, final_observation)]
if probability > max_probability:
lowerCAmelCase_ : List[str] = probability
lowerCAmelCase_ : Tuple = k_state
lowerCAmelCase_ : str = arg_max
# Process pointers backwards
lowerCAmelCase_ : int = last_state
lowerCAmelCase_ : int = []
for o in range(len(snake_case__) - 1 , -1 , -1):
result.append(snake_case__)
lowerCAmelCase_ : Optional[Any] = pointers[previous, observations_space[o]]
result.reverse()
return result
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ):
_validate_not_empty(
snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , )
_validate_lists(snake_case__ , snake_case__)
_validate_dicts(
snake_case__ , snake_case__ , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , ):
if not all(
[
observations_space,
states_space,
initial_probabilities,
transition_probabilities,
emission_probabilities,
]):
raise ValueError("There's an empty parameter")
def UpperCamelCase ( snake_case__ , snake_case__):
_validate_list(snake_case__ , "observations_space")
_validate_list(snake_case__ , "states_space")
def UpperCamelCase ( snake_case__ , snake_case__):
if not isinstance(_object , snake_case__):
lowerCAmelCase_ : Optional[Any] = F'''{var_name} must be a list'''
raise ValueError(snake_case__)
else:
for x in _object:
if not isinstance(snake_case__ , snake_case__):
lowerCAmelCase_ : Optional[Any] = F'''{var_name} must be a list of strings'''
raise ValueError(snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , ):
_validate_dict(snake_case__ , "initial_probabilities" , snake_case__)
_validate_nested_dict(snake_case__ , "transition_probabilities")
_validate_nested_dict(snake_case__ , "emission_probabilities")
def UpperCamelCase ( snake_case__ , snake_case__):
_validate_dict(_object , snake_case__ , snake_case__)
for x in _object.values():
_validate_dict(snake_case__ , snake_case__ , snake_case__ , snake_case__)
def UpperCamelCase ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = False):
if not isinstance(_object , snake_case__):
lowerCAmelCase_ : List[str] = F'''{var_name} must be a dict'''
raise ValueError(snake_case__)
if not all(isinstance(snake_case__ , snake_case__) for x in _object):
lowerCAmelCase_ : Dict = F'''{var_name} all keys must be strings'''
raise ValueError(snake_case__)
if not all(isinstance(snake_case__ , snake_case__) for x in _object.values()):
lowerCAmelCase_ : Union[str, Any] = "nested dictionary " if nested else ""
lowerCAmelCase_ : Any = F'''{var_name} {nested_text}all values must be {value_type.__name__}'''
raise ValueError(snake_case__)
if __name__ == "__main__":
from doctest import testmod
testmod()
| 683 | 1 |
import os
import tempfile
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from torch import nn
from transformers import (
Adafactor,
AdamW,
get_constant_schedule,
get_constant_schedule_with_warmup,
get_cosine_schedule_with_warmup,
get_cosine_with_hard_restarts_schedule_with_warmup,
get_inverse_sqrt_schedule,
get_linear_schedule_with_warmup,
get_polynomial_decay_schedule_with_warmup,
)
def a (lowerCAmelCase__ , lowerCAmelCase__=10 ):
__a = []
for _ in range(lowerCAmelCase__ ):
lrs.append(scheduler.get_lr()[0] )
scheduler.step()
return lrs
def a (lowerCAmelCase__ , lowerCAmelCase__=10 ):
__a = []
for step in range(lowerCAmelCase__ ):
lrs.append(scheduler.get_lr()[0] )
scheduler.step()
if step == num_steps // 2:
with tempfile.TemporaryDirectory() as tmpdirname:
__a = os.path.join(lowerCAmelCase__ , """schedule.bin""" )
torch.save(scheduler.state_dict() , lowerCAmelCase__ )
__a = torch.load(lowerCAmelCase__ )
scheduler.load_state_dict(lowerCAmelCase__ )
return lrs
@require_torch
class __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def snake_case_ ( self , __A , __A , __A ):
self.assertEqual(len(__A ) , len(__A ) )
for a, b in zip(__A , __A ):
self.assertAlmostEqual(__A , __A , delta=__A )
def snake_case_ ( self ):
__a = torch.tensor([0.1, -0.2, -0.1] , requires_grad=__A )
__a = torch.tensor([0.4, 0.2, -0.5] )
__a = nn.MSELoss()
# No warmup, constant schedule, no gradient clipping
__a = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 )
for _ in range(100 ):
__a = criterion(__A , __A )
loss.backward()
optimizer.step()
w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves.
w.grad.zero_()
self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 )
def snake_case_ ( self ):
__a = torch.tensor([0.1, -0.2, -0.1] , requires_grad=__A )
__a = torch.tensor([0.4, 0.2, -0.5] )
__a = nn.MSELoss()
# No warmup, constant schedule, no gradient clipping
__a = Adafactor(
params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=__A , weight_decay=0.0 , relative_step=__A , scale_parameter=__A , warmup_init=__A , )
for _ in range(1000 ):
__a = criterion(__A , __A )
loss.backward()
optimizer.step()
w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves.
w.grad.zero_()
self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 )
@require_torch
class __UpperCAmelCase ( unittest.TestCase ):
"""simple docstring"""
_lowerCamelCase = nn.Linear(50 , 50 ) if is_torch_available() else None
_lowerCamelCase = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None
_lowerCamelCase = 10
def snake_case_ ( self , __A , __A , __A , __A=None ):
self.assertEqual(len(__A ) , len(__A ) )
for a, b in zip(__A , __A ):
self.assertAlmostEqual(__A , __A , delta=__A , msg=__A )
def snake_case_ ( self ):
__a = {"""num_warmup_steps""": 2, """num_training_steps""": 10}
# schedulers doct format
# function: (sched_args_dict, expected_learning_rates)
__a = {
get_constant_schedule: ({}, [10.0] * self.num_steps),
get_constant_schedule_with_warmup: (
{"""num_warmup_steps""": 4},
[0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
),
get_linear_schedule_with_warmup: (
{**common_kwargs},
[0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
),
get_cosine_schedule_with_warmup: (
{**common_kwargs},
[0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
),
get_cosine_with_hard_restarts_schedule_with_warmup: (
{**common_kwargs, """num_cycles""": 2},
[0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
),
get_polynomial_decay_schedule_with_warmup: (
{**common_kwargs, """power""": 2.0, """lr_end""": 1E-7},
[0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156],
),
get_inverse_sqrt_schedule: (
{"""num_warmup_steps""": 2},
[0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714],
),
}
for scheduler_func, data in scheds.items():
__a , __a = data
__a = scheduler_func(self.optimizer , **__A )
self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 )
__a = unwrap_schedule(__A , self.num_steps )
self.assertListAlmostEqual(
__A , __A , tol=1E-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , )
__a = scheduler_func(self.optimizer , **__A )
if scheduler_func.__name__ != "get_constant_schedule":
LambdaScheduleWrapper.wrap_scheduler(__A ) # wrap to test picklability of the schedule
__a = unwrap_and_save_reload_schedule(__A , self.num_steps )
self.assertListEqual(__A , __A , msg=f'''failed for {scheduler_func} in save and reload''' )
class __UpperCAmelCase :
"""simple docstring"""
def __init__( self , __A ):
__a = fn
def __call__( self , *__A , **__A ):
return self.fn(*__A , **__A )
@classmethod
def snake_case_ ( self , __A ):
__a = list(map(self , scheduler.lr_lambdas ) )
| 99 |
from collections.abc import Callable
def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
__a = a
__a = b
if function(lowerCAmelCase__ ) == 0: # one of the a or b is a root for the function
return a
elif function(lowerCAmelCase__ ) == 0:
return b
elif (
function(lowerCAmelCase__ ) * function(lowerCAmelCase__ ) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("""could not find root in given interval.""" )
else:
__a = start + (end - start) / 2.0
while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7
if function(lowerCAmelCase__ ) == 0:
return mid
elif function(lowerCAmelCase__ ) * function(lowerCAmelCase__ ) < 0:
__a = mid
else:
__a = mid
__a = start + (end - start) / 2.0
return mid
def a (lowerCAmelCase__ ):
return x**3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1_0_0_0))
import doctest
doctest.testmod()
| 99 | 1 |
"""simple docstring"""
import json
import os
import re
import unittest
from transformers import CodeGenTokenizer, CodeGenTokenizerFast
from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCamelCase ( snake_case , unittest.TestCase ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = CodeGenTokenizer
SCREAMING_SNAKE_CASE_ : str = CodeGenTokenizerFast
SCREAMING_SNAKE_CASE_ : Tuple = True
SCREAMING_SNAKE_CASE_ : Dict = {"add_prefix_space": True}
SCREAMING_SNAKE_CASE_ : List[Any] = False
def lowerCamelCase__ ( self ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_lowercase : Dict = [
"""l""",
"""o""",
"""w""",
"""e""",
"""r""",
"""s""",
"""t""",
"""i""",
"""d""",
"""n""",
"""\u0120""",
"""\u0120l""",
"""\u0120n""",
"""\u0120lo""",
"""\u0120low""",
"""er""",
"""\u0120lowest""",
"""\u0120newer""",
"""\u0120wider""",
"""<unk>""",
"""<|endoftext|>""",
]
_lowercase : List[Any] = dict(zip(UpperCAmelCase_ ,range(len(UpperCAmelCase_ ) ) ) )
_lowercase : Union[str, Any] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
_lowercase : List[Any] = {"""unk_token""": """<unk>"""}
_lowercase : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""vocab_file"""] )
_lowercase : Union[str, Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""merges_file"""] )
with open(self.vocab_file ,"""w""" ,encoding="""utf-8""" ) as fp:
fp.write(json.dumps(UpperCAmelCase_ ) + """\n""" )
with open(self.merges_file ,"""w""" ,encoding="""utf-8""" ) as fp:
fp.write("""\n""".join(UpperCAmelCase_ ) )
def lowerCamelCase__ ( self ,**UpperCAmelCase_ ):
kwargs.update(self.special_tokens_map )
return CodeGenTokenizer.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ )
def lowerCamelCase__ ( self ,**UpperCAmelCase_ ):
kwargs.update(self.special_tokens_map )
return CodeGenTokenizerFast.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ )
def lowerCamelCase__ ( self ,UpperCAmelCase_ ):
_lowercase : int = """lower newer"""
_lowercase : List[Any] = """lower newer"""
return input_text, output_text
def lowerCamelCase__ ( self ):
_lowercase : Optional[Any] = CodeGenTokenizer(self.vocab_file ,self.merges_file ,**self.special_tokens_map )
_lowercase : str = """lower newer"""
_lowercase : Optional[Any] = ["""\u0120low""", """er""", """\u0120""", """n""", """e""", """w""", """er"""]
_lowercase : int = tokenizer.tokenize(UpperCAmelCase_ ,add_prefix_space=UpperCAmelCase_ )
self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ )
_lowercase : Union[str, Any] = tokens + [tokenizer.unk_token]
_lowercase : Union[str, Any] = [14, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) ,UpperCAmelCase_ )
def lowerCamelCase__ ( self ):
if not self.test_rust_tokenizer:
return
_lowercase : Union[str, Any] = self.get_tokenizer()
_lowercase : Optional[int] = self.get_rust_tokenizer(add_prefix_space=UpperCAmelCase_ )
_lowercase : Tuple = """lower newer"""
# Testing tokenization
_lowercase : Union[str, Any] = tokenizer.tokenize(UpperCAmelCase_ ,add_prefix_space=UpperCAmelCase_ )
_lowercase : List[str] = rust_tokenizer.tokenize(UpperCAmelCase_ )
self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ )
# Testing conversion to ids without special tokens
_lowercase : Dict = tokenizer.encode(UpperCAmelCase_ ,add_special_tokens=UpperCAmelCase_ ,add_prefix_space=UpperCAmelCase_ )
_lowercase : int = rust_tokenizer.encode(UpperCAmelCase_ ,add_special_tokens=UpperCAmelCase_ )
self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ )
# Testing conversion to ids with special tokens
_lowercase : int = self.get_rust_tokenizer(add_prefix_space=UpperCAmelCase_ )
_lowercase : int = tokenizer.encode(UpperCAmelCase_ ,add_prefix_space=UpperCAmelCase_ )
_lowercase : Optional[int] = rust_tokenizer.encode(UpperCAmelCase_ )
self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ )
# Testing the unknown token
_lowercase : str = tokens + [rust_tokenizer.unk_token]
_lowercase : Optional[Any] = [14, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) ,UpperCAmelCase_ )
def lowerCamelCase__ ( self ,*UpperCAmelCase_ ,**UpperCAmelCase_ ):
# It's very difficult to mix/test pretokenization with byte-level
# And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string)
pass
def lowerCamelCase__ ( self ,UpperCAmelCase_=15 ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ):
_lowercase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ ,**UpperCAmelCase_ )
# Simple input
_lowercase : Dict = """This is a simple input"""
_lowercase : Any = ["""This is a simple input 1""", """This is a simple input 2"""]
_lowercase : Optional[Any] = ("""This is a simple input""", """This is a pair""")
_lowercase : Dict = [
("""This is a simple input 1""", """This is a simple input 2"""),
("""This is a simple pair 1""", """This is a simple pair 2"""),
]
# Simple input tests
self.assertRaises(UpperCAmelCase_ ,tokenizer_r.encode ,UpperCAmelCase_ ,max_length=UpperCAmelCase_ ,padding="""max_length""" )
# Simple input
self.assertRaises(UpperCAmelCase_ ,tokenizer_r.encode_plus ,UpperCAmelCase_ ,max_length=UpperCAmelCase_ ,padding="""max_length""" )
# Simple input
self.assertRaises(
UpperCAmelCase_ ,tokenizer_r.batch_encode_plus ,UpperCAmelCase_ ,max_length=UpperCAmelCase_ ,padding="""max_length""" ,)
# Pair input
self.assertRaises(UpperCAmelCase_ ,tokenizer_r.encode ,UpperCAmelCase_ ,max_length=UpperCAmelCase_ ,padding="""max_length""" )
# Pair input
self.assertRaises(UpperCAmelCase_ ,tokenizer_r.encode_plus ,UpperCAmelCase_ ,max_length=UpperCAmelCase_ ,padding="""max_length""" )
# Pair input
self.assertRaises(
UpperCAmelCase_ ,tokenizer_r.batch_encode_plus ,UpperCAmelCase_ ,max_length=UpperCAmelCase_ ,padding="""max_length""" ,)
def lowerCamelCase__ ( self ):
_lowercase : int = CodeGenTokenizer.from_pretrained(self.tmpdirname ,pad_token="""<pad>""" )
# Simple input
_lowercase : Optional[int] = """This is a simple input"""
_lowercase : List[Any] = ["""This is a simple input looooooooong""", """This is a simple input"""]
_lowercase : List[str] = ("""This is a simple input""", """This is a pair""")
_lowercase : str = [
("""This is a simple input loooooong""", """This is a simple input"""),
("""This is a simple pair loooooong""", """This is a simple pair"""),
]
_lowercase : Union[str, Any] = tokenizer.pad_token_id
_lowercase : Any = tokenizer(UpperCAmelCase_ ,padding="""max_length""" ,max_length=30 ,return_tensors="""np""" )
_lowercase : List[Any] = tokenizer(UpperCAmelCase_ ,padding=UpperCAmelCase_ ,truncate=UpperCAmelCase_ ,return_tensors="""np""" )
_lowercase : Union[str, Any] = tokenizer(*UpperCAmelCase_ ,padding="""max_length""" ,max_length=60 ,return_tensors="""np""" )
_lowercase : Optional[int] = tokenizer(UpperCAmelCase_ ,padding=UpperCAmelCase_ ,truncate=UpperCAmelCase_ ,return_tensors="""np""" )
# s
# test single string max_length padding
self.assertEqual(out_s["""input_ids"""].shape[-1] ,30 )
self.assertTrue(pad_token_id in out_s["""input_ids"""] )
self.assertTrue(0 in out_s["""attention_mask"""] )
# s2
# test automatic padding
self.assertEqual(out_sa["""input_ids"""].shape[-1] ,33 )
# long slice doesn't have padding
self.assertFalse(pad_token_id in out_sa["""input_ids"""][0] )
self.assertFalse(0 in out_sa["""attention_mask"""][0] )
# short slice does have padding
self.assertTrue(pad_token_id in out_sa["""input_ids"""][1] )
self.assertTrue(0 in out_sa["""attention_mask"""][1] )
# p
# test single pair max_length padding
self.assertEqual(out_p["""input_ids"""].shape[-1] ,60 )
self.assertTrue(pad_token_id in out_p["""input_ids"""] )
self.assertTrue(0 in out_p["""attention_mask"""] )
# p2
# test automatic padding pair
self.assertEqual(out_pa["""input_ids"""].shape[-1] ,52 )
# long slice pair doesn't have padding
self.assertFalse(pad_token_id in out_pa["""input_ids"""][0] )
self.assertFalse(0 in out_pa["""attention_mask"""][0] )
# short slice pair does have padding
self.assertTrue(pad_token_id in out_pa["""input_ids"""][1] )
self.assertTrue(0 in out_pa["""attention_mask"""][1] )
def lowerCamelCase__ ( self ):
_lowercase : str = """$$$"""
_lowercase : Optional[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname ,bos_token=UpperCAmelCase_ ,add_bos_token=UpperCAmelCase_ )
_lowercase : Tuple = """This is a simple input"""
_lowercase : Tuple = ["""This is a simple input 1""", """This is a simple input 2"""]
_lowercase : Union[str, Any] = tokenizer.bos_token_id
_lowercase : Optional[int] = tokenizer(UpperCAmelCase_ )
_lowercase : Optional[int] = tokenizer(UpperCAmelCase_ )
self.assertEqual(out_s.input_ids[0] ,UpperCAmelCase_ )
self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) )
_lowercase : Dict = tokenizer.decode(out_s.input_ids )
_lowercase : Dict = tokenizer.batch_decode(out_sa.input_ids )
self.assertEqual(decode_s.split()[0] ,UpperCAmelCase_ )
self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) )
@slow
def lowerCamelCase__ ( self ):
_lowercase : List[Any] = CodeGenTokenizer.from_pretrained("""Salesforce/codegen-350M-mono""" )
_lowercase : Union[str, Any] = """\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#"""
_lowercase : int = """\nif len_a > len_b: result = a\nelse: result = b"""
_lowercase : int = tokenizer.encode(UpperCAmelCase_ )
_lowercase : Any = ["""^#""", re.escape("""<|endoftext|>""" ), """^'''""", """^\"\"\"""", """\n\n\n"""]
_lowercase : Union[str, Any] = tokenizer.decode(UpperCAmelCase_ ,truncate_before_pattern=UpperCAmelCase_ )
self.assertEqual(UpperCAmelCase_ ,UpperCAmelCase_ )
def lowerCamelCase__ ( self ):
pass
| 600 |
"""simple docstring"""
import argparse
import os
import jax as jnp
import numpy as onp
import torch
import torch.nn as nn
from music_spectrogram_diffusion import inference
from tax import checkpoints
from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder
UpperCAmelCase: str = """base_with_context"""
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ):
_lowercase : Dict = nn.Parameter(torch.FloatTensor(weights["""token_embedder"""]["""embedding"""] ) )
_lowercase : Any = nn.Parameter(
torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=__UpperCAmelCase )
for lyr_num, lyr in enumerate(model.encoders ):
_lowercase : Optional[Any] = weights[F"""layers_{lyr_num}"""]
_lowercase : str = nn.Parameter(
torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) )
_lowercase : Optional[Any] = ly_weight["""attention"""]
_lowercase : Dict = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) )
_lowercase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) )
_lowercase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) )
_lowercase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) )
_lowercase : int = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) )
_lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) )
_lowercase : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) )
_lowercase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) )
_lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) )
return model
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ):
_lowercase : int = nn.Parameter(torch.FloatTensor(weights["""input_proj"""]["""kernel"""].T ) )
_lowercase : Optional[int] = nn.Parameter(
torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=__UpperCAmelCase )
for lyr_num, lyr in enumerate(model.encoders ):
_lowercase : int = weights[F"""layers_{lyr_num}"""]
_lowercase : Any = ly_weight["""attention"""]
_lowercase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) )
_lowercase : str = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) )
_lowercase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) )
_lowercase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) )
_lowercase : Optional[Any] = nn.Parameter(
torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""] ) )
_lowercase : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) )
_lowercase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) )
_lowercase : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) )
_lowercase : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) )
_lowercase : Union[str, Any] = nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""] ) )
return model
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ):
_lowercase : Dict = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense0"""]["""kernel"""].T ) )
_lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(weights["""time_emb_dense1"""]["""kernel"""].T ) )
_lowercase : Optional[int] = nn.Parameter(
torch.FloatTensor(weights["""Embed_0"""]["""embedding"""] ) , requires_grad=__UpperCAmelCase )
_lowercase : Optional[Any] = nn.Parameter(
torch.FloatTensor(weights["""continuous_inputs_projection"""]["""kernel"""].T ) )
for lyr_num, lyr in enumerate(model.decoders ):
_lowercase : List[Any] = weights[F"""layers_{lyr_num}"""]
_lowercase : Dict = nn.Parameter(
torch.FloatTensor(ly_weight["""pre_self_attention_layer_norm"""]["""scale"""] ) )
_lowercase : int = nn.Parameter(
torch.FloatTensor(ly_weight["""FiLMLayer_0"""]["""DenseGeneral_0"""]["""kernel"""].T ) )
_lowercase : List[Any] = ly_weight["""self_attention"""]
_lowercase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) )
_lowercase : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) )
_lowercase : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) )
_lowercase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) )
_lowercase : Union[str, Any] = ly_weight["""MultiHeadDotProductAttention_0"""]
_lowercase : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T ) )
_lowercase : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T ) )
_lowercase : Any = nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T ) )
_lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T ) )
_lowercase : List[str] = nn.Parameter(
torch.FloatTensor(ly_weight["""pre_cross_attention_layer_norm"""]["""scale"""] ) )
_lowercase : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""] ) )
_lowercase : Any = nn.Parameter(
torch.FloatTensor(ly_weight["""FiLMLayer_1"""]["""DenseGeneral_0"""]["""kernel"""].T ) )
_lowercase : str = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T ) )
_lowercase : Dict = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T ) )
_lowercase : List[str] = nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T ) )
_lowercase : str = nn.Parameter(torch.FloatTensor(weights["""decoder_norm"""]["""scale"""] ) )
_lowercase : Any = nn.Parameter(torch.FloatTensor(weights["""spec_out_dense"""]["""kernel"""].T ) )
return model
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase ):
_lowercase : Tuple = checkpoints.load_tax_checkpoint(args.checkpoint_path )
_lowercase : List[Any] = jnp.tree_util.tree_map(onp.array , __UpperCAmelCase )
_lowercase : int = [
"""from __gin__ import dynamic_registration""",
"""from music_spectrogram_diffusion.models.diffusion import diffusion_utils""",
"""diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0""",
"""diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()""",
]
_lowercase : List[Any] = os.path.join(args.checkpoint_path , """..""" , """config.gin""" )
_lowercase : Optional[int] = inference.parse_training_gin_file(__UpperCAmelCase , __UpperCAmelCase )
_lowercase : Optional[Any] = inference.InferenceModel(args.checkpoint_path , __UpperCAmelCase )
_lowercase : List[Any] = DDPMScheduler(beta_schedule="""squaredcos_cap_v2""" , variance_type="""fixed_large""" )
_lowercase : List[str] = SpectrogramNotesEncoder(
max_length=synth_model.sequence_length["""inputs"""] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="""gated-gelu""" , )
_lowercase : Dict = SpectrogramContEncoder(
input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["""targets_context"""] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="""gated-gelu""" , )
_lowercase : int = TaFilmDecoder(
input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["""targets_context"""] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , )
_lowercase : str = load_notes_encoder(ta_checkpoint["""target"""]["""token_encoder"""] , __UpperCAmelCase )
_lowercase : Dict = load_continuous_encoder(ta_checkpoint["""target"""]["""continuous_encoder"""] , __UpperCAmelCase )
_lowercase : List[str] = load_decoder(ta_checkpoint["""target"""]["""decoder"""] , __UpperCAmelCase )
_lowercase : Any = OnnxRuntimeModel.from_pretrained("""kashif/soundstream_mel_decoder""" )
_lowercase : str = SpectrogramDiffusionPipeline(
notes_encoder=__UpperCAmelCase , continuous_encoder=__UpperCAmelCase , decoder=__UpperCAmelCase , scheduler=__UpperCAmelCase , melgan=__UpperCAmelCase , )
if args.save:
pipe.save_pretrained(args.output_path )
if __name__ == "__main__":
UpperCAmelCase: Any = argparse.ArgumentParser()
parser.add_argument("""--output_path""", default=None, type=str, required=True, help="""Path to the converted model.""")
parser.add_argument(
"""--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not."""
)
parser.add_argument(
"""--checkpoint_path""",
default=F'{MODEL}/checkpoint_500000',
type=str,
required=False,
help="""Path to the original jax model checkpoint.""",
)
UpperCAmelCase: Optional[Any] = parser.parse_args()
main(args)
| 600 | 1 |
from __future__ import annotations
UpperCamelCase__ = {
'''A''': ['''B''', '''C''', '''E'''],
'''B''': ['''A''', '''D''', '''E'''],
'''C''': ['''A''', '''F''', '''G'''],
'''D''': ['''B'''],
'''E''': ['''A''', '''B''', '''D'''],
'''F''': ['''C'''],
'''G''': ['''C'''],
}
class A :
def __init__(self : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] ) -> None:
"""simple docstring"""
UpperCAmelCase__ = graph
# mapping node to its parent in resulting breadth first tree
UpperCAmelCase__ = {}
UpperCAmelCase__ = source_vertex
def lowercase_ (self : Optional[Any] ) -> None:
"""simple docstring"""
UpperCAmelCase__ = {self.source_vertex}
UpperCAmelCase__ = None
UpperCAmelCase__ = [self.source_vertex] # first in first out queue
while queue:
UpperCAmelCase__ = queue.pop(0 )
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(lowerCAmelCase__ )
UpperCAmelCase__ = vertex
queue.append(lowerCAmelCase__ )
def lowercase_ (self : Tuple , __UpperCAmelCase : Optional[Any] ) -> str:
"""simple docstring"""
if target_vertex == self.source_vertex:
return self.source_vertex
UpperCAmelCase__ = self.parent.get(lowerCAmelCase__ )
if target_vertex_parent is None:
UpperCAmelCase__ = (
f"""No path from vertex: {self.source_vertex} to vertex: {target_vertex}"""
)
raise ValueError(lowerCAmelCase__ )
return self.shortest_path(lowerCAmelCase__ ) + f"""->{target_vertex}"""
if __name__ == "__main__":
UpperCamelCase__ = Graph(graph, 'G')
g.breath_first_search()
print(g.shortest_path('D'))
print(g.shortest_path('G'))
print(g.shortest_path('Foo'))
| 486 |
"""simple docstring"""
def _SCREAMING_SNAKE_CASE ( _lowercase : list[int] ) ->float:
'''simple docstring'''
if not nums: # Makes sure that the list is not empty
raise ValueError("List is empty" )
a : Dict = sum(_lowercase ) / len(_lowercase ) # Calculate the average
return sum(abs(x - average ) for x in nums ) / len(_lowercase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 633 | 0 |
'''simple docstring'''
import argparse
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline
if __name__ == "__main__":
__lowercase : Union[str, Any] = argparse.ArgumentParser()
parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''')
parser.add_argument(
'''--txt2img_unclip''',
default='''kakaobrain/karlo-v1-alpha''',
type=str,
required=False,
help='''The pretrained txt2img unclip.''',
)
__lowercase : Union[str, Any] = parser.parse_args()
__lowercase : List[str] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip)
__lowercase : int = CLIPImageProcessor()
__lowercase : List[Any] = CLIPVisionModelWithProjection.from_pretrained('''openai/clip-vit-large-patch14''')
__lowercase : str = UnCLIPImageVariationPipeline(
decoder=txtaimg.decoder,
text_encoder=txtaimg.text_encoder,
tokenizer=txtaimg.tokenizer,
text_proj=txtaimg.text_proj,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
super_res_first=txtaimg.super_res_first,
super_res_last=txtaimg.super_res_last,
decoder_scheduler=txtaimg.decoder_scheduler,
super_res_scheduler=txtaimg.super_res_scheduler,
)
imgaimg.save_pretrained(args.dump_path)
| 719 |
'''simple docstring'''
from __future__ import annotations
def lowercase_ ( _lowercase , _lowercase , _lowercase , _lowercase ) -> None:
'''simple docstring'''
if (direction == 1 and array[indexa] > array[indexa]) or (
direction == 0 and array[indexa] < array[indexa]
):
lowerCamelCase_, lowerCamelCase_ : str = array[indexa], array[indexa]
def lowercase_ ( _lowercase , _lowercase , _lowercase , _lowercase ) -> None:
'''simple docstring'''
if length > 1:
lowerCamelCase_ : int = int(length / 2 )
for i in range(_lowercase , low + middle ):
comp_and_swap(_lowercase , _lowercase , i + middle , _lowercase )
bitonic_merge(_lowercase , _lowercase , _lowercase , _lowercase )
bitonic_merge(_lowercase , low + middle , _lowercase , _lowercase )
def lowercase_ ( _lowercase , _lowercase , _lowercase , _lowercase ) -> None:
'''simple docstring'''
if length > 1:
lowerCamelCase_ : Dict = int(length / 2 )
bitonic_sort(_lowercase , _lowercase , _lowercase , 1 )
bitonic_sort(_lowercase , low + middle , _lowercase , 0 )
bitonic_merge(_lowercase , _lowercase , _lowercase , _lowercase )
if __name__ == "__main__":
__lowercase : Any = input('''Enter numbers separated by a comma:\n''').strip()
__lowercase : Tuple = [int(item.strip()) for item in user_input.split(''',''')]
bitonic_sort(unsorted, 0, len(unsorted), 1)
print('''\nSorted array in ascending order is: ''', end='''''')
print(*unsorted, sep=''', ''')
bitonic_merge(unsorted, 0, len(unsorted), 0)
print('''Sorted array in descending order is: ''', end='''''')
print(*unsorted, sep=''', ''')
| 357 | 0 |
"""simple docstring"""
def UpperCamelCase (SCREAMING_SNAKE_CASE ):
UpperCamelCase : List[str] = len(SCREAMING_SNAKE_CASE )
UpperCamelCase : Dict = len(matrix[0] )
UpperCamelCase : str = min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
for row in range(SCREAMING_SNAKE_CASE ):
# Check if diagonal element is not zero
if matrix[row][row] != 0:
# Eliminate all the elements below the diagonal
for col in range(row + 1 , SCREAMING_SNAKE_CASE ):
UpperCamelCase : List[Any] = matrix[col][row] / matrix[row][row]
for i in range(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
matrix[col][i] -= multiplier * matrix[row][i]
else:
# Find a non-zero diagonal element to swap rows
UpperCamelCase : Union[str, Any] = True
for i in range(row + 1 , SCREAMING_SNAKE_CASE ):
if matrix[i][row] != 0:
UpperCamelCase , UpperCamelCase : Union[str, Any] = matrix[i], matrix[row]
UpperCamelCase : Any = False
break
if reduce:
rank -= 1
for i in range(SCREAMING_SNAKE_CASE ):
UpperCamelCase : Dict = matrix[i][rank]
# Reduce the row pointer by one to stay on the same row
row -= 1
return rank
if __name__ == "__main__":
import doctest
doctest.testmod()
| 102 |
"""simple docstring"""
import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple
from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available
from ...test_tokenization_common import TokenizerTesterMixin
if is_torch_available():
__magic_name__ : Any = """pt"""
elif is_tf_available():
__magic_name__ : Optional[Any] = """tf"""
else:
__magic_name__ : int = """jax"""
class lowercase__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
__lowerCAmelCase : Any = PerceiverTokenizer
__lowerCAmelCase : int = False
def _a ( self ):
'''simple docstring'''
super().setUp()
UpperCamelCase : List[Any] = PerceiverTokenizer()
tokenizer.save_pretrained(self.tmpdirname )
@cached_property
def _a ( self ):
'''simple docstring'''
return PerceiverTokenizer.from_pretrained("""deepmind/language-perceiver""" )
def _a ( self , **_A ):
'''simple docstring'''
return self.tokenizer_class.from_pretrained(self.tmpdirname , **_A )
def _a ( self , _A , _A=False , _A=2_0 , _A=5 ):
'''simple docstring'''
UpperCamelCase : Tuple = []
for i in range(len(_A ) ):
try:
UpperCamelCase : List[str] = tokenizer.decode([i] , clean_up_tokenization_spaces=_A )
except UnicodeDecodeError:
pass
toks.append((i, tok) )
UpperCamelCase : Dict = list(filter(lambda _A : re.match(r"""^[ a-zA-Z]+$""" , t[1] ) , _A ) )
UpperCamelCase : List[str] = list(filter(lambda _A : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_A ) , _A ) )
if max_length is not None and len(_A ) > max_length:
UpperCamelCase : int = toks[:max_length]
if min_length is not None and len(_A ) < min_length and len(_A ) > 0:
while len(_A ) < min_length:
UpperCamelCase : List[str] = toks + toks
# toks_str = [t[1] for t in toks]
UpperCamelCase : Any = [t[0] for t in toks]
# Ensure consistency
UpperCamelCase : List[str] = tokenizer.decode(_A , clean_up_tokenization_spaces=_A )
if " " not in output_txt and len(_A ) > 1:
UpperCamelCase : Optional[Any] = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_A )
+ """ """
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_A )
)
if with_prefix_space:
UpperCamelCase : Dict = """ """ + output_txt
UpperCamelCase : List[Any] = tokenizer.encode(_A , add_special_tokens=_A )
return output_txt, output_ids
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Any = self.perceiver_tokenizer
UpperCamelCase : str = """Unicode €."""
UpperCamelCase : Dict = tokenizer(_A )
UpperCamelCase : Optional[Any] = [4, 9_1, 1_1_6, 1_1_1, 1_0_5, 1_1_7, 1_0_6, 1_0_7, 3_8, 2_3_2, 1_3_6, 1_7_8, 5_2, 5]
self.assertEqual(encoded["""input_ids"""] , _A )
# decoding
UpperCamelCase : Optional[int] = tokenizer.decode(_A )
self.assertEqual(_A , """[CLS]Unicode €.[SEP]""" )
UpperCamelCase : str = tokenizer("""e è é ê ë""" )
UpperCamelCase : str = [4, 1_0_7, 3_8, 2_0_1, 1_7_4, 3_8, 2_0_1, 1_7_5, 3_8, 2_0_1, 1_7_6, 3_8, 2_0_1, 1_7_7, 5]
self.assertEqual(encoded["""input_ids"""] , _A )
# decoding
UpperCamelCase : Any = tokenizer.decode(_A )
self.assertEqual(_A , """[CLS]e è é ê ë[SEP]""" )
# encode/decode, but with `encode` instead of `__call__`
self.assertEqual(tokenizer.decode(tokenizer.encode("""e è é ê ë""" ) ) , """[CLS]e è é ê ë[SEP]""" )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Optional[int] = self.perceiver_tokenizer
UpperCamelCase : Optional[Any] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
# fmt: off
UpperCamelCase : List[Any] = [4, 7_1, 3_8, 1_1_4, 1_1_7, 1_1_6, 1_0_9, 3_8, 1_1_8, 1_0_3, 1_2_0, 1_0_3, 1_0_9, 1_2_0, 1_0_3, 1_1_8, 1_1_0, 3_8, 1_0_8, 1_1_7, 1_2_0, 3_8, 1_2_1, 1_2_3, 1_1_5, 1_1_5, 1_0_3, 1_2_0, 1_1_1, 1_2_8, 1_0_3, 1_2_2, 1_1_1, 1_1_7, 1_1_6, 5_2, 5, 0]
# fmt: on
UpperCamelCase : Dict = tokenizer(_A , padding=_A , return_tensors=_A )
self.assertIsInstance(_A , _A )
if FRAMEWORK != "jax":
UpperCamelCase : Dict = list(batch.input_ids.numpy()[0] )
else:
UpperCamelCase : Optional[int] = list(batch.input_ids.tolist()[0] )
self.assertListEqual(_A , _A )
self.assertEqual((2, 3_8) , batch.input_ids.shape )
self.assertEqual((2, 3_8) , batch.attention_mask.shape )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Any = self.perceiver_tokenizer
UpperCamelCase : Optional[int] = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""]
UpperCamelCase : Any = tokenizer(_A , padding=_A , return_tensors=_A )
# check if input_ids are returned and no decoder_input_ids
self.assertIn("""input_ids""" , _A )
self.assertIn("""attention_mask""" , _A )
self.assertNotIn("""decoder_input_ids""" , _A )
self.assertNotIn("""decoder_attention_mask""" , _A )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Optional[Any] = self.perceiver_tokenizer
UpperCamelCase : int = [
"""Summary of the text.""",
"""Another summary.""",
]
UpperCamelCase : int = tokenizer(
text_target=_A , max_length=3_2 , padding="""max_length""" , truncation=_A , return_tensors=_A )
self.assertEqual(3_2 , targets["""input_ids"""].shape[1] )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Any = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
self.assertNotEqual(tokenizer.model_max_length , 4_2 )
# Now let's start the test
UpperCamelCase : Any = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
# Isolate this from the other tests because we save additional tokens/etc
UpperCamelCase : int = tempfile.mkdtemp()
UpperCamelCase : Tuple = """ He is very happy, UNwant\u00E9d,running"""
UpperCamelCase : Dict = tokenizer.encode(_A , add_special_tokens=_A )
tokenizer.save_pretrained(_A )
UpperCamelCase : Any = tokenizer.__class__.from_pretrained(_A )
UpperCamelCase : Tuple = after_tokenizer.encode(_A , add_special_tokens=_A )
self.assertListEqual(_A , _A )
shutil.rmtree(_A )
UpperCamelCase : Union[str, Any] = self.get_tokenizers(model_max_length=4_2 )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
# Isolate this from the other tests because we save additional tokens/etc
UpperCamelCase : List[Any] = tempfile.mkdtemp()
UpperCamelCase : Union[str, Any] = """ He is very happy, UNwant\u00E9d,running"""
tokenizer.add_tokens(["""bim""", """bambam"""] )
UpperCamelCase : int = tokenizer.additional_special_tokens
additional_special_tokens.append("""new_additional_special_token""" )
tokenizer.add_special_tokens({"""additional_special_tokens""": additional_special_tokens} )
UpperCamelCase : List[str] = tokenizer.encode(_A , add_special_tokens=_A )
tokenizer.save_pretrained(_A )
UpperCamelCase : List[str] = tokenizer.__class__.from_pretrained(_A )
UpperCamelCase : Tuple = after_tokenizer.encode(_A , add_special_tokens=_A )
self.assertListEqual(_A , _A )
self.assertIn("""new_additional_special_token""" , after_tokenizer.additional_special_tokens )
self.assertEqual(after_tokenizer.model_max_length , 4_2 )
UpperCamelCase : Any = tokenizer.__class__.from_pretrained(_A , model_max_length=4_3 )
self.assertEqual(tokenizer.model_max_length , 4_3 )
shutil.rmtree(_A )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : int = []
if self.test_slow_tokenizer:
tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) )
if self.test_rust_tokenizer:
tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) )
for tokenizer_class, tokenizer_utils in tokenizer_list:
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer_utils.save_pretrained(_A )
with open(os.path.join(_A , """special_tokens_map.json""" ) , encoding="""utf-8""" ) as json_file:
UpperCamelCase : Union[str, Any] = json.load(_A )
with open(os.path.join(_A , """tokenizer_config.json""" ) , encoding="""utf-8""" ) as json_file:
UpperCamelCase : List[Any] = json.load(_A )
UpperCamelCase : Optional[int] = [f"""<extra_id_{i}>""" for i in range(1_2_5 )]
UpperCamelCase : List[Any] = added_tokens_extra_ids + [
"""an_additional_special_token"""
]
UpperCamelCase : int = added_tokens_extra_ids + [
"""an_additional_special_token"""
]
with open(os.path.join(_A , """special_tokens_map.json""" ) , """w""" , encoding="""utf-8""" ) as outfile:
json.dump(_A , _A )
with open(os.path.join(_A , """tokenizer_config.json""" ) , """w""" , encoding="""utf-8""" ) as outfile:
json.dump(_A , _A )
# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
# "special_tokens_map.json" files
UpperCamelCase : Tuple = tokenizer_class.from_pretrained(
_A , )
self.assertIn(
"""an_additional_special_token""" , tokenizer_without_change_in_init.additional_special_tokens )
self.assertEqual(
["""an_additional_special_token"""] , tokenizer_without_change_in_init.convert_ids_to_tokens(
tokenizer_without_change_in_init.convert_tokens_to_ids(["""an_additional_special_token"""] ) ) , )
# Now we test that we can change the value of additional_special_tokens in the from_pretrained
UpperCamelCase : List[str] = added_tokens_extra_ids + [AddedToken("""a_new_additional_special_token""" , lstrip=_A )]
UpperCamelCase : Optional[Any] = tokenizer_class.from_pretrained(
_A , additional_special_tokens=_A , )
self.assertIn("""a_new_additional_special_token""" , tokenizer.additional_special_tokens )
self.assertEqual(
["""a_new_additional_special_token"""] , tokenizer.convert_ids_to_tokens(
tokenizer.convert_tokens_to_ids(["""a_new_additional_special_token"""] ) ) , )
def _a ( self ):
'''simple docstring'''
UpperCamelCase : Dict = self.perceiver_tokenizer
self.assertEqual(tokenizer.decode([1_7_8] ) , """�""" )
def _a ( self ):
'''simple docstring'''
pass
def _a ( self ):
'''simple docstring'''
pass
def _a ( self ):
'''simple docstring'''
pass
def _a ( self ):
'''simple docstring'''
pass
def _a ( self ):
'''simple docstring'''
UpperCamelCase : List[Any] = self.get_tokenizers(fast=_A , do_lower_case=_A )
for tokenizer in tokenizers:
with self.subTest(f"""{tokenizer.__class__.__name__}""" ):
UpperCamelCase : Optional[Any] = ["""[CLS]""", """t""", """h""", """i""", """s""", """ """, """i""", """s""", """ """, """a""", """ """, """t""", """e""", """s""", """t""", """[SEP]"""]
UpperCamelCase : Dict = tokenizer.convert_tokens_to_string(_A )
self.assertIsInstance(_A , _A )
| 102 | 1 |
"""simple docstring"""
import os
import pytest
from datasets import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
)
UpperCAmelCase =pytest.mark.integration
@pytest.mark.parametrize("""path""" , ["""paws""", """csv"""] )
def _A ( _a : str , _a : int ):
"""simple docstring"""
inspect_dataset(_a , _a )
A = path + """.py"""
assert script_name in os.listdir(_a )
assert "__pycache__" not in os.listdir(_a )
@pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning""" )
@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" )
@pytest.mark.parametrize("""path""" , ["""accuracy"""] )
def _A ( _a : str , _a : Dict ):
"""simple docstring"""
inspect_metric(_a , _a )
A = path + """.py"""
assert script_name in os.listdir(_a )
assert "__pycache__" not in os.listdir(_a )
@pytest.mark.parametrize(
"""path, config_name, expected_splits""" , [
("""squad""", """plain_text""", ["""train""", """validation"""]),
("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]),
("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]),
] , )
def _A ( _a : Any , _a : List[Any] , _a : Tuple ):
"""simple docstring"""
A = get_dataset_config_info(_a , config_name=_a )
assert info.config_name == config_name
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
"""path, config_name, expected_exception""" , [
("""paws""", None, ValueError),
] , )
def _A ( _a : Optional[Any] , _a : Dict , _a : List[Any] ):
"""simple docstring"""
with pytest.raises(_a ):
get_dataset_config_info(_a , config_name=_a )
@pytest.mark.parametrize(
"""path, expected""" , [
("""squad""", """plain_text"""),
("""acronym_identification""", """default"""),
("""lhoestq/squad""", """plain_text"""),
("""lhoestq/test""", """default"""),
("""lhoestq/demo1""", """lhoestq--demo1"""),
("""dalle-mini/wit""", """dalle-mini--wit"""),
] , )
def _A ( _a : str , _a : Any ):
"""simple docstring"""
A = get_dataset_config_names(_a )
assert expected in config_names
@pytest.mark.parametrize(
"""path, expected_configs, expected_splits_in_first_config""" , [
("""squad""", ["""plain_text"""], ["""train""", """validation"""]),
("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]),
("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]),
] , )
def _A ( _a : Optional[int] , _a : Any , _a : Dict ):
"""simple docstring"""
A = get_dataset_infos(_a )
assert list(infos.keys() ) == expected_configs
A = expected_configs[0]
assert expected_config in infos
A = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits_in_first_config
@pytest.mark.parametrize(
"""path, expected_config, expected_splits""" , [
("""squad""", """plain_text""", ["""train""", """validation"""]),
("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]),
("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]),
] , )
def _A ( _a : Optional[int] , _a : Any , _a : List[Any] ):
"""simple docstring"""
A = get_dataset_infos(_a )
assert expected_config in infos
A = infos[expected_config]
assert info.config_name == expected_config
assert list(info.splits.keys() ) == expected_splits
@pytest.mark.parametrize(
"""path, config_name, expected_exception""" , [
("""paws""", None, ValueError),
] , )
def _A ( _a : str , _a : Union[str, Any] , _a : Any ):
"""simple docstring"""
with pytest.raises(_a ):
get_dataset_split_names(_a , config_name=_a )
| 255 |
"""simple docstring"""
def _A ( _a : int | float | str ):
"""simple docstring"""
try:
A = float(_a )
except ValueError:
raise ValueError("""Please enter a valid number""" )
A = decimal - int(_a )
if fractional_part == 0:
return int(_a ), 1
else:
A = len(str(_a ).split(""".""" )[1] )
A = int(decimal * (1_0**number_of_frac_digits) )
A = 1_0**number_of_frac_digits
A , A = denominator, numerator
while True:
A = dividend % divisor
if remainder == 0:
break
A , A = divisor, remainder
A , A = numerator / divisor, denominator / divisor
return int(_a ), int(_a )
if __name__ == "__main__":
print(f"""{decimal_to_fraction(2) = }""")
print(f"""{decimal_to_fraction(89.0) = }""")
print(f"""{decimal_to_fraction("67") = }""")
print(f"""{decimal_to_fraction("45.0") = }""")
print(f"""{decimal_to_fraction(1.5) = }""")
print(f"""{decimal_to_fraction("6.25") = }""")
print(f"""{decimal_to_fraction("78td") = }""")
| 255 | 1 |
"""simple docstring"""
A : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
A : Dict = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
A : str = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
}
def snake_case__ ( _snake_case : int , _snake_case : int , _snake_case : int ):
"""simple docstring"""
assert len(str(_snake_case ) ) > 2, "year should be in YYYY format"
assert 1 <= month <= 12, "month should be between 1 to 12"
assert 1 <= day <= 31, "day should be between 1 to 31"
# Doomsday algorithm:
UpperCamelCase__ = year // 1_00
UpperCamelCase__ = (5 * (century % 4) + 2) % 7
UpperCamelCase__ = year % 1_00
UpperCamelCase__ = centurian % 12
UpperCamelCase__ = (
(centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor
) % 7
UpperCamelCase__ = (
DOOMSDAY_NOT_LEAP[month - 1]
if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0)
else DOOMSDAY_LEAP[month - 1]
)
UpperCamelCase__ = (dooms_day + day - day_anchor) % 7
return WEEK_DAY_NAMES[week_day]
if __name__ == "__main__":
import doctest
doctest.testmod() | 516 | """simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
A : List[Any] = {
'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
A : int = [
'LILT_PRETRAINED_MODEL_ARCHIVE_LIST',
'LiltForQuestionAnswering',
'LiltForSequenceClassification',
'LiltForTokenClassification',
'LiltModel',
'LiltPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_lilt import (
LILT_PRETRAINED_MODEL_ARCHIVE_LIST,
LiltForQuestionAnswering,
LiltForSequenceClassification,
LiltForTokenClassification,
LiltModel,
LiltPreTrainedModel,
)
else:
import sys
A : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 516 | 1 |
"""simple docstring"""
import numpy as np
def __lowerCamelCase ( lowerCAmelCase__ ):
return 1 / (1 + np.exp(-vector ))
def __lowerCamelCase ( lowerCAmelCase__ ):
return vector * sigmoid(lowerCAmelCase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 715 |
"""simple docstring"""
from PIL import Image
def __lowerCamelCase ( lowerCAmelCase__ ):
A__ , A__ = image.size
A__ = 0
A__ = image.load()
for i in range(lowerCAmelCase__ ):
for j in range(lowerCAmelCase__ ):
A__ = pixels[j, i]
mean += pixel
mean //= width * height
for j in range(lowerCAmelCase__ ):
for i in range(lowerCAmelCase__ ):
A__ = 255 if pixels[i, j] > mean else 0
return image
if __name__ == "__main__":
SCREAMING_SNAKE_CASE : Dict = mean_threshold(Image.open('''path_to_image''').convert('''L'''))
image.save('''output_image_path''')
| 554 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A = logging.get_logger(__name__)
A = {
"""google/vivit-b-16x2-kinetics400""": (
"""https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json"""
),
# See all Vivit models at https://huggingface.co/models?filter=vivit
}
class a__ ( __magic_name__ ):
lowercase_ = "vivit"
def __init__( self : Union[str, Any] , UpperCamelCase_ : Dict=224 , UpperCamelCase_ : Optional[Any]=32 , UpperCamelCase_ : List[Any]=[2, 16, 16] , UpperCamelCase_ : str=3 , UpperCamelCase_ : Tuple=768 , UpperCamelCase_ : Tuple=12 , UpperCamelCase_ : Any=12 , UpperCamelCase_ : Any=3072 , UpperCamelCase_ : int="gelu_fast" , UpperCamelCase_ : Any=0.0 , UpperCamelCase_ : Tuple=0.0 , UpperCamelCase_ : Optional[int]=0.02 , UpperCamelCase_ : Tuple=1e-06 , UpperCamelCase_ : Optional[int]=True , **UpperCamelCase_ : int , ):
"""simple docstring"""
__UpperCAmelCase : List[Any] = hidden_size
__UpperCAmelCase : Optional[Any] = num_hidden_layers
__UpperCAmelCase : Any = num_attention_heads
__UpperCAmelCase : Tuple = intermediate_size
__UpperCAmelCase : int = hidden_act
__UpperCAmelCase : Tuple = hidden_dropout_prob
__UpperCAmelCase : Dict = attention_probs_dropout_prob
__UpperCAmelCase : Optional[Any] = initializer_range
__UpperCAmelCase : List[Any] = layer_norm_eps
__UpperCAmelCase : Dict = image_size
__UpperCAmelCase : Optional[Any] = num_frames
__UpperCAmelCase : List[Any] = tubelet_size
__UpperCAmelCase : Optional[Any] = num_channels
__UpperCAmelCase : Optional[int] = qkv_bias
super().__init__(**UpperCamelCase_)
| 77 | import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
import pytest
import transformers
from transformers import (
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
AutoTokenizer,
BertConfig,
BertTokenizer,
BertTokenizerFast,
CTRLTokenizer,
GPTaTokenizer,
GPTaTokenizerFast,
PreTrainedTokenizerFast,
RobertaTokenizer,
RobertaTokenizerFast,
is_tokenizers_available,
)
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.auto.tokenization_auto import (
TOKENIZER_MAPPING,
get_tokenizer_config,
tokenizer_class_from_name,
)
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import (
DUMMY_DIFF_TOKENIZER_IDENTIFIER,
DUMMY_UNKNOWN_IDENTIFIER,
SMALL_MODEL_IDENTIFIER,
RequestCounter,
require_tokenizers,
slow,
)
sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_tokenization import CustomTokenizer # noqa E402
if is_tokenizers_available():
from test_module.custom_tokenization_fast import CustomTokenizerFast
class UpperCamelCase ( unittest.TestCase ):
def UpperCamelCase_ ( self : Any ):
"""simple docstring"""
__snake_case = 0
@slow
def UpperCamelCase_ ( self : Union[str, Any] ):
"""simple docstring"""
for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsNotNone(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,(BertTokenizer, BertTokenizerFast) )
self.assertGreater(len(_lowerCAmelCase ) ,0 )
for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsNotNone(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,(GPTaTokenizer, GPTaTokenizerFast) )
self.assertGreater(len(_lowerCAmelCase ) ,0 )
def UpperCamelCase_ ( self : int ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,(BertTokenizer, BertTokenizerFast) )
self.assertEqual(tokenizer.vocab_size ,12 )
def UpperCamelCase_ ( self : List[str] ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,(RobertaTokenizer, RobertaTokenizerFast) )
self.assertEqual(tokenizer.vocab_size ,20 )
def UpperCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
__snake_case = AutoConfig.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
# Check that tokenizer_type ≠ model_type
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,config=_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,(BertTokenizer, BertTokenizerFast) )
self.assertEqual(tokenizer.vocab_size ,12 )
def UpperCamelCase_ ( self : List[Any] ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("./tests/fixtures/vocab.txt" ,os.path.join(_lowerCAmelCase ,"vocab.txt" ) )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,tokenizer_type="bert" ,use_fast=_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("./tests/fixtures/vocab.json" ,os.path.join(_lowerCAmelCase ,"vocab.json" ) )
shutil.copy("./tests/fixtures/merges.txt" ,os.path.join(_lowerCAmelCase ,"merges.txt" ) )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,tokenizer_type="gpt2" ,use_fast=_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
@require_tokenizers
def UpperCamelCase_ ( self : Tuple ):
"""simple docstring"""
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("./tests/fixtures/vocab.txt" ,os.path.join(_lowerCAmelCase ,"vocab.txt" ) )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,tokenizer_type="bert" )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmp_dir:
shutil.copy("./tests/fixtures/vocab.json" ,os.path.join(_lowerCAmelCase ,"vocab.json" ) )
shutil.copy("./tests/fixtures/merges.txt" ,os.path.join(_lowerCAmelCase ,"merges.txt" ) )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,tokenizer_type="gpt2" )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
def UpperCamelCase_ ( self : Dict ):
"""simple docstring"""
with pytest.raises(_lowerCAmelCase ):
AutoTokenizer.from_pretrained("./" ,tokenizer_type="xxx" )
@require_tokenizers
def UpperCamelCase_ ( self : List[str] ):
"""simple docstring"""
for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
__snake_case = tokenizer_class.from_pretrained("wietsedv/bert-base-dutch-cased" )
self.assertIsInstance(_lowerCAmelCase ,(BertTokenizer, BertTokenizerFast) )
if isinstance(_lowerCAmelCase ,_lowerCAmelCase ):
self.assertEqual(tokenizer.basic_tokenizer.do_lower_case ,_lowerCAmelCase )
else:
self.assertEqual(tokenizer.do_lower_case ,_lowerCAmelCase )
self.assertEqual(tokenizer.model_max_length ,512 )
@require_tokenizers
def UpperCamelCase_ ( self : Tuple ):
"""simple docstring"""
for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
with self.assertRaisesRegex(
_lowerCAmelCase ,"julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier" ,):
__snake_case = tokenizer_class.from_pretrained("julien-c/herlolip-not-exists" )
def UpperCamelCase_ ( self : str ):
"""simple docstring"""
__snake_case = TOKENIZER_MAPPING.values()
__snake_case = []
for slow_tok, fast_tok in tokenizers:
if slow_tok is not None:
tokenizer_names.append(slow_tok.__name__ )
if fast_tok is not None:
tokenizer_names.append(fast_tok.__name__ )
for tokenizer_name in tokenizer_names:
# must find the right class
tokenizer_class_from_name(_lowerCAmelCase )
@require_tokenizers
def UpperCamelCase_ ( self : Dict ):
"""simple docstring"""
self.assertIsInstance(AutoTokenizer.from_pretrained("bert-base-cased" ,use_fast=_lowerCAmelCase ) ,_lowerCAmelCase )
self.assertIsInstance(AutoTokenizer.from_pretrained("bert-base-cased" ) ,_lowerCAmelCase )
@require_tokenizers
def UpperCamelCase_ ( self : Dict ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("distilbert-base-uncased" ,do_lower_case=_lowerCAmelCase )
__snake_case = "Hello, world. How are you?"
__snake_case = tokenizer.tokenize(_lowerCAmelCase )
self.assertEqual("[UNK]" ,tokens[0] )
__snake_case = AutoTokenizer.from_pretrained("microsoft/mpnet-base" ,do_lower_case=_lowerCAmelCase )
__snake_case = tokenizer.tokenize(_lowerCAmelCase )
self.assertEqual("[UNK]" ,tokens[0] )
@require_tokenizers
def UpperCamelCase_ ( self : Optional[int] ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("robot-test/dummy-tokenizer-fast-with-model-config" )
self.assertEqual(type(_lowerCAmelCase ) ,_lowerCAmelCase )
self.assertEqual(tokenizer.model_max_length ,512 )
self.assertEqual(tokenizer.vocab_size ,30_000 )
self.assertEqual(tokenizer.unk_token ,"[UNK]" )
self.assertEqual(tokenizer.padding_side ,"right" )
self.assertEqual(tokenizer.truncation_side ,"right" )
def UpperCamelCase_ ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,(BertTokenizer, BertTokenizerFast) )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,tokenizer.__class__ )
self.assertEqual(tokenizera.vocab_size ,12 )
def UpperCamelCase_ ( self : Any ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("ctrl" )
# There is no fast CTRL so this always gives us a slow tokenizer.
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
def UpperCamelCase_ ( self : Tuple ):
"""simple docstring"""
__snake_case = get_tokenizer_config("bert-base-cased" )
__snake_case = config.pop("_commit_hash" ,_lowerCAmelCase )
# If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
self.assertEqual(_lowerCAmelCase ,{"do_lower_case": False} )
# This model does not have a tokenizer_config so we get back an empty dict.
__snake_case = get_tokenizer_config(_lowerCAmelCase )
self.assertDictEqual(_lowerCAmelCase ,{} )
# A tokenizer saved with `save_pretrained` always creates a tokenizer config.
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = get_tokenizer_config(_lowerCAmelCase )
# Check the class of the tokenizer was properly saved (note that it always saves the slow class).
self.assertEqual(config["tokenizer_class"] ,"BertTokenizer" )
def UpperCamelCase_ ( self : str ):
"""simple docstring"""
try:
AutoConfig.register("custom" ,_lowerCAmelCase )
AutoTokenizer.register(_lowerCAmelCase ,slow_tokenizer_class=_lowerCAmelCase )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_lowerCAmelCase ):
AutoTokenizer.register(_lowerCAmelCase ,slow_tokenizer_class=_lowerCAmelCase )
__snake_case = CustomTokenizer.from_pretrained(_lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
@require_tokenizers
def UpperCamelCase_ ( self : List[str] ):
"""simple docstring"""
try:
AutoConfig.register("custom" ,_lowerCAmelCase )
# Can register in two steps
AutoTokenizer.register(_lowerCAmelCase ,slow_tokenizer_class=_lowerCAmelCase )
self.assertEqual(TOKENIZER_MAPPING[CustomConfig] ,(CustomTokenizer, None) )
AutoTokenizer.register(_lowerCAmelCase ,fast_tokenizer_class=_lowerCAmelCase )
self.assertEqual(TOKENIZER_MAPPING[CustomConfig] ,(CustomTokenizer, CustomTokenizerFast) )
del TOKENIZER_MAPPING._extra_content[CustomConfig]
# Can register in one step
AutoTokenizer.register(
_lowerCAmelCase ,slow_tokenizer_class=_lowerCAmelCase ,fast_tokenizer_class=_lowerCAmelCase )
self.assertEqual(TOKENIZER_MAPPING[CustomConfig] ,(CustomTokenizer, CustomTokenizerFast) )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(_lowerCAmelCase ):
AutoTokenizer.register(_lowerCAmelCase ,fast_tokenizer_class=_lowerCAmelCase )
# We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
# and that model does not have a tokenizer.json
with tempfile.TemporaryDirectory() as tmp_dir:
__snake_case = BertTokenizerFast.from_pretrained(_lowerCAmelCase )
bert_tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = CustomTokenizerFast.from_pretrained(_lowerCAmelCase )
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,use_fast=_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase ,_lowerCAmelCase )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
def UpperCamelCase_ ( self : Any ):
"""simple docstring"""
with self.assertRaises(_lowerCAmelCase ):
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" )
# If remote code is disabled, we can't load this config.
with self.assertRaises(_lowerCAmelCase ):
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase )
self.assertTrue(tokenizer.special_attribute_present )
# Test tokenizer can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,trust_remote_code=_lowerCAmelCase )
self.assertTrue(reloaded_tokenizer.special_attribute_present )
if is_tokenizers_available():
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizerFast" )
self.assertEqual(reloaded_tokenizer.__class__.__name__ ,"NewTokenizerFast" )
# Test we can also load the slow version
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase ,use_fast=_lowerCAmelCase )
self.assertTrue(tokenizer.special_attribute_present )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
# Test tokenizer can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(_lowerCAmelCase )
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,trust_remote_code=_lowerCAmelCase ,use_fast=_lowerCAmelCase )
self.assertEqual(reloaded_tokenizer.__class__.__name__ ,"NewTokenizer" )
self.assertTrue(reloaded_tokenizer.special_attribute_present )
else:
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
self.assertEqual(reloaded_tokenizer.__class__.__name__ ,"NewTokenizer" )
@require_tokenizers
def UpperCamelCase_ ( self : Optional[Any] ):
"""simple docstring"""
class UpperCamelCase ( snake_case__ ):
__UpperCamelCase = False
class UpperCamelCase ( snake_case__ ):
__UpperCamelCase = NewTokenizer
__UpperCamelCase = False
try:
AutoConfig.register("custom" ,_lowerCAmelCase )
AutoTokenizer.register(_lowerCAmelCase ,slow_tokenizer_class=_lowerCAmelCase )
AutoTokenizer.register(_lowerCAmelCase ,fast_tokenizer_class=_lowerCAmelCase )
# If remote code is not set, the default is to use local
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizerFast" )
self.assertFalse(tokenizer.special_attribute_present )
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/test_dynamic_tokenizer" ,use_fast=_lowerCAmelCase )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
self.assertFalse(tokenizer.special_attribute_present )
# If remote code is disabled, we load the local one.
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizerFast" )
self.assertFalse(tokenizer.special_attribute_present )
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase ,use_fast=_lowerCAmelCase )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
self.assertFalse(tokenizer.special_attribute_present )
# If remote is enabled, we load from the Hub
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizerFast" )
self.assertTrue(tokenizer.special_attribute_present )
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer" ,trust_remote_code=_lowerCAmelCase ,use_fast=_lowerCAmelCase )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
self.assertTrue(tokenizer.special_attribute_present )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
def UpperCamelCase_ ( self : List[Any] ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer_legacy" ,trust_remote_code=_lowerCAmelCase )
self.assertTrue(tokenizer.special_attribute_present )
if is_tokenizers_available():
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizerFast" )
# Test we can also load the slow version
__snake_case = AutoTokenizer.from_pretrained(
"hf-internal-testing/test_dynamic_tokenizer_legacy" ,trust_remote_code=_lowerCAmelCase ,use_fast=_lowerCAmelCase )
self.assertTrue(tokenizer.special_attribute_present )
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
else:
self.assertEqual(tokenizer.__class__.__name__ ,"NewTokenizer" )
def UpperCamelCase_ ( self : Any ):
"""simple docstring"""
with self.assertRaisesRegex(
_lowerCAmelCase ,"bert-base is not a local folder and is not a valid model identifier" ):
__snake_case = AutoTokenizer.from_pretrained("bert-base" )
def UpperCamelCase_ ( self : Union[str, Any] ):
"""simple docstring"""
with self.assertRaisesRegex(
_lowerCAmelCase ,r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
__snake_case = AutoTokenizer.from_pretrained(_lowerCAmelCase ,revision="aaaaaa" )
def UpperCamelCase_ ( self : Dict ):
"""simple docstring"""
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
with RequestCounter() as counter:
__snake_case = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" )
self.assertEqual(counter.get_request_count ,0 )
self.assertEqual(counter.head_request_count ,1 )
self.assertEqual(counter.other_request_count ,0 )
| 524 | 0 |
'''simple docstring'''
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import jax
import jaxlib
__A : Any = get_logger()
__A : Optional[dict] = None
class lowercase ( TensorFormatter[Mapping, "jax.Array", Mapping] ):
'''simple docstring'''
def __init__( self : str , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Dict=None , **__lowerCamelCase : str ) -> List[Any]:
'''simple docstring'''
super().__init__(features=__lowerCamelCase )
import jax
from jaxlib.xla_client import Device
if isinstance(__lowerCamelCase , __lowerCamelCase ):
raise ValueError(
f'''Expected {device} to be a `str` not {type(__lowerCamelCase )}, as `jaxlib.xla_extension.Device` '''
"is not serializable neither with `pickle` nor with `dill`. Instead you can surround "
"the device with `str()` to get its string identifier that will be internally mapped "
"to the actual `jaxlib.xla_extension.Device`." )
lowerCamelCase__ = device if isinstance(__lowerCamelCase , __lowerCamelCase ) else str(jax.devices()[0] )
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
lowerCamelCase__ = self._map_devices_to_str()
if self.device not in list(DEVICE_MAPPING.keys() ):
logger.warning(
f'''Device with string identifier {self.device} not listed among the available '''
f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default '''
f'''device: {str(jax.devices()[0] )}.''' )
lowerCamelCase__ = str(jax.devices()[0] )
lowerCamelCase__ = jnp_array_kwargs
@staticmethod
def a__ ( ) -> Dict[str, "jaxlib.xla_extension.Device"]:
'''simple docstring'''
import jax
return {str(__lowerCamelCase ): device for device in jax.devices()}
def a__ ( self : Optional[Any] , __lowerCamelCase : Optional[int] ) -> List[str]:
'''simple docstring'''
import jax
import jax.numpy as jnp
if isinstance(__lowerCamelCase , __lowerCamelCase ) and column:
if all(
isinstance(__lowerCamelCase , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ):
return jnp.stack(__lowerCamelCase , axis=0 )
return column
def a__ ( self : List[Any] , __lowerCamelCase : List[Any] ) -> Optional[int]:
'''simple docstring'''
import jax
import jax.numpy as jnp
if isinstance(__lowerCamelCase , (str, bytes, type(__lowerCamelCase )) ):
return value
elif isinstance(__lowerCamelCase , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ):
return value.tolist()
lowerCamelCase__ = {}
if isinstance(__lowerCamelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ):
# the default int precision depends on the jax config
# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
if jax.config.jax_enable_xaa:
lowerCamelCase__ = {"dtype": jnp.intaa}
else:
lowerCamelCase__ = {"dtype": jnp.intaa}
elif isinstance(__lowerCamelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ):
lowerCamelCase__ = {"dtype": jnp.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(__lowerCamelCase , PIL.Image.Image ):
lowerCamelCase__ = np.asarray(__lowerCamelCase )
# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
# with `pickle` nor with `dill`, so we need to use a global variable instead
global DEVICE_MAPPING
if DEVICE_MAPPING is None:
lowerCamelCase__ = self._map_devices_to_str()
with jax.default_device(DEVICE_MAPPING[self.device] ):
# calling jnp.array on a np.ndarray does copy the data
# see https://github.com/google/jax/issues/4486
return jnp.array(__lowerCamelCase , **{**default_dtype, **self.jnp_array_kwargs} )
def a__ ( self : List[str] , __lowerCamelCase : Optional[Any] ) -> Dict:
'''simple docstring'''
import jax
# support for torch, tf, jax etc.
if config.TORCH_AVAILABLE and "torch" in sys.modules:
import torch
if isinstance(__lowerCamelCase , torch.Tensor ):
return self._tensorize(data_struct.detach().cpu().numpy()[()] )
if hasattr(__lowerCamelCase , "__array__" ) and not isinstance(__lowerCamelCase , jax.Array ):
lowerCamelCase__ = data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(__lowerCamelCase , np.ndarray ):
if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(__lowerCamelCase ) for substruct in data_struct] )
elif isinstance(__lowerCamelCase , (list, tuple) ):
return self._consolidate([self.recursive_tensorize(__lowerCamelCase ) for substruct in data_struct] )
return self._tensorize(__lowerCamelCase )
def a__ ( self : Any , __lowerCamelCase : dict ) -> int:
'''simple docstring'''
return map_nested(self._recursive_tensorize , __lowerCamelCase , map_list=__lowerCamelCase )
def a__ ( self : Union[str, Any] , __lowerCamelCase : pa.Table ) -> Mapping:
'''simple docstring'''
lowerCamelCase__ = self.numpy_arrow_extractor().extract_row(__lowerCamelCase )
lowerCamelCase__ = self.python_features_decoder.decode_row(__lowerCamelCase )
return self.recursive_tensorize(__lowerCamelCase )
def a__ ( self : List[Any] , __lowerCamelCase : pa.Table ) -> "jax.Array":
'''simple docstring'''
lowerCamelCase__ = self.numpy_arrow_extractor().extract_column(__lowerCamelCase )
lowerCamelCase__ = self.python_features_decoder.decode_column(__lowerCamelCase , pa_table.column_names[0] )
lowerCamelCase__ = self.recursive_tensorize(__lowerCamelCase )
lowerCamelCase__ = self._consolidate(__lowerCamelCase )
return column
def a__ ( self : List[str] , __lowerCamelCase : pa.Table ) -> Mapping:
'''simple docstring'''
lowerCamelCase__ = self.numpy_arrow_extractor().extract_batch(__lowerCamelCase )
lowerCamelCase__ = self.python_features_decoder.decode_batch(__lowerCamelCase )
lowerCamelCase__ = self.recursive_tensorize(__lowerCamelCase )
for column_name in batch:
lowerCamelCase__ = self._consolidate(batch[column_name] )
return batch | 715 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
__A : Tuple = {
"""configuration_deberta""": ["""DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DebertaConfig""", """DebertaOnnxConfig"""],
"""tokenization_deberta""": ["""DebertaTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : int = ["""DebertaTokenizerFast"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : str = [
"""DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""DebertaForMaskedLM""",
"""DebertaForQuestionAnswering""",
"""DebertaForSequenceClassification""",
"""DebertaForTokenClassification""",
"""DebertaModel""",
"""DebertaPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__A : Union[str, Any] = [
"""TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFDebertaForMaskedLM""",
"""TFDebertaForQuestionAnswering""",
"""TFDebertaForSequenceClassification""",
"""TFDebertaForTokenClassification""",
"""TFDebertaModel""",
"""TFDebertaPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig
from .tokenization_deberta import DebertaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_deberta_fast import DebertaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deberta import (
DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
DebertaForMaskedLM,
DebertaForQuestionAnswering,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaModel,
DebertaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deberta import (
TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDebertaForMaskedLM,
TFDebertaForQuestionAnswering,
TFDebertaForSequenceClassification,
TFDebertaForTokenClassification,
TFDebertaModel,
TFDebertaPreTrainedModel,
)
else:
import sys
__A : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 187 | 0 |
"""simple docstring"""
from __future__ import annotations
def lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )-> tuple[float, list[float]]:
"""simple docstring"""
UpperCamelCase = list(range(len(UpperCAmelCase_ ) ) )
UpperCamelCase = [v / w for v, w in zip(UpperCAmelCase_ , UpperCAmelCase_ )]
index.sort(key=lambda UpperCAmelCase_ : ratio[i] , reverse=UpperCAmelCase_ )
UpperCamelCase = 0
UpperCamelCase = [0] * len(UpperCAmelCase_ )
for i in index:
if weight[i] <= capacity:
UpperCamelCase = 1
max_value += value[i]
capacity -= weight[i]
else:
UpperCamelCase = capacity / weight[i]
max_value += value[i] * capacity / weight[i]
break
return max_value, fractions
if __name__ == "__main__":
import doctest
doctest.testmod()
| 554 |
"""simple docstring"""
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
SCREAMING_SNAKE_CASE = """src/transformers"""
# This is to make sure the transformers module imported is the one in the repo.
SCREAMING_SNAKE_CASE = direct_transformers_import(PATH_TO_TRANSFORMERS)
SCREAMING_SNAKE_CASE = transformers.models.auto.configuration_auto.CONFIG_MAPPING
SCREAMING_SNAKE_CASE = {
# 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 lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )-> Optional[Any]:
"""simple docstring"""
UpperCamelCase = 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
):
UpperCamelCase = 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
):
UpperCamelCase = 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:
UpperCamelCase = True
if attribute_used:
break
if attribute_used:
break
# common and important attributes, even if they do not always appear in the modeling files
UpperCamelCase = [
"bos_index",
"eos_index",
"pad_index",
"unk_index",
"mask_index",
"image_size",
"use_cache",
"out_features",
"out_indices",
]
UpperCamelCase = ["encoder_no_repeat_ngram_size"]
# Special cases to be allowed
UpperCamelCase = True
if not attribute_used:
UpperCamelCase = 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:
UpperCamelCase = True
elif attribute in ["tie_word_embeddings"] and default_value is False:
UpperCamelCase = True
# Allow cases without checking the default value in the configuration class
elif attribute in attributes_to_allow + attributes_used_in_generation:
UpperCamelCase = True
elif attribute.endswith("_token_id" ):
UpperCamelCase = True
# configuration class specific cases
if not case_allowed:
UpperCamelCase = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] )
UpperCamelCase = allowed_cases is True or attribute in allowed_cases
return attribute_used or case_allowed
def lowerCamelCase__ ( UpperCAmelCase_ )-> Optional[Any]:
"""simple docstring"""
UpperCamelCase = dict(inspect.signature(config_class.__init__ ).parameters )
UpperCamelCase = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]]
UpperCamelCase = [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
UpperCamelCase = {}
if len(config_class.attribute_map ) > 0:
UpperCamelCase = {v: k for k, v in config_class.attribute_map.items()}
# Get the path to modeling source files
UpperCamelCase = inspect.getsourcefile(UpperCAmelCase_ )
UpperCamelCase = os.path.dirname(UpperCAmelCase_ )
# Let's check against all frameworks: as long as one framework uses an attribute, we are good.
UpperCamelCase = [os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) for fn in os.listdir(UpperCAmelCase_ ) if fn.startswith("modeling_" )]
# Get the source code strings
UpperCamelCase = []
for path in modeling_paths:
if os.path.isfile(UpperCAmelCase_ ):
with open(UpperCAmelCase_ ) as fp:
modeling_sources.append(fp.read() )
UpperCamelCase = []
for config_param, default_value in zip(UpperCAmelCase_ , UpperCAmelCase_ ):
# `attributes` here is all the variant names for `config_param`
UpperCamelCase = [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 lowerCamelCase__ ( )-> List[str]:
"""simple docstring"""
UpperCamelCase = {}
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.)
UpperCamelCase = [
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:
UpperCamelCase = check_config_attributes_being_used(UpperCAmelCase_ )
if len(UpperCAmelCase_ ) > 0:
UpperCamelCase = unused_attributes
if len(UpperCAmelCase_ ) > 0:
UpperCamelCase = "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()
| 554 | 1 |
'''simple docstring'''
class a_ :
def __init__( self : List[Any] ):
__snake_case = 0
__snake_case = 0
__snake_case = {}
def lowercase__ ( self : Any , __lowerCAmelCase : int ):
if vertex not in self.adjacency:
__snake_case = {}
self.num_vertices += 1
def lowercase__ ( self : Optional[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : List[str] ):
self.add_vertex(__lowerCAmelCase )
self.add_vertex(__lowerCAmelCase )
if head == tail:
return
__snake_case = weight
__snake_case = weight
def lowercase__ ( self : str ):
__snake_case = self.get_edges()
for edge in edges:
__snake_case , __snake_case , __snake_case = edge
edges.remove((tail, head, weight) )
for i in range(len(__lowerCAmelCase ) ):
__snake_case = 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]:
__snake_case = edges[i][2] + 1
for edge in edges:
__snake_case , __snake_case , __snake_case = edge
__snake_case = weight
__snake_case = weight
def __str__( self : List[Any] ):
__snake_case = ''
for tail in self.adjacency:
for head in self.adjacency[tail]:
__snake_case = self.adjacency[head][tail]
string += F'{head} -> {tail} == {weight}\n'
return string.rstrip('\n' )
def lowercase__ ( self : int ):
__snake_case = []
for tail in self.adjacency:
for head in self.adjacency[tail]:
output.append((tail, head, self.adjacency[head][tail]) )
return output
def lowercase__ ( self : Optional[Any] ):
return self.adjacency.keys()
@staticmethod
def lowercase__ ( __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : str=None ):
__snake_case = Graph()
if vertices is None:
__snake_case = []
if edges is None:
__snake_case = []
for vertex in vertices:
g.add_vertex(__lowerCAmelCase )
for edge in edges:
g.add_edge(*__lowerCAmelCase )
return g
class a_ :
def __init__( self : str ):
__snake_case = {}
__snake_case = {}
def __len__( self : List[str] ):
return len(self.parent )
def lowercase__ ( self : List[Any] , __lowerCAmelCase : List[Any] ):
if item in self.parent:
return self.find(__lowerCAmelCase )
__snake_case = item
__snake_case = 0
return item
def lowercase__ ( self : Optional[int] , __lowerCAmelCase : Any ):
if item not in self.parent:
return self.make_set(__lowerCAmelCase )
if item != self.parent[item]:
__snake_case = self.find(self.parent[item] )
return self.parent[item]
def lowercase__ ( self : Optional[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any ):
__snake_case = self.find(__lowerCAmelCase )
__snake_case = self.find(__lowerCAmelCase )
if roota == roota:
return roota
if self.rank[roota] > self.rank[roota]:
__snake_case = roota
return roota
if self.rank[roota] < self.rank[roota]:
__snake_case = roota
return roota
if self.rank[roota] == self.rank[roota]:
self.rank[roota] += 1
__snake_case = roota
return roota
return None
@staticmethod
def lowercase__ ( __lowerCAmelCase : Any ):
__snake_case = graph.num_vertices
__snake_case = Graph.UnionFind()
__snake_case = []
while num_components > 1:
__snake_case = {}
for vertex in graph.get_vertices():
__snake_case = -1
__snake_case = graph.get_edges()
for edge in edges:
__snake_case , __snake_case , __snake_case = edge
edges.remove((tail, head, weight) )
for edge in edges:
__snake_case , __snake_case , __snake_case = edge
__snake_case = union_find.find(__lowerCAmelCase )
__snake_case = union_find.find(__lowerCAmelCase )
if seta != seta:
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
__snake_case = [head, tail, weight]
if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
__snake_case = [head, tail, weight]
for vertex in cheap_edge:
if cheap_edge[vertex] != -1:
__snake_case , __snake_case , __snake_case = cheap_edge[vertex]
if union_find.find(__lowerCAmelCase ) != union_find.find(__lowerCAmelCase ):
union_find.union(__lowerCAmelCase , __lowerCAmelCase )
mst_edges.append(cheap_edge[vertex] )
__snake_case = num_components - 1
__snake_case = Graph.build(edges=__lowerCAmelCase )
return mst
| 427 |
'''simple docstring'''
import unittest
from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, 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.models.esm.modeling_esmfold import EsmForProteinFolding
class a_ :
def __init__( self : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=1_3 , __lowerCAmelCase : str=7 , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : Union[str, Any]=False , __lowerCAmelCase : List[Any]=False , __lowerCAmelCase : Union[str, Any]=1_9 , __lowerCAmelCase : Optional[Any]=3_2 , __lowerCAmelCase : str=5 , __lowerCAmelCase : List[str]=4 , __lowerCAmelCase : str=3_7 , __lowerCAmelCase : List[Any]="gelu" , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : List[Any]=5_1_2 , __lowerCAmelCase : Optional[int]=1_6 , __lowerCAmelCase : Dict=2 , __lowerCAmelCase : str=0.02 , __lowerCAmelCase : str=3 , __lowerCAmelCase : List[Any]=4 , __lowerCAmelCase : Any=None , ):
__snake_case = parent
__snake_case = batch_size
__snake_case = seq_length
__snake_case = is_training
__snake_case = use_input_mask
__snake_case = use_token_type_ids
__snake_case = use_labels
__snake_case = vocab_size
__snake_case = hidden_size
__snake_case = num_hidden_layers
__snake_case = num_attention_heads
__snake_case = intermediate_size
__snake_case = hidden_act
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = max_position_embeddings
__snake_case = type_vocab_size
__snake_case = type_sequence_label_size
__snake_case = initializer_range
__snake_case = num_labels
__snake_case = num_choices
__snake_case = scope
def lowercase__ ( self : int ):
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__snake_case = None
if self.use_input_mask:
__snake_case = random_attention_mask([self.batch_size, self.seq_length] )
__snake_case = None
__snake_case = None
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__snake_case = ids_tensor([self.batch_size] , self.num_choices )
__snake_case = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowercase__ ( self : Any ):
__snake_case = EsmConfig(
vocab_size=3_3 , hidden_size=self.hidden_size , pad_token_id=1 , 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 , is_folding_model=__lowerCAmelCase , esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False} , )
return config
def lowercase__ ( self : Union[str, Any] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[Any] ):
__snake_case = EsmForProteinFolding(config=__lowerCAmelCase ).float()
model.to(__lowerCAmelCase )
model.eval()
__snake_case = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )
__snake_case = model(__lowerCAmelCase )
__snake_case = model(__lowerCAmelCase )
self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 1_4, 3) )
self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) )
def lowercase__ ( self : Union[str, Any] ):
__snake_case = self.prepare_config_and_inputs()
(
(
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) , (
__snake_case
) ,
) = config_and_inputs
__snake_case = {'input_ids': input_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class a_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ):
lowercase_ : Dict = False
lowercase_ : Optional[int] = (EsmForProteinFolding,) if is_torch_available() else ()
lowercase_ : List[str] = ()
lowercase_ : List[str] = {} if is_torch_available() else {}
lowercase_ : List[str] = False
def lowercase__ ( self : List[Any] ):
__snake_case = EsmFoldModelTester(self )
__snake_case = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=3_7 )
def lowercase__ ( self : List[Any] ):
self.config_tester.run_common_tests()
def lowercase__ ( self : Union[str, Any] ):
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__lowerCAmelCase )
@unittest.skip('Does not support attention outputs' )
def lowercase__ ( self : Optional[int] ):
pass
@unittest.skip
def lowercase__ ( self : Any ):
pass
@unittest.skip('Esm does not support embedding resizing' )
def lowercase__ ( self : Optional[Any] ):
pass
@unittest.skip('Esm does not support embedding resizing' )
def lowercase__ ( self : List[Any] ):
pass
@unittest.skip('ESMFold does not support passing input embeds!' )
def lowercase__ ( self : List[str] ):
pass
@unittest.skip('ESMFold does not support head pruning.' )
def lowercase__ ( self : Union[str, Any] ):
pass
@unittest.skip('ESMFold does not support head pruning.' )
def lowercase__ ( self : int ):
pass
@unittest.skip('ESMFold does not support head pruning.' )
def lowercase__ ( self : Tuple ):
pass
@unittest.skip('ESMFold does not support head pruning.' )
def lowercase__ ( self : Optional[Any] ):
pass
@unittest.skip('ESMFold does not support head pruning.' )
def lowercase__ ( self : Dict ):
pass
@unittest.skip('ESMFold does not output hidden states in the normal way.' )
def lowercase__ ( self : Union[str, Any] ):
pass
@unittest.skip('ESMfold does not output hidden states in the normal way.' )
def lowercase__ ( self : int ):
pass
@unittest.skip('ESMFold only has one output format.' )
def lowercase__ ( self : Dict ):
pass
@unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality' )
def lowercase__ ( self : Any ):
pass
@unittest.skip('ESMFold does not support input chunking.' )
def lowercase__ ( self : Optional[Any] ):
pass
@unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.' )
def lowercase__ ( self : str ):
pass
@unittest.skip('ESMFold doesn\'t support torchscript compilation.' )
def lowercase__ ( self : Optional[int] ):
pass
@unittest.skip('ESMFold doesn\'t support torchscript compilation.' )
def lowercase__ ( self : Optional[int] ):
pass
@unittest.skip('ESMFold doesn\'t support torchscript compilation.' )
def lowercase__ ( self : List[str] ):
pass
@unittest.skip('ESMFold doesn\'t support data parallel.' )
def lowercase__ ( self : Dict ):
pass
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
def lowercase__ ( self : Optional[int] ):
pass
@require_torch
class a_ ( UpperCAmelCase__ ):
@slow
def lowercase__ ( self : Optional[int] ):
__snake_case = EsmForProteinFolding.from_pretrained('facebook/esmfold_v1' ).float()
model.eval()
__snake_case = torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] )
__snake_case = model(__lowerCAmelCase )['positions']
__snake_case = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa )
self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , __lowerCAmelCase , atol=1E-4 ) )
| 427 | 1 |
"""simple docstring"""
def lowerCAmelCase_( lowercase_ : int = 10 ) -> str:
if not isinstance(lowercase_ , lowercase_ ) or n < 0:
raise ValueError('''Invalid input''' )
_lowerCamelCase = 10**n
_lowerCamelCase = 2_84_33 * (pow(2 , 7_83_04_57 , lowercase_ )) + 1
return str(number % modulus )
if __name__ == "__main__":
from doctest import testmod
testmod()
print(F"""{solution(1_0) = }""")
| 661 |
"""simple docstring"""
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__SCREAMING_SNAKE_CASE : Optional[int] = {
'''configuration_informer''': [
'''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''InformerConfig''',
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__SCREAMING_SNAKE_CASE : int = [
'''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''InformerForPrediction''',
'''InformerModel''',
'''InformerPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_informer import (
INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
InformerForPrediction,
InformerModel,
InformerPreTrainedModel,
)
else:
import sys
__SCREAMING_SNAKE_CASE : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 661 | 1 |
# 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_tokenizers_available, is_torch_available
UpperCAmelCase_ : Union[str, Any] = {"configuration_mra": ["MRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MraConfig"]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase_ : int = [
"MRA_PRETRAINED_MODEL_ARCHIVE_LIST",
"MraForMaskedLM",
"MraForMultipleChoice",
"MraForQuestionAnswering",
"MraForSequenceClassification",
"MraForTokenClassification",
"MraLayer",
"MraModel",
"MraPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mra import (
MRA_PRETRAINED_MODEL_ARCHIVE_LIST,
MraForMaskedLM,
MraForMultipleChoice,
MraForQuestionAnswering,
MraForSequenceClassification,
MraForTokenClassification,
MraLayer,
MraModel,
MraPreTrainedModel,
)
else:
import sys
UpperCAmelCase_ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure)
| 232 |
from .imports import is_rich_available
if is_rich_available():
from rich.traceback import install
install(show_locals=False)
else:
raise ModuleNotFoundError("To use the rich extension, install rich with `pip install rich`")
| 232 | 1 |
"""simple docstring"""
from __future__ import annotations
A__ : Any = {
'A': ['B', 'C', 'E'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B', 'D'],
'F': ['C'],
'G': ['C'],
}
class lowercase__ :
def __init__( self : int , snake_case__ : dict[str, list[str]] , snake_case__ : str ):
lowerCamelCase_ : int =graph
# mapping node to its parent in resulting breadth first tree
lowerCamelCase_ : dict[str, str | None] ={}
lowerCamelCase_ : int =source_vertex
def UpperCAmelCase__ ( self : Optional[int] ):
lowerCamelCase_ : int ={self.source_vertex}
lowerCamelCase_ : Any =None
lowerCamelCase_ : Dict =[self.source_vertex] # first in first out queue
while queue:
lowerCamelCase_ : int =queue.pop(0 )
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(snake_case__ )
lowerCamelCase_ : Any =vertex
queue.append(snake_case__ )
def UpperCAmelCase__ ( self : str , snake_case__ : str ):
if target_vertex == self.source_vertex:
return self.source_vertex
lowerCamelCase_ : Optional[int] =self.parent.get(snake_case__ )
if target_vertex_parent is None:
lowerCamelCase_ : Optional[Any] =(
F"""No path from vertex: {self.source_vertex} to vertex: {target_vertex}"""
)
raise ValueError(snake_case__ )
return self.shortest_path(snake_case__ ) + F"""->{target_vertex}"""
if __name__ == "__main__":
A__ : Union[str, Any] = Graph(graph, 'G')
g.breath_first_search()
print(g.shortest_path('D'))
print(g.shortest_path('G'))
print(g.shortest_path('Foo'))
| 153 |
"""simple docstring"""
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 lowercase__ ( snake_case__, unittest.TestCase ):
_UpperCAmelCase :Dict = "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"
def UpperCAmelCase__ ( self : Union[str, Any] , snake_case__ : Any=0 ):
lowerCamelCase_ : Tuple =np.random.RandomState(snake_case__ )
lowerCamelCase_ : Union[str, Any] ={
"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 UpperCAmelCase__ ( self : str ):
lowerCamelCase_ : str =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : List[str] =self.get_dummy_inputs()
lowerCamelCase_ : List[str] =pipe(**snake_case__ ).images
lowerCamelCase_ : Dict =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
lowerCamelCase_ : Dict =np.array([0.65_072, 0.58_492, 0.48_219, 0.55_521, 0.53_180, 0.55_939, 0.50_697, 0.39_800, 0.46_455] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : Union[str, Any] ):
lowerCamelCase_ : Optional[Any] =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
lowerCamelCase_ : int =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=snake_case__ )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : List[Any] =self.get_dummy_inputs()
lowerCamelCase_ : Union[str, Any] =pipe(**snake_case__ ).images
lowerCamelCase_ : Tuple =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
lowerCamelCase_ : Union[str, Any] =np.array([0.65_863, 0.59_425, 0.49_326, 0.56_313, 0.53_875, 0.56_627, 0.51_065, 0.39_777, 0.46_330] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : Dict ):
lowerCamelCase_ : Optional[int] =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
lowerCamelCase_ : int =LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : int =self.get_dummy_inputs()
lowerCamelCase_ : Optional[Any] =pipe(**snake_case__ ).images
lowerCamelCase_ : List[Any] =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
lowerCamelCase_ : Any =np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : Any ):
lowerCamelCase_ : List[Any] =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
lowerCamelCase_ : str =EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : Dict =self.get_dummy_inputs()
lowerCamelCase_ : Dict =pipe(**snake_case__ ).images
lowerCamelCase_ : Tuple =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
lowerCamelCase_ : Tuple =np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : Tuple ):
lowerCamelCase_ : int =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
lowerCamelCase_ : Optional[Any] =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : Dict =self.get_dummy_inputs()
lowerCamelCase_ : str =pipe(**snake_case__ ).images
lowerCamelCase_ : Optional[int] =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
lowerCamelCase_ : Optional[int] =np.array([0.53_817, 0.60_812, 0.47_384, 0.49_530, 0.51_894, 0.49_814, 0.47_984, 0.38_958, 0.44_271] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : str ):
lowerCamelCase_ : Any =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
lowerCamelCase_ : Union[str, Any] =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : Optional[int] =self.get_dummy_inputs()
lowerCamelCase_ : Tuple =pipe(**snake_case__ ).images
lowerCamelCase_ : List[str] =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
lowerCamelCase_ : List[Any] =np.array([0.53_895, 0.60_808, 0.47_933, 0.49_608, 0.51_886, 0.49_950, 0.48_053, 0.38_957, 0.44_200] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase__ ( self : Any ):
lowerCamelCase_ : int =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : Union[str, Any] =self.get_dummy_inputs()
lowerCamelCase_ : Optional[Any] =3 * [inputs["prompt"]]
# forward
lowerCamelCase_ : Optional[int] =pipe(**snake_case__ )
lowerCamelCase_ : Dict =output.images[0, -3:, -3:, -1]
lowerCamelCase_ : Any =self.get_dummy_inputs()
lowerCamelCase_ : Dict =3 * [inputs.pop("prompt" )]
lowerCamelCase_ : Union[str, Any] =pipe.tokenizer(
snake_case__ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=snake_case__ , return_tensors="np" , )
lowerCamelCase_ : Any =text_inputs["input_ids"]
lowerCamelCase_ : Dict =pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0]
lowerCamelCase_ : Union[str, Any] =prompt_embeds
# forward
lowerCamelCase_ : Tuple =pipe(**snake_case__ )
lowerCamelCase_ : List[str] =output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
def UpperCAmelCase__ ( self : Dict ):
lowerCamelCase_ : List[str] =OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : List[Any] =self.get_dummy_inputs()
lowerCamelCase_ : Dict =3 * ["this is a negative prompt"]
lowerCamelCase_ : Tuple =negative_prompt
lowerCamelCase_ : List[str] =3 * [inputs["prompt"]]
# forward
lowerCamelCase_ : Optional[Any] =pipe(**snake_case__ )
lowerCamelCase_ : Any =output.images[0, -3:, -3:, -1]
lowerCamelCase_ : str =self.get_dummy_inputs()
lowerCamelCase_ : int =3 * [inputs.pop("prompt" )]
lowerCamelCase_ : List[Any] =[]
for p in [prompt, negative_prompt]:
lowerCamelCase_ : Tuple =pipe.tokenizer(
snake_case__ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=snake_case__ , return_tensors="np" , )
lowerCamelCase_ : Dict =text_inputs["input_ids"]
embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] )
lowerCamelCase_ , lowerCamelCase_ : int =embeds
# forward
lowerCamelCase_ : str =pipe(**snake_case__ )
lowerCamelCase_ : Any =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 lowercase__ ( unittest.TestCase ):
@property
def UpperCAmelCase__ ( self : int ):
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCAmelCase__ ( self : List[str] ):
lowerCamelCase_ : List[str] =ort.SessionOptions()
lowerCamelCase_ : List[Any] =False
return options
def UpperCAmelCase__ ( self : Tuple ):
# using the PNDM scheduler by default
lowerCamelCase_ : Optional[Any] =OnnxStableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : List[Any] ="A painting of a squirrel eating a burger"
np.random.seed(0 )
lowerCamelCase_ : Tuple =sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" )
lowerCamelCase_ : Union[str, Any] =output.images
lowerCamelCase_ : List[Any] =image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
lowerCamelCase_ : List[str] =np.array([0.0_452, 0.0_390, 0.0_087, 0.0_350, 0.0_617, 0.0_364, 0.0_544, 0.0_523, 0.0_720] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase__ ( self : Union[str, Any] ):
lowerCamelCase_ : List[Any] =DDIMScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
lowerCamelCase_ : List[str] =OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=snake_case__ , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : int ="open neural network exchange"
lowerCamelCase_ : List[Any] =np.random.RandomState(0 )
lowerCamelCase_ : str =sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=snake_case__ , output_type="np" )
lowerCamelCase_ : Optional[int] =output.images
lowerCamelCase_ : Optional[int] =image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
lowerCamelCase_ : Any =np.array([0.2_867, 0.1_974, 0.1_481, 0.7_294, 0.7_251, 0.6_667, 0.4_194, 0.5_642, 0.6_486] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase__ ( self : List[str] ):
lowerCamelCase_ : str =LMSDiscreteScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
lowerCamelCase_ : Any =OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=snake_case__ , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : Union[str, Any] ="open neural network exchange"
lowerCamelCase_ : str =np.random.RandomState(0 )
lowerCamelCase_ : Optional[int] =sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=snake_case__ , output_type="np" )
lowerCamelCase_ : Dict =output.images
lowerCamelCase_ : Optional[int] =image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
lowerCamelCase_ : Dict =np.array([0.2_306, 0.1_959, 0.1_593, 0.6_549, 0.6_394, 0.5_408, 0.5_065, 0.6_010, 0.6_161] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase__ ( self : Optional[Any] ):
lowerCamelCase_ : Any =0
def test_callback_fn(snake_case__ : int , snake_case__ : int , snake_case__ : np.ndarray ) -> None:
lowerCamelCase_ : Optional[int] =True
nonlocal number_of_steps
number_of_steps += 1
if step == 0:
assert latents.shape == (1, 4, 64, 64)
lowerCamelCase_ : List[str] =latents[0, -3:, -3:, -1]
lowerCamelCase_ : Union[str, Any] =np.array(
[-0.6_772, -0.3_835, -1.2_456, 0.1_905, -1.0_974, 0.6_967, -1.9_353, 0.0_178, 1.0_167] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
elif step == 5:
assert latents.shape == (1, 4, 64, 64)
lowerCamelCase_ : Optional[Any] =latents[0, -3:, -3:, -1]
lowerCamelCase_ : List[Any] =np.array(
[-0.3_351, 0.2_241, -0.1_837, -0.2_325, -0.6_577, 0.3_393, -0.0_241, 0.5_899, 1.3_875] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
lowerCamelCase_ : Any =False
lowerCamelCase_ : int =OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=snake_case__ )
lowerCamelCase_ : Dict ="Andromeda galaxy in a bottle"
lowerCamelCase_ : Union[str, Any] =np.random.RandomState(0 )
pipe(
prompt=snake_case__ , num_inference_steps=5 , guidance_scale=7.5 , generator=snake_case__ , callback=snake_case__ , callback_steps=1 , )
assert test_callback_fn.has_been_called
assert number_of_steps == 6
def UpperCAmelCase__ ( self : Tuple ):
lowerCamelCase_ : List[str] =OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=snake_case__ , feature_extractor=snake_case__ , provider=self.gpu_provider , sess_options=self.gpu_options , )
assert isinstance(snake_case__ , snake_case__ )
assert pipe.safety_checker is None
lowerCamelCase_ : Tuple =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(snake_case__ )
lowerCamelCase_ : str =OnnxStableDiffusionPipeline.from_pretrained(snake_case__ )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
lowerCamelCase_ : Any =pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None
| 153 | 1 |
snake_case__ : Optional[Any] = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
snake_case__ : Any = [{'type': 'code', 'content': INSTALL_CONTENT}]
snake_case__ : str = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 592 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
snake_case__ : Union[str, Any] = logging.get_logger(__name__)
snake_case__ : Union[str, Any] = {'vocab_file': 'sentencepiece.bpe.model'}
snake_case__ : List[Any] = {
'vocab_file': {
'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model',
'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model',
'moussaKam/barthez-orangesum-title': (
'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model'
),
},
}
snake_case__ : str = {
'moussaKam/mbarthez': 1_0_2_4,
'moussaKam/barthez': 1_0_2_4,
'moussaKam/barthez-orangesum-title': 1_0_2_4,
}
snake_case__ : Tuple = '▁'
class _a ( A__ ):
"""simple docstring"""
snake_case =VOCAB_FILES_NAMES
snake_case =PRETRAINED_VOCAB_FILES_MAP
snake_case =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case =["""input_ids""", """attention_mask"""]
def __init__( self , _snake_case , _snake_case="<s>" , _snake_case="</s>" , _snake_case="</s>" , _snake_case="<s>" , _snake_case="<unk>" , _snake_case="<pad>" , _snake_case="<mask>" , _snake_case = None , **_snake_case , ):
# Mask token behave like a normal word, i.e. include the space before it
_UpperCAmelCase =AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else mask_token
_UpperCAmelCase ={} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=_snake_case , eos_token=_snake_case , unk_token=_snake_case , sep_token=_snake_case , cls_token=_snake_case , pad_token=_snake_case , mask_token=_snake_case , sp_model_kwargs=self.sp_model_kwargs , **_snake_case , )
_UpperCAmelCase =vocab_file
_UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(_snake_case ) )
_UpperCAmelCase ={"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
_UpperCAmelCase =len(self.sp_model ) - 1
_UpperCAmelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()}
def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case = None ):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
_UpperCAmelCase =[self.cls_token_id]
_UpperCAmelCase =[self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case = None , _snake_case = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_snake_case , token_ids_a=_snake_case , already_has_special_tokens=_snake_case )
if token_ids_a is None:
return [1] + ([0] * len(_snake_case )) + [1]
return [1] + ([0] * len(_snake_case )) + [1, 1] + ([0] * len(_snake_case )) + [1]
def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case = None ):
_UpperCAmelCase =[self.sep_token_id]
_UpperCAmelCase =[self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def SCREAMING_SNAKE_CASE ( self ):
return len(self.sp_model )
def SCREAMING_SNAKE_CASE ( self ):
_UpperCAmelCase ={self.convert_ids_to_tokens(_snake_case ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE ( self , _snake_case ):
return self.sp_model.encode(_snake_case , out_type=_snake_case )
def SCREAMING_SNAKE_CASE ( self , _snake_case ):
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
_UpperCAmelCase =self.sp_model.PieceToId(_snake_case )
return spm_id if spm_id else self.unk_token_id
def SCREAMING_SNAKE_CASE ( self , _snake_case ):
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(_snake_case )
def SCREAMING_SNAKE_CASE ( self , _snake_case ):
_UpperCAmelCase =[]
_UpperCAmelCase =""
_UpperCAmelCase =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(_snake_case ) + token
_UpperCAmelCase =True
_UpperCAmelCase =[]
else:
current_sub_tokens.append(_snake_case )
_UpperCAmelCase =False
out_string += self.sp_model.decode(_snake_case )
return out_string.strip()
def __getstate__( self ):
_UpperCAmelCase =self.__dict__.copy()
_UpperCAmelCase =None
return state
def __setstate__( self , _snake_case ):
_UpperCAmelCase =d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
_UpperCAmelCase ={}
_UpperCAmelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def SCREAMING_SNAKE_CASE ( self , _snake_case , _snake_case = None ):
if not os.path.isdir(_snake_case ):
logger.error(F"Vocabulary path ({save_directory}) should be a directory" )
return
_UpperCAmelCase =os.path.join(
_snake_case , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_snake_case ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _snake_case )
elif not os.path.isfile(self.vocab_file ):
with open(_snake_case , "wb" ) as fi:
_UpperCAmelCase =self.sp_model.serialized_model_proto()
fi.write(_snake_case )
return (out_vocab_file,)
| 592 | 1 |
'''simple docstring'''
import unittest
import numpy as np
from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
from transformers.pipelines import AudioClassificationPipeline, pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_torchaudio,
slow,
)
from .test_pipelines_common import ANY
@is_pipeline_test
class _lowercase ( unittest.TestCase ):
_SCREAMING_SNAKE_CASE : Any = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
_SCREAMING_SNAKE_CASE : Tuple = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
def a ( self : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ) -> str:
__snake_case = AudioClassificationPipeline(model=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ )
# test with a raw waveform
__snake_case = np.zeros((3_4000,) )
__snake_case = np.zeros((1_4000,) )
return audio_classifier, [audioa, audio]
def a ( self : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : List[str] ) -> List[Any]:
__snake_case , __snake_case = examples
__snake_case = audio_classifier(SCREAMING_SNAKE_CASE_ )
# by default a model is initialized with num_labels=2
self.assertEqual(
SCREAMING_SNAKE_CASE_ , [
{'score': ANY(SCREAMING_SNAKE_CASE_ ), 'label': ANY(SCREAMING_SNAKE_CASE_ )},
{'score': ANY(SCREAMING_SNAKE_CASE_ ), 'label': ANY(SCREAMING_SNAKE_CASE_ )},
] , )
__snake_case = audio_classifier(SCREAMING_SNAKE_CASE_ , top_k=1 )
self.assertEqual(
SCREAMING_SNAKE_CASE_ , [
{'score': ANY(SCREAMING_SNAKE_CASE_ ), 'label': ANY(SCREAMING_SNAKE_CASE_ )},
] , )
self.run_torchaudio(SCREAMING_SNAKE_CASE_ )
@require_torchaudio
def a ( self : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, Any] ) -> Dict:
import datasets
# test with a local file
__snake_case = datasets.load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' )
__snake_case = dataset[0]['audio']['array']
__snake_case = audio_classifier(SCREAMING_SNAKE_CASE_ )
self.assertEqual(
SCREAMING_SNAKE_CASE_ , [
{'score': ANY(SCREAMING_SNAKE_CASE_ ), 'label': ANY(SCREAMING_SNAKE_CASE_ )},
{'score': ANY(SCREAMING_SNAKE_CASE_ ), 'label': ANY(SCREAMING_SNAKE_CASE_ )},
] , )
@require_torch
def a ( self : Union[str, Any] ) -> List[Any]:
__snake_case = 'anton-l/wav2vec2-random-tiny-classifier'
__snake_case = pipeline('audio-classification' , model=SCREAMING_SNAKE_CASE_ )
__snake_case = np.ones((8000,) )
__snake_case = audio_classifier(SCREAMING_SNAKE_CASE_ , top_k=4 )
__snake_case = [
{'score': 0.0_8_4_2, 'label': 'no'},
{'score': 0.0_8_3_8, 'label': 'up'},
{'score': 0.0_8_3_7, 'label': 'go'},
{'score': 0.0_8_3_4, 'label': 'right'},
]
__snake_case = [
{'score': 0.0_8_4_5, 'label': 'stop'},
{'score': 0.0_8_4_4, 'label': 'on'},
{'score': 0.0_8_4_1, 'label': 'right'},
{'score': 0.0_8_3_4, 'label': 'left'},
]
self.assertIn(nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] )
__snake_case = {'array': np.ones((8000,) ), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate}
__snake_case = audio_classifier(SCREAMING_SNAKE_CASE_ , top_k=4 )
self.assertIn(nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] )
@require_torch
@slow
def a ( self : List[Any] ) -> Any:
import datasets
__snake_case = 'superb/wav2vec2-base-superb-ks'
__snake_case = pipeline('audio-classification' , model=SCREAMING_SNAKE_CASE_ )
__snake_case = datasets.load_dataset('anton-l/superb_dummy' , 'ks' , split='test' )
__snake_case = np.array(dataset[3]['speech'] , dtype=np.floataa )
__snake_case = audio_classifier(SCREAMING_SNAKE_CASE_ , top_k=4 )
self.assertEqual(
nested_simplify(SCREAMING_SNAKE_CASE_ , decimals=3 ) , [
{'score': 0.9_8_1, 'label': 'go'},
{'score': 0.0_0_7, 'label': 'up'},
{'score': 0.0_0_6, 'label': '_unknown_'},
{'score': 0.0_0_1, 'label': 'down'},
] , )
@require_tf
@unittest.skip('Audio classification is not implemented for TF' )
def a ( self : List[str] ) -> Tuple:
pass
| 56 |
"""simple docstring"""
from pathlib import Path
import cva
import numpy as np
from matplotlib import pyplot as plt
def lowercase_ ( _snake_case ,_snake_case ,_snake_case ,_snake_case ,_snake_case ):
SCREAMING_SNAKE_CASE__ : int = cva.getAffineTransform(_snake_case ,_snake_case )
return cva.warpAffine(_snake_case ,_snake_case ,(rows, cols) )
if __name__ == "__main__":
# read original image
UpperCAmelCase__ : str = cva.imread(
str(Path(__file__).resolve().parent.parent / 'image_data' / 'lena.jpg')
)
# turn image in gray scale value
UpperCAmelCase__ : List[str] = cva.cvtColor(image, cva.COLOR_BGR2GRAY)
# get image shape
UpperCAmelCase__ , UpperCAmelCase__ : str = gray_img.shape
# set different points to rotate image
UpperCAmelCase__ : List[Any] = np.array([[5_0, 5_0], [2_0_0, 5_0], [5_0, 2_0_0]], np.floataa)
UpperCAmelCase__ : Union[str, Any] = np.array([[1_0, 1_0_0], [2_0_0, 5_0], [1_0_0, 2_5_0]], np.floataa)
UpperCAmelCase__ : List[str] = np.array([[5_0, 5_0], [1_5_0, 5_0], [1_2_0, 2_0_0]], np.floataa)
UpperCAmelCase__ : str = np.array([[1_0, 1_0_0], [8_0, 5_0], [1_8_0, 2_5_0]], np.floataa)
# add all rotated images in a list
UpperCAmelCase__ : List[Any] = [
gray_img,
get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols),
]
# plot different image rotations
UpperCAmelCase__ : List[Any] = plt.figure(1)
UpperCAmelCase__ : Optional[int] = ['Original', 'Rotation 1', 'Rotation 2', 'Rotation 3']
for i, image in enumerate(images):
plt.subplot(2, 2, i + 1), plt.imshow(image, 'gray')
plt.title(titles[i])
plt.axis('off')
plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95)
plt.show()
| 223 | 0 |
"""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_( lowercase_ : Dataset , lowercase_ : Dict[str, str] ) -> Tuple:
_lowerCamelCase = args.log_outputs
_lowerCamelCase = '''_'''.join(args.dataset.split('''/''' ) + [args.config, args.split] )
# load metric
_lowerCamelCase = load_metric('''wer''' )
_lowerCamelCase = load_metric('''cer''' )
# compute metrics
_lowerCamelCase = wer.compute(references=result['''target'''] , predictions=result['''prediction'''] )
_lowerCamelCase = cer.compute(references=result['''target'''] , predictions=result['''prediction'''] )
# print & log results
_lowerCamelCase = F"""WER: {wer_result}\nCER: {cer_result}"""
print(lowercase_ )
with open(F"""{dataset_id}_eval_results.txt""" , '''w''' ) as f:
f.write(lowercase_ )
# log all results in text file. Possibly interesting for analysis
if log_outputs is not None:
_lowerCamelCase = F"""log_{dataset_id}_predictions.txt"""
_lowerCamelCase = F"""log_{dataset_id}_targets.txt"""
with open(lowercase_ , '''w''' ) as p, open(lowercase_ , '''w''' ) as t:
# mapping function to write output
def write_to_file(lowercase_ : Optional[int] , lowercase_ : List[Any] ):
p.write(F"""{i}""" + '''\n''' )
p.write(batch['''prediction'''] + '''\n''' )
t.write(F"""{i}""" + '''\n''' )
t.write(batch['''target'''] + '''\n''' )
result.map(lowercase_ , with_indices=lowercase_ )
def lowerCAmelCase_( lowercase_ : str ) -> str:
_lowerCamelCase = '''[,?.!\-\;\:"“%‘”�—’…–]''' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
_lowerCamelCase = re.sub(lowercase_ , '''''' , text.lower() )
# In addition, we can normalize the target text, e.g. removing new lines characters etc...
# note that order is important here!
_lowerCamelCase = ['''\n\n''', '''\n''', ''' ''', ''' ''']
for t in token_sequences_to_ignore:
_lowerCamelCase = ''' '''.join(text.split(lowercase_ ) )
return text
def lowerCAmelCase_( lowercase_ : Any ) -> List[Any]:
# load dataset
_lowerCamelCase = load_dataset(args.dataset , args.config , split=args.split , use_auth_token=lowercase_ )
# for testing: only process the first two examples as a test
# dataset = dataset.select(range(10))
# load processor
_lowerCamelCase = AutoFeatureExtractor.from_pretrained(args.model_id )
_lowerCamelCase = feature_extractor.sampling_rate
# resample audio
_lowerCamelCase = dataset.cast_column('''audio''' , Audio(sampling_rate=lowercase_ ) )
# load eval pipeline
if args.device is None:
_lowerCamelCase = 0 if torch.cuda.is_available() else -1
_lowerCamelCase = pipeline('''automatic-speech-recognition''' , model=args.model_id , device=args.device )
# map function to decode audio
def map_to_pred(lowercase_ : Optional[Any] ):
_lowerCamelCase = asr(
batch['''audio''']['''array'''] , chunk_length_s=args.chunk_length_s , stride_length_s=args.stride_length_s )
_lowerCamelCase = prediction['''text''']
_lowerCamelCase = normalize_text(batch['''sentence'''] )
return batch
# run inference on all examples
_lowerCamelCase = dataset.map(lowercase_ , remove_columns=dataset.column_names )
# compute and log_results
# do not change function below
log_results(lowercase_ , lowercase_ )
if __name__ == "__main__":
__SCREAMING_SNAKE_CASE : Optional[int] = 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 : Any = parser.parse_args()
main(args)
| 623 |
"""simple docstring"""
from __future__ import annotations
from math import pow, sqrt
def lowerCAmelCase_( lowercase_ : float , lowercase_ : float , lowercase_ : float ) -> dict[str, float]:
if (resistance, reactance, impedance).count(0 ) != 1:
raise ValueError('''One and only one argument must be 0''' )
if resistance == 0:
return {"resistance": sqrt(pow(lowercase_ , 2 ) - pow(lowercase_ , 2 ) )}
elif reactance == 0:
return {"reactance": sqrt(pow(lowercase_ , 2 ) - pow(lowercase_ , 2 ) )}
elif impedance == 0:
return {"impedance": sqrt(pow(lowercase_ , 2 ) + pow(lowercase_ , 2 ) )}
else:
raise ValueError('''Exactly one argument must be 0''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 623 | 1 |
def __a ( lowerCAmelCase_ : int ,lowerCAmelCase_ : int ) -> List[Any]:
'''simple docstring'''
while a != 0:
UpperCAmelCase_, UpperCAmelCase_= b % a, a
return b
def __a ( lowerCAmelCase_ : int ,lowerCAmelCase_ : int ) -> int:
'''simple docstring'''
if gcd(lowerCAmelCase_ ,lowerCAmelCase_ ) != 1:
UpperCAmelCase_= F"""mod inverse of {a!r} and {m!r} does not exist"""
raise ValueError(lowerCAmelCase_ )
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= 1, 0, a
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= 0, 1, m
while va != 0:
UpperCAmelCase_= ua // va
UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m
| 593 |
"""simple docstring"""
class _SCREAMING_SNAKE_CASE :
'''simple docstring'''
def __init__( self : Optional[int] , UpperCAmelCase_ : int ) -> None:
"""simple docstring"""
_lowerCAmelCase = size
_lowerCAmelCase = [0] * size
_lowerCAmelCase = [0] * size
@staticmethod
def __lowerCamelCase ( UpperCAmelCase_ : int ) -> int:
"""simple docstring"""
return index | (index + 1)
@staticmethod
def __lowerCamelCase ( UpperCAmelCase_ : int ) -> int:
"""simple docstring"""
return (index & (index + 1)) - 1
def __lowerCamelCase ( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> None:
"""simple docstring"""
_lowerCAmelCase = value
while index < self.size:
_lowerCAmelCase = self.get_prev(UpperCAmelCase_ ) + 1
if current_left_border == index:
_lowerCAmelCase = value
else:
_lowerCAmelCase = max(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
_lowerCAmelCase = self.get_next(UpperCAmelCase_ )
def __lowerCamelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int:
"""simple docstring"""
right -= 1 # Because of right is exclusive
_lowerCAmelCase = 0
while left <= right:
_lowerCAmelCase = self.get_prev(UpperCAmelCase_ )
if left <= current_left:
_lowerCAmelCase = max(UpperCAmelCase_ , self.tree[right] )
_lowerCAmelCase = current_left
else:
_lowerCAmelCase = max(UpperCAmelCase_ , self.arr[right] )
right -= 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| 580 | 0 |
"""simple docstring"""
from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean
def a__ ( __lowercase ) -> Tuple:
# A local function to see if a dot lands in the circle.
def is_in_circle(__lowercase , __lowercase ) -> bool:
_A = sqrt((x**2) + (y**2) )
# Our circle has a radius of 1, so a distance
# greater than 1 would land outside the circle.
return distance_from_centre <= 1
# The proportion of guesses that landed in the circle
_A = mean(
int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) )
for _ in range(__lowercase ) )
# The ratio of the area for circle to square is pi/4.
_A = proportion * 4
print(f"""The estimated value of pi is {pi_estimate}""" )
print(f"""The numpy value of pi is {pi}""" )
print(f"""The total error is {abs(pi - pi_estimate )}""" )
def a__ ( __lowercase , __lowercase , __lowercase = 0.0 , __lowercase = 1.0 , ) -> float:
return mean(
function_to_integrate(uniform(__lowercase , __lowercase ) ) for _ in range(__lowercase ) ) * (max_value - min_value)
def a__ ( __lowercase , __lowercase = 0.0 , __lowercase = 1.0 ) -> None:
def identity_function(__lowercase ) -> float:
return x
_A = area_under_curve_estimator(
__lowercase , __lowercase , __lowercase , __lowercase )
_A = (max_value * max_value - min_value * min_value) / 2
print("******************" )
print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" )
print(f"""Estimated value is {estimated_value}""" )
print(f"""Expected value is {expected_value}""" )
print(f"""Total error is {abs(estimated_value - expected_value )}""" )
print("******************" )
def a__ ( __lowercase ) -> None:
def function_to_integrate(__lowercase ) -> float:
return sqrt(4.0 - x * x )
_A = area_under_curve_estimator(
__lowercase , __lowercase , 0.0 , 2.0 )
print("******************" )
print("Estimating pi using area_under_curve_estimator" )
print(f"""Estimated value is {estimated_value}""" )
print(f"""Expected value is {pi}""" )
print(f"""Total error is {abs(estimated_value - pi )}""" )
print("******************" )
if __name__ == "__main__":
import doctest
doctest.testmod() | 707 |
"""simple docstring"""
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
a_ = logging.get_logger(__name__)
class snake_case ( _UpperCamelCase):
__UpperCamelCase = ['input_features']
def __init__( self : int , a__ : Optional[Any]=80 , a__ : Optional[int]=1_60_00 , a__ : int=1_60 , a__ : Union[str, Any]=30 , a__ : Tuple=4_00 , a__ : List[Any]=0.0 , a__ : Optional[Any]=False , **a__ : List[Any] , ) -> str:
'''simple docstring'''
super().__init__(
feature_size=a__ , sampling_rate=a__ , padding_value=a__ , return_attention_mask=a__ , **a__ , )
_A = n_fft
_A = hop_length
_A = chunk_length
_A = chunk_length * sampling_rate
_A = self.n_samples // hop_length
_A = sampling_rate
_A = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=a__ , min_frequency=0.0 , max_frequency=8_0_0_0.0 , sampling_rate=a__ , norm="slaney" , mel_scale="slaney" , )
def a_ ( self : int , a__ : np.array ) -> np.ndarray:
'''simple docstring'''
_A = spectrogram(
a__ , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="log10" , )
_A = log_spec[:, :-1]
_A = np.maximum(a__ , log_spec.max() - 8.0 )
_A = (log_spec + 4.0) / 4.0
return log_spec
@staticmethod
# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
def a_ ( a__ : List[np.ndarray] , a__ : List[np.ndarray] , a__ : float = 0.0 ) -> List[np.ndarray]:
'''simple docstring'''
if attention_mask is not None:
_A = np.array(a__ , np.intaa )
_A = []
for vector, length in zip(a__ , attention_mask.sum(-1 ) ):
_A = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 )
if length < normed_slice.shape[0]:
_A = padding_value
normed_input_values.append(a__ )
else:
_A = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values]
return normed_input_values
def __call__( self : Optional[int] , a__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , a__ : bool = True , a__ : Optional[int] = None , a__ : Optional[Union[str, TensorType]] = None , a__ : Optional[bool] = None , a__ : Optional[str] = "max_length" , a__ : Optional[int] = None , a__ : Optional[int] = None , a__ : Optional[bool] = None , **a__ : Dict , ) -> BatchFeature:
'''simple docstring'''
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
F"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
F""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
F""" was sampled with {self.sampling_rate} and not {sampling_rate}.""" )
else:
logger.warning(
"It is strongly recommended to pass the `sampling_rate` argument to this function. "
"Failing to do so can result in silent errors that might be hard to debug." )
_A = isinstance(a__ , 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 = is_batched_numpy or (
isinstance(a__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
_A = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech]
elif not is_batched and not isinstance(a__ , np.ndarray ):
_A = np.asarray(a__ , dtype=np.floataa )
elif isinstance(a__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
_A = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
_A = [np.asarray([raw_speech] ).T]
_A = BatchFeature({"input_features": raw_speech} )
# convert into correct format for padding
_A = self.pad(
a__ , padding=a__ , max_length=max_length if max_length else self.n_samples , truncation=a__ , pad_to_multiple_of=a__ , return_attention_mask=return_attention_mask or do_normalize , )
# zero-mean and unit-variance normalization
if do_normalize:
_A = self.zero_mean_unit_var_norm(
padded_inputs["input_features"] , attention_mask=padded_inputs["attention_mask"] , padding_value=self.padding_value , )
_A = np.stack(padded_inputs["input_features"] , axis=0 )
# make sure list is in array format
_A = padded_inputs.get("input_features" ).transpose(2 , 0 , 1 )
_A = [self._np_extract_fbank_features(a__ ) for waveform in input_features[0]]
if isinstance(input_features[0] , a__ ):
_A = [np.asarray(a__ , dtype=np.floataa ) for feature in input_features]
else:
_A = input_features
if return_attention_mask:
# rescale from sample (48000) to feature (3000)
_A = padded_inputs["attention_mask"][:, :: self.hop_length]
if return_tensors is not None:
_A = padded_inputs.convert_to_tensors(a__ )
return padded_inputs
def a_ ( self : Dict ) -> Dict[str, Any]:
'''simple docstring'''
_A = copy.deepcopy(self.__dict__ )
_A = self.__class__.__name__
if "mel_filters" in output:
del output["mel_filters"]
return output | 621 | 0 |
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import torch
class UpperCamelCase_ ( TensorFormatter[Mapping, '''torch.Tensor''', Mapping] ):
'''simple docstring'''
def __init__( self : List[str] , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : List[Any]) ->Dict:
'''simple docstring'''
super().__init__(features=UpperCAmelCase__)
A__ = torch_tensor_kwargs
import torch # noqa import torch at initialization
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any]) ->Tuple:
'''simple docstring'''
import torch
if isinstance(UpperCAmelCase__ , UpperCAmelCase__) and column:
if all(
isinstance(UpperCAmelCase__ , torch.Tensor) and x.shape == column[0].shape and x.dtype == column[0].dtype
for x in column):
return torch.stack(UpperCAmelCase__)
return column
def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Optional[Any]) ->int:
'''simple docstring'''
import torch
if isinstance(UpperCAmelCase__ , (str, bytes, type(UpperCAmelCase__))):
return value
elif isinstance(UpperCAmelCase__ , (np.character, np.ndarray)) and np.issubdtype(value.dtype , np.character):
return value.tolist()
A__ = {}
if isinstance(UpperCAmelCase__ , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.integer):
A__ = {'''dtype''': torch.intaa}
elif isinstance(UpperCAmelCase__ , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.floating):
A__ = {'''dtype''': torch.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(UpperCAmelCase__ , PIL.Image.Image):
A__ = np.asarray(UpperCAmelCase__)
return torch.tensor(UpperCAmelCase__ , **{**default_dtype, **self.torch_tensor_kwargs})
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , UpperCAmelCase__ : Optional[int]) ->List[Any]:
'''simple docstring'''
import torch
# support for torch, tf, jax etc.
if hasattr(UpperCAmelCase__ , '''__array__''') and not isinstance(UpperCAmelCase__ , torch.Tensor):
A__ = data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(UpperCAmelCase__ , np.ndarray):
if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(UpperCAmelCase__) for substruct in data_struct])
elif isinstance(UpperCAmelCase__ , (list, tuple)):
return self._consolidate([self.recursive_tensorize(UpperCAmelCase__) for substruct in data_struct])
return self._tensorize(UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : dict) ->Union[str, Any]:
'''simple docstring'''
return map_nested(self._recursive_tensorize , UpperCAmelCase__ , map_list=UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : pa.Table) ->List[str]:
'''simple docstring'''
A__ = self.numpy_arrow_extractor().extract_row(UpperCAmelCase__)
A__ = self.python_features_decoder.decode_row(UpperCAmelCase__)
return self.recursive_tensorize(UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : pa.Table) ->Union[str, Any]:
'''simple docstring'''
A__ = self.numpy_arrow_extractor().extract_column(UpperCAmelCase__)
A__ = self.python_features_decoder.decode_column(UpperCAmelCase__ , pa_table.column_names[0])
A__ = self.recursive_tensorize(UpperCAmelCase__)
A__ = self._consolidate(UpperCAmelCase__)
return column
def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : pa.Table) ->List[str]:
'''simple docstring'''
A__ = self.numpy_arrow_extractor().extract_batch(UpperCAmelCase__)
A__ = self.python_features_decoder.decode_batch(UpperCAmelCase__)
A__ = self.recursive_tensorize(UpperCAmelCase__)
for column_name in batch:
A__ = self._consolidate(batch[column_name])
return batch
| 87 |
from __future__ import annotations
def _lowercase ( SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : int ):
"""simple docstring"""
if len(SCREAMING_SNAKE_CASE_ ) == 0:
return False
UpperCamelCase = len(SCREAMING_SNAKE_CASE_ ) // 2
if a_list[midpoint] == item:
return True
if item < a_list[midpoint]:
return binary_search(a_list[:midpoint] , SCREAMING_SNAKE_CASE_ )
else:
return binary_search(a_list[midpoint + 1 :] , SCREAMING_SNAKE_CASE_ )
if __name__ == "__main__":
__snake_case = input("Enter numbers separated by comma:\n").strip()
__snake_case = [int(item.strip()) for item in user_input.split(",")]
__snake_case = int(input("Enter the number to be found in the list:\n").strip())
__snake_case = "" if binary_search(sequence, target) else "not "
print(F'''{target} was {not_str}found in {sequence}''')
| 386 | 0 |
"""simple docstring"""
class UpperCamelCase__:
def __init__( self ,__UpperCAmelCase ) -> List[str]:
# we need a list not a string, so do something to change the type
A__ = arr.split(',' )
def snake_case__ ( self ) -> Optional[int]:
A__ = [int(self.array[0] )] * len(self.array )
A__ = [int(self.array[0] )] * len(self.array )
for i in range(1 ,len(self.array ) ):
A__ = max(
int(self.array[i] ) + sum_value[i - 1] ,int(self.array[i] ) )
A__ = max(sum_value[i] ,rear[i - 1] )
return rear[len(self.array ) - 1]
if __name__ == "__main__":
__lowerCamelCase = input("please input some numbers:")
__lowerCamelCase = SubArray(whole_array)
__lowerCamelCase = array.solve_sub_array()
print(("the results is:", re))
| 536 | """simple docstring"""
def UpperCAmelCase ( UpperCamelCase__ ):
"""simple docstring"""
if len(UpperCamelCase__ ) <= 1:
return [tuple(UpperCamelCase__ )]
A__ = []
def generate(UpperCamelCase__ , UpperCamelCase__ ):
if k == 1:
res.append(tuple(arr[:] ) )
return
generate(k - 1 , UpperCamelCase__ )
for i in range(k - 1 ):
if k % 2 == 0: # k is even
A__ , A__ = arr[k - 1], arr[i]
else: # k is odd
A__ , A__ = arr[k - 1], arr[0]
generate(k - 1 , UpperCamelCase__ )
generate(len(UpperCamelCase__ ) , UpperCamelCase__ )
return res
if __name__ == "__main__":
__lowerCamelCase = input("Enter numbers separated by a comma:\n").strip()
__lowerCamelCase = [int(item) for item in user_input.split(",")]
print(heaps(arr))
| 536 | 1 |
'''simple docstring'''
import math
class lowerCAmelCase_ :
def __init__( self , _lowerCAmelCase=0 ) -> str: # a graph with Node 0,1,...,N-1
_lowerCAmelCase = n
_lowerCAmelCase = [
[math.inf for j in range(0 , _lowerCAmelCase )] for i in range(0 , _lowerCAmelCase )
] # adjacency matrix for weight
_lowerCAmelCase = [
[math.inf for j in range(0 , _lowerCAmelCase )] for i in range(0 , _lowerCAmelCase )
] # dp[i][j] stores minimum distance from i to j
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]:
_lowerCAmelCase = w
def _snake_case ( self ) -> Optional[Any]:
for k in range(0 , self.n ):
for i in range(0 , self.n ):
for j in range(0 , self.n ):
_lowerCAmelCase = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase ) -> Any:
return self.dp[u][v]
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE = Graph(5)
graph.add_edge(0, 2, 9)
graph.add_edge(0, 4, 10)
graph.add_edge(1, 3, 5)
graph.add_edge(2, 3, 7)
graph.add_edge(3, 0, 10)
graph.add_edge(3, 1, 2)
graph.add_edge(3, 2, 1)
graph.add_edge(3, 4, 6)
graph.add_edge(4, 1, 3)
graph.add_edge(4, 2, 4)
graph.add_edge(4, 3, 9)
graph.floyd_warshall()
graph.show_min(1, 4)
graph.show_min(0, 3)
| 18 | '''simple docstring'''
def snake_case__ ( _A: int ) -> list[int]:
'''simple docstring'''
if length <= 0 or not isinstance(_A , _A ):
raise ValueError("""Length must be a positive integer.""" )
return [n * (2 * n - 1) for n in range(_A )]
if __name__ == "__main__":
print(hexagonal_numbers(length=5))
print(hexagonal_numbers(length=1_0))
| 370 | 0 |
'''simple docstring'''
import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures
UpperCAmelCase__ :Tuple = logging.get_logger(__name__)
@dataclass
class SCREAMING_SNAKE_CASE :
snake_case__ : str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys() )} )
snake_case__ : str = field(
metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} )
snake_case__ : int = field(
default=1_2_8 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
snake_case__ : bool = field(
default=lowerCAmelCase_ , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
def a_ ( self : Dict ):
"""simple docstring"""
__lowerCamelCase : Any = self.task_name.lower()
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : List[str] = 'train'
snake_case__ : str = 'dev'
snake_case__ : str = 'test'
class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ):
snake_case__ : GlueDataTrainingArguments
snake_case__ : str
snake_case__ : List[InputFeatures]
def __init__( self : List[str] , A__ : GlueDataTrainingArguments , A__ : PreTrainedTokenizerBase , A__ : Optional[int] = None , A__ : Union[str, Split] = Split.train , A__ : Optional[str] = None , ):
"""simple docstring"""
warnings.warn(
"""This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
"""library. You can have a look at this example script for pointers: """
"""https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , A__ , )
__lowerCamelCase : Optional[int] = args
__lowerCamelCase : Union[str, Any] = glue_processors[args.task_name]()
__lowerCamelCase : List[str] = glue_output_modes[args.task_name]
if isinstance(A__ , A__ ):
try:
__lowerCamelCase : List[str] = Split[mode]
except KeyError:
raise KeyError("""mode is not a valid split name""" )
# Load data features from cache or dataset file
__lowerCamelCase : str = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}" , )
__lowerCamelCase : Tuple = self.processor.get_labels()
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
"RobertaTokenizer",
"RobertaTokenizerFast",
"XLMRobertaTokenizer",
"BartTokenizer",
"BartTokenizerFast",
):
# HACK(label indices are swapped in RoBERTa pretrained model)
__lowerCamelCase : Optional[Any] = label_list[2], label_list[1]
__lowerCamelCase : Union[str, Any] = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
__lowerCamelCase : List[str] = cached_features_file + """.lock"""
with FileLock(A__ ):
if os.path.exists(A__ ) and not args.overwrite_cache:
__lowerCamelCase : Tuple = time.time()
__lowerCamelCase : Optional[Any] = torch.load(A__ )
logger.info(
f"Loading features from cached file {cached_features_file} [took %.3f s]" , time.time() - start )
else:
logger.info(f"Creating features from dataset file at {args.data_dir}" )
if mode == Split.dev:
__lowerCamelCase : List[Any] = self.processor.get_dev_examples(args.data_dir )
elif mode == Split.test:
__lowerCamelCase : List[str] = self.processor.get_test_examples(args.data_dir )
else:
__lowerCamelCase : Any = self.processor.get_train_examples(args.data_dir )
if limit_length is not None:
__lowerCamelCase : Tuple = examples[:limit_length]
__lowerCamelCase : Optional[int] = glue_convert_examples_to_features(
A__ , A__ , max_length=args.max_seq_length , label_list=A__ , output_mode=self.output_mode , )
__lowerCamelCase : List[Any] = time.time()
torch.save(self.features , A__ )
# ^ 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 : Tuple ):
"""simple docstring"""
return len(self.features )
def __getitem__( self : Any , A__ : int ):
"""simple docstring"""
return self.features[i]
def a_ ( self : Union[str, Any] ):
"""simple docstring"""
return self.label_list
| 705 |
'''simple docstring'''
UpperCAmelCase__ :List[Any] = 256
# Modulus to hash a string
UpperCAmelCase__ :str = 1_000_003
def __lowercase (_lowercase, _lowercase ) -> bool:
"""simple docstring"""
__lowerCamelCase : str = len(_lowercase )
__lowerCamelCase : List[str] = len(_lowercase )
if p_len > t_len:
return False
__lowerCamelCase : Optional[Any] = 0
__lowerCamelCase : Tuple = 0
__lowerCamelCase : Dict = 1
# Calculating the hash of pattern and substring of text
for i in range(_lowercase ):
__lowerCamelCase : Optional[int] = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus
__lowerCamelCase : Dict = (ord(text[i] ) + text_hash * alphabet_size) % modulus
if i == p_len - 1:
continue
__lowerCamelCase : Dict = (modulus_power * alphabet_size) % modulus
for i in range(0, t_len - p_len + 1 ):
if text_hash == p_hash and text[i : i + p_len] == pattern:
return True
if i == t_len - p_len:
continue
# Calculate the https://en.wikipedia.org/wiki/Rolling_hash
__lowerCamelCase : Dict = (
(text_hash - ord(text[i] ) * modulus_power) * alphabet_size
+ ord(text[i + p_len] )
) % modulus
return False
def __lowercase () -> None:
"""simple docstring"""
__lowerCamelCase : List[Any] = """abc1abc12"""
__lowerCamelCase : Optional[Any] = """alskfjaldsabc1abc1abc12k23adsfabcabc"""
__lowerCamelCase : List[Any] = """alskfjaldsk23adsfabcabc"""
assert rabin_karp(_lowercase, _lowercase ) and not rabin_karp(_lowercase, _lowercase )
# Test 2)
__lowerCamelCase : Optional[int] = """ABABX"""
__lowerCamelCase : Dict = """ABABZABABYABABX"""
assert rabin_karp(_lowercase, _lowercase )
# Test 3)
__lowerCamelCase : Any = """AAAB"""
__lowerCamelCase : int = """ABAAAAAB"""
assert rabin_karp(_lowercase, _lowercase )
# Test 4)
__lowerCamelCase : Any = """abcdabcy"""
__lowerCamelCase : Dict = """abcxabcdabxabcdabcdabcy"""
assert rabin_karp(_lowercase, _lowercase )
# Test 5)
__lowerCamelCase : str = """Lü"""
__lowerCamelCase : str = """Lüsai"""
assert rabin_karp(_lowercase, _lowercase )
__lowerCamelCase : Tuple = """Lue"""
assert not rabin_karp(_lowercase, _lowercase )
print("""Success.""" )
if __name__ == "__main__":
test_rabin_karp()
| 483 | 0 |
import unittest
from transformers import (
MODEL_FOR_OBJECT_DETECTION_MAPPING,
AutoFeatureExtractor,
AutoModelForObjectDetection,
ObjectDetectionPipeline,
is_vision_available,
pipeline,
)
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_pytesseract,
require_tf,
require_timm,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
else:
class __UpperCamelCase :
@staticmethod
def __A ( *lowerCAmelCase : Optional[Any] , **lowerCAmelCase : Union[str, Any] ):
'''simple docstring'''
pass
@is_pipeline_test
@require_vision
@require_timm
@require_torch
class __UpperCamelCase ( unittest.TestCase ):
SCREAMING_SNAKE_CASE__ = MODEL_FOR_OBJECT_DETECTION_MAPPING
def __A ( self : List[str] , lowerCAmelCase : Any , lowerCAmelCase : List[str] , lowerCAmelCase : int ):
'''simple docstring'''
UpperCAmelCase_ = ObjectDetectionPipeline(model=lowerCAmelCase , image_processor=lowerCAmelCase )
return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"]
def __A ( self : str , lowerCAmelCase : Optional[int] , lowerCAmelCase : str ):
'''simple docstring'''
UpperCAmelCase_ = object_detector("./tests/fixtures/tests_samples/COCO/000000039769.png" , threshold=0.0 )
self.assertGreater(len(lowerCAmelCase ) , 0 )
for detected_object in outputs:
self.assertEqual(
lowerCAmelCase , {
"score": ANY(lowerCAmelCase ),
"label": ANY(lowerCAmelCase ),
"box": {"xmin": ANY(lowerCAmelCase ), "ymin": ANY(lowerCAmelCase ), "xmax": ANY(lowerCAmelCase ), "ymax": ANY(lowerCAmelCase )},
} , )
import datasets
UpperCAmelCase_ = datasets.load_dataset("hf-internal-testing/fixtures_image_utils" , "image" , split="test" )
UpperCAmelCase_ = [
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"],
]
UpperCAmelCase_ = object_detector(lowerCAmelCase , threshold=0.0 )
self.assertEqual(len(lowerCAmelCase ) , len(lowerCAmelCase ) )
for outputs in batch_outputs:
self.assertGreater(len(lowerCAmelCase ) , 0 )
for detected_object in outputs:
self.assertEqual(
lowerCAmelCase , {
"score": ANY(lowerCAmelCase ),
"label": ANY(lowerCAmelCase ),
"box": {"xmin": ANY(lowerCAmelCase ), "ymin": ANY(lowerCAmelCase ), "xmax": ANY(lowerCAmelCase ), "ymax": ANY(lowerCAmelCase )},
} , )
@require_tf
@unittest.skip("Object detection not implemented in TF" )
def __A ( self : Any ):
'''simple docstring'''
pass
@require_torch
def __A ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = "hf-internal-testing/tiny-detr-mobilenetsv3"
UpperCAmelCase_ = AutoModelForObjectDetection.from_pretrained(lowerCAmelCase )
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase )
UpperCAmelCase_ = ObjectDetectionPipeline(model=lowerCAmelCase , feature_extractor=lowerCAmelCase )
UpperCAmelCase_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=0.0 )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
{"score": 0.3_376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
{"score": 0.3_376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
] , )
UpperCAmelCase_ = object_detector(
[
"http://images.cocodataset.org/val2017/000000039769.jpg",
"http://images.cocodataset.org/val2017/000000039769.jpg",
] , threshold=0.0 , )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
[
{"score": 0.3_376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
{"score": 0.3_376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
],
[
{"score": 0.3_376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
{"score": 0.3_376, "label": "LABEL_0", "box": {"xmin": 159, "ymin": 120, "xmax": 480, "ymax": 359}},
],
] , )
@require_torch
@slow
def __A ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = "facebook/detr-resnet-50"
UpperCAmelCase_ = AutoModelForObjectDetection.from_pretrained(lowerCAmelCase )
UpperCAmelCase_ = AutoFeatureExtractor.from_pretrained(lowerCAmelCase )
UpperCAmelCase_ = ObjectDetectionPipeline(model=lowerCAmelCase , feature_extractor=lowerCAmelCase )
UpperCAmelCase_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
{"score": 0.9_982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
{"score": 0.9_960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
{"score": 0.9_955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
] , )
UpperCAmelCase_ = object_detector(
[
"http://images.cocodataset.org/val2017/000000039769.jpg",
"http://images.cocodataset.org/val2017/000000039769.jpg",
] )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
[
{"score": 0.9_982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
{"score": 0.9_960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
{"score": 0.9_955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
],
[
{"score": 0.9_982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
{"score": 0.9_960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
{"score": 0.9_955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
],
] , )
@require_torch
@slow
def __A ( self : List[str] ):
'''simple docstring'''
UpperCAmelCase_ = "facebook/detr-resnet-50"
UpperCAmelCase_ = pipeline("object-detection" , model=lowerCAmelCase )
UpperCAmelCase_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
{"score": 0.9_982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
{"score": 0.9_960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
{"score": 0.9_955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
] , )
UpperCAmelCase_ = object_detector(
[
"http://images.cocodataset.org/val2017/000000039769.jpg",
"http://images.cocodataset.org/val2017/000000039769.jpg",
] )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
[
{"score": 0.9_982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
{"score": 0.9_960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
{"score": 0.9_955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
],
[
{"score": 0.9_982, "label": "remote", "box": {"xmin": 40, "ymin": 70, "xmax": 175, "ymax": 117}},
{"score": 0.9_960, "label": "remote", "box": {"xmin": 333, "ymin": 72, "xmax": 368, "ymax": 187}},
{"score": 0.9_955, "label": "couch", "box": {"xmin": 0, "ymin": 1, "xmax": 639, "ymax": 473}},
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
],
] , )
@require_torch
@slow
def __A ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase_ = 0.9_985
UpperCAmelCase_ = "facebook/detr-resnet-50"
UpperCAmelCase_ = pipeline("object-detection" , model=lowerCAmelCase )
UpperCAmelCase_ = object_detector("http://images.cocodataset.org/val2017/000000039769.jpg" , threshold=lowerCAmelCase )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
{"score": 0.9_988, "label": "cat", "box": {"xmin": 13, "ymin": 52, "xmax": 314, "ymax": 470}},
{"score": 0.9_987, "label": "cat", "box": {"xmin": 345, "ymin": 23, "xmax": 640, "ymax": 368}},
] , )
@require_torch
@require_pytesseract
@slow
def __A ( self : str ):
'''simple docstring'''
UpperCAmelCase_ = "Narsil/layoutlmv3-finetuned-funsd"
UpperCAmelCase_ = 0.9_993
UpperCAmelCase_ = pipeline("object-detection" , model=lowerCAmelCase , threshold=lowerCAmelCase )
UpperCAmelCase_ = object_detector(
"https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png" )
self.assertEqual(
nested_simplify(lowerCAmelCase , decimals=4 ) , [
{"score": 0.9_993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
{"score": 0.9_993, "label": "I-ANSWER", "box": {"xmin": 294, "ymin": 254, "xmax": 343, "ymax": 264}},
] , ) | 162 |
from dataclasses import dataclass, field
from typing import Tuple
from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments
if is_torch_available():
import torch
if is_torch_tpu_available(check_device=False):
import torch_xla.core.xla_model as xm
_a: List[str] = logging.get_logger(__name__)
@dataclass
class __UpperCamelCase ( lowercase ):
SCREAMING_SNAKE_CASE__ = [
'no_inference',
'no_cuda',
'no_tpu',
'no_speed',
'no_memory',
'no_env_print',
'no_multi_process',
]
def __init__( self : Optional[int] , **lowerCAmelCase : List[str] ):
'''simple docstring'''
for deprecated_arg in self.deprecated_args:
if deprecated_arg in kwargs:
UpperCAmelCase_ = deprecated_arg[3:]
setattr(self , lowerCAmelCase , not kwargs.pop(lowerCAmelCase ) )
logger.warning(
F"{deprecated_arg} is depreciated. Please use --no_{positive_arg} or"
F" {positive_arg}={kwargs[positive_arg]}" )
UpperCAmelCase_ = kwargs.pop("torchscript" , self.torchscript )
UpperCAmelCase_ = kwargs.pop("torch_xla_tpu_print_metrics" , self.torch_xla_tpu_print_metrics )
UpperCAmelCase_ = kwargs.pop("fp16_opt_level" , self.fpaa_opt_level )
super().__init__(**lowerCAmelCase )
SCREAMING_SNAKE_CASE__ = field(default=lowercase , metadata={'help': 'Trace the models using torchscript'} )
SCREAMING_SNAKE_CASE__ = field(default=lowercase , metadata={'help': 'Print Xla/PyTorch tpu metrics'} )
SCREAMING_SNAKE_CASE__ = field(
default='O1' , metadata={
'help': (
'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. '
'See details at https://nvidia.github.io/apex/amp.html'
)
} , )
@cached_property
def __A ( self : Union[str, Any] ):
'''simple docstring'''
requires_backends(self , ["torch"] )
logger.info("PyTorch: setting up devices" )
if not self.cuda:
UpperCAmelCase_ = torch.device("cpu" )
UpperCAmelCase_ = 0
elif is_torch_tpu_available():
UpperCAmelCase_ = xm.xla_device()
UpperCAmelCase_ = 0
else:
UpperCAmelCase_ = torch.device("cuda" if torch.cuda.is_available() else "cpu" )
UpperCAmelCase_ = torch.cuda.device_count()
return device, n_gpu
@property
def __A ( self : int ):
'''simple docstring'''
return is_torch_tpu_available() and self.tpu
@property
def __A ( self : List[Any] ):
'''simple docstring'''
requires_backends(self , ["torch"] )
# TODO(PVP): currently only single GPU is supported
return torch.cuda.current_device()
@property
def __A ( self : Tuple ):
'''simple docstring'''
requires_backends(self , ["torch"] )
return self._setup_devices[0]
@property
def __A ( self : List[Any] ):
'''simple docstring'''
requires_backends(self , ["torch"] )
return self._setup_devices[1]
@property
def __A ( self : Union[str, Any] ):
'''simple docstring'''
return self.n_gpu > 0 | 162 | 1 |
def UpperCamelCase__( UpperCamelCase__ : int = 60_08_51_47_51_43 )->int:
try:
A__ = int(UpperCamelCase__ )
except (TypeError, ValueError):
raise TypeError('''Parameter n must be int or castable to int.''' )
if n <= 0:
raise ValueError('''Parameter n must be greater than or equal to one.''' )
A__ = 1
A__ = 2
while i * i <= n:
while n % i == 0:
A__ = i
n //= i
i += 1
if n > 1:
A__ = n
return int(UpperCamelCase__ )
if __name__ == "__main__":
print(F"{solution() = }")
| 701 |
import unittest
from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_detectrona,
require_pytesseract,
require_tf,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
from transformers.image_utils import load_image
else:
class SCREAMING_SNAKE_CASE__ :
@staticmethod
def UpperCamelCase ( *__lowerCamelCase,**__lowerCamelCase ):
pass
def UpperCamelCase__( UpperCamelCase__ : Any )->List[str]:
return None
# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
a__: Optional[int] = (
'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)
@is_pipeline_test
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
__SCREAMING_SNAKE_CASE = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
@require_pytesseract
@require_vision
def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ):
A__ = pipeline(
'''document-question-answering''',model=__lowerCamelCase,tokenizer=__lowerCamelCase,image_processor=__lowerCamelCase )
A__ = INVOICE_URL
A__ = list(zip(*apply_tesseract(load_image(__lowerCamelCase ),__lowerCamelCase,'''''' ) ) )
A__ = '''What is the placebo?'''
A__ = [
{
'''image''': load_image(__lowerCamelCase ),
'''question''': question,
},
{
'''image''': image,
'''question''': question,
},
{
'''image''': image,
'''question''': question,
'''word_boxes''': word_boxes,
},
]
return dqa_pipeline, examples
def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase ):
A__ = dqa_pipeline(__lowerCamelCase,top_k=2 )
self.assertEqual(
__lowerCamelCase,[
[
{'''score''': ANY(__lowerCamelCase ), '''answer''': ANY(__lowerCamelCase ), '''start''': ANY(__lowerCamelCase ), '''end''': ANY(__lowerCamelCase )},
{'''score''': ANY(__lowerCamelCase ), '''answer''': ANY(__lowerCamelCase ), '''start''': ANY(__lowerCamelCase ), '''end''': ANY(__lowerCamelCase )},
]
]
* 3,)
@require_torch
@require_detectrona
@require_pytesseract
def UpperCamelCase ( self ):
A__ = pipeline('''document-question-answering''',model='''hf-internal-testing/tiny-random-layoutlmv2''' )
A__ = INVOICE_URL
A__ = '''How many cats are there?'''
A__ = [
{'''score''': 0.0001, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39},
{'''score''': 0.0001, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40},
]
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(nested_simplify(__lowerCamelCase,decimals=4 ),__lowerCamelCase )
A__ = dqa_pipeline({'''image''': image, '''question''': question},top_k=2 )
self.assertEqual(nested_simplify(__lowerCamelCase,decimals=4 ),__lowerCamelCase )
# This image does not detect ANY text in it, meaning layoutlmv2 should fail.
# Empty answer probably
A__ = '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(__lowerCamelCase,[] )
# We can optionnally pass directly the words and bounding boxes
A__ = '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
A__ = []
A__ = []
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,words=__lowerCamelCase,boxes=__lowerCamelCase,top_k=2 )
self.assertEqual(__lowerCamelCase,[] )
@slow
@require_torch
@require_detectrona
@require_pytesseract
def UpperCamelCase ( self ):
A__ = pipeline(
'''document-question-answering''',model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''',revision='''9977165''',)
A__ = INVOICE_URL
A__ = '''What is the invoice number?'''
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],)
A__ = dqa_pipeline({'''image''': image, '''question''': question},top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],)
A__ = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}],top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
[
{'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],
]
* 2,)
@slow
@require_torch
@require_detectrona
@require_pytesseract
def UpperCamelCase ( self ):
A__ = pipeline(
'''document-question-answering''',model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''',revision='''9977165''',max_seq_len=50,)
A__ = INVOICE_URL
A__ = '''What is the invoice number?'''
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
{'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],)
A__ = dqa_pipeline({'''image''': image, '''question''': question},top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
{'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],)
A__ = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}],top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
[
{'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
{'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
]
]
* 2,)
@slow
@require_torch
@require_pytesseract
@require_vision
def UpperCamelCase ( self ):
A__ = AutoTokenizer.from_pretrained(
'''impira/layoutlm-document-qa''',revision='''3dc6de3''',add_prefix_space=__lowerCamelCase )
A__ = pipeline(
'''document-question-answering''',model='''impira/layoutlm-document-qa''',tokenizer=__lowerCamelCase,revision='''3dc6de3''',)
A__ = INVOICE_URL
A__ = '''What is the invoice number?'''
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
],)
A__ = dqa_pipeline({'''image''': image, '''question''': question},top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
],)
A__ = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}],top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
[
{'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
]
]
* 2,)
A__ = list(zip(*apply_tesseract(load_image(__lowerCamelCase ),__lowerCamelCase,'''''' ) ) )
# This model should also work if `image` is set to None
A__ = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question},top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
],)
@slow
@require_torch
@require_pytesseract
@require_vision
def UpperCamelCase ( self ):
A__ = AutoTokenizer.from_pretrained(
'''impira/layoutlm-document-qa''',revision='''3dc6de3''',add_prefix_space=__lowerCamelCase )
A__ = pipeline(
'''document-question-answering''',model='''impira/layoutlm-document-qa''',tokenizer=__lowerCamelCase,revision='''3dc6de3''',max_seq_len=50,)
A__ = INVOICE_URL
A__ = '''What is the invoice number?'''
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],)
A__ = dqa_pipeline(
[{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}],top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
[
{'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
]
]
* 2,)
A__ = list(zip(*apply_tesseract(load_image(__lowerCamelCase ),__lowerCamelCase,'''''' ) ) )
# This model should also work if `image` is set to None
A__ = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question},top_k=2 )
self.assertEqual(
nested_simplify(__lowerCamelCase,decimals=4 ),[
{'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
{'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
],)
@slow
@require_torch
def UpperCamelCase ( self ):
A__ = pipeline(
'''document-question-answering''',model='''naver-clova-ix/donut-base-finetuned-docvqa''',tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' ),feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa''',)
A__ = INVOICE_URL
A__ = '''What is the invoice number?'''
A__ = dqa_pipeline(image=__lowerCamelCase,question=__lowerCamelCase,top_k=2 )
self.assertEqual(nested_simplify(__lowerCamelCase,decimals=4 ),[{'''answer''': '''us-001'''}] )
@require_tf
@unittest.skip('''Document question answering not implemented in TF''' )
def UpperCamelCase ( self ):
pass
| 212 | 0 |
from __future__ import annotations
def lowerCamelCase__ ( a : str , a : str ) -> bool:
"""simple docstring"""
a__ :Dict = get_failure_array(a )
# 2) Step through text searching for pattern
a__ , a__ :Tuple = 0, 0 # index into text, pattern
while i < len(a ):
if pattern[j] == text[i]:
if j == (len(a ) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
a__ :List[Any] = failure[j - 1]
continue
i += 1
return False
def lowerCamelCase__ ( a : str ) -> list[int]:
"""simple docstring"""
a__ :Union[str, Any] = [0]
a__ :Union[str, Any] = 0
a__ :Optional[int] = 1
while j < len(a ):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
a__ :Optional[int] = failure[i - 1]
continue
j += 1
failure.append(a )
return failure
if __name__ == "__main__":
# Test 1)
snake_case__ = '''abc1abc12'''
snake_case__ = '''alskfjaldsabc1abc1abc12k23adsfabcabc'''
snake_case__ = '''alskfjaldsk23adsfabcabc'''
assert kmp(pattern, texta) and not kmp(pattern, texta)
# Test 2)
snake_case__ = '''ABABX'''
snake_case__ = '''ABABZABABYABABX'''
assert kmp(pattern, text)
# Test 3)
snake_case__ = '''AAAB'''
snake_case__ = '''ABAAAAAB'''
assert kmp(pattern, text)
# Test 4)
snake_case__ = '''abcdabcy'''
snake_case__ = '''abcxabcdabxabcdabcdabcy'''
assert kmp(pattern, text)
# Test 5)
snake_case__ = '''aabaabaaa'''
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| 395 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
if is_sentencepiece_available():
from ..ta.tokenization_ta import TaTokenizer
else:
from ...utils.dummy_sentencepiece_objects import TaTokenizer
snake_case__ = TaTokenizer
if is_tokenizers_available():
from ..ta.tokenization_ta_fast import TaTokenizerFast
else:
from ...utils.dummy_tokenizers_objects import TaTokenizerFast
snake_case__ = TaTokenizerFast
snake_case__ = {'''configuration_mt5''': ['''MT5Config''', '''MT5OnnxConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ = [
'''MT5EncoderModel''',
'''MT5ForConditionalGeneration''',
'''MT5ForQuestionAnswering''',
'''MT5Model''',
'''MT5PreTrainedModel''',
'''MT5Stack''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ = ['''TFMT5EncoderModel''', '''TFMT5ForConditionalGeneration''', '''TFMT5Model''']
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case__ = ['''FlaxMT5EncoderModel''', '''FlaxMT5ForConditionalGeneration''', '''FlaxMT5Model''']
if TYPE_CHECKING:
from .configuration_mta import MTaConfig, MTaOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mta import (
MTaEncoderModel,
MTaForConditionalGeneration,
MTaForQuestionAnswering,
MTaModel,
MTaPreTrainedModel,
MTaStack,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel
else:
import sys
snake_case__ = _LazyModule(
__name__,
globals()['''__file__'''],
_import_structure,
extra_objects={'''MT5Tokenizer''': MTaTokenizer, '''MT5TokenizerFast''': MTaTokenizerFast},
module_spec=__spec__,
)
| 395 | 1 |
import os
import sys
from contextlib import contextmanager
# Windows only
if os.name == "nt":
import ctypes
import msvcrt # noqa
class __snake_case ( ctypes.Structure ):
'''simple docstring'''
lowerCAmelCase__ = [("""size""", ctypes.c_int), ("""visible""", ctypes.c_byte)]
def A__ ( ) -> List[Any]:
if os.name == "nt":
__snake_case: str = CursorInfo()
__snake_case: List[str] = ctypes.windll.kernelaa.GetStdHandle(-11)
ctypes.windll.kernelaa.GetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__))
__snake_case: Optional[int] = False
ctypes.windll.kernelaa.SetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__))
elif os.name == "posix":
sys.stdout.write("""\033[?25l""")
sys.stdout.flush()
def A__ ( ) -> List[Any]:
if os.name == "nt":
__snake_case: Dict = CursorInfo()
__snake_case: List[str] = ctypes.windll.kernelaa.GetStdHandle(-11)
ctypes.windll.kernelaa.GetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__))
__snake_case: List[str] = True
ctypes.windll.kernelaa.SetConsoleCursorInfo(SCREAMING_SNAKE_CASE__ , ctypes.byref(SCREAMING_SNAKE_CASE__))
elif os.name == "posix":
sys.stdout.write("""\033[?25h""")
sys.stdout.flush()
@contextmanager
def A__ ( ) -> int:
try:
hide_cursor()
yield
finally:
show_cursor()
| 155 |
from datasets.utils.patching import _PatchedModuleObj, patch_submodule
from . import _test_patching
def A__ ( ) -> Tuple:
import os as original_os
from os import path as original_path
from os import rename as original_rename
from os.path import dirname as original_dirname
from os.path import join as original_join
assert _test_patching.os is original_os
assert _test_patching.path is original_path
assert _test_patching.join is original_join
assert _test_patching.renamed_os is original_os
assert _test_patching.renamed_path is original_path
assert _test_patching.renamed_join is original_join
__snake_case: List[str] = """__test_patch_submodule_mock__"""
with patch_submodule(_test_patching , """os.path.join""" , SCREAMING_SNAKE_CASE__):
# Every way to access os.path.join must be patched, and the rest must stay untouched
# check os.path.join
assert isinstance(_test_patching.os , _PatchedModuleObj)
assert isinstance(_test_patching.os.path , _PatchedModuleObj)
assert _test_patching.os.path.join is mock
# check path.join
assert isinstance(_test_patching.path , _PatchedModuleObj)
assert _test_patching.path.join is mock
# check join
assert _test_patching.join is mock
# check that the other attributes are untouched
assert _test_patching.os.rename is original_rename
assert _test_patching.path.dirname is original_dirname
assert _test_patching.os.path.dirname is original_dirname
# Even renamed modules or objects must be patched
# check renamed_os.path.join
assert isinstance(_test_patching.renamed_os , _PatchedModuleObj)
assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj)
assert _test_patching.renamed_os.path.join is mock
# check renamed_path.join
assert isinstance(_test_patching.renamed_path , _PatchedModuleObj)
assert _test_patching.renamed_path.join is mock
# check renamed_join
assert _test_patching.renamed_join is mock
# check that the other attributes are untouched
assert _test_patching.renamed_os.rename is original_rename
assert _test_patching.renamed_path.dirname is original_dirname
assert _test_patching.renamed_os.path.dirname is original_dirname
# check that everthing is back to normal when the patch is over
assert _test_patching.os is original_os
assert _test_patching.path is original_path
assert _test_patching.join is original_join
assert _test_patching.renamed_os is original_os
assert _test_patching.renamed_path is original_path
assert _test_patching.renamed_join is original_join
def A__ ( ) -> Tuple:
assert _test_patching.open is open
__snake_case: Tuple = """__test_patch_submodule_builtin_mock__"""
# _test_patching has "open" in its globals
assert _test_patching.open is open
with patch_submodule(_test_patching , """open""" , SCREAMING_SNAKE_CASE__):
assert _test_patching.open is mock
# check that everthing is back to normal when the patch is over
assert _test_patching.open is open
def A__ ( ) -> Dict:
# pandas.read_csv is not present in _test_patching
__snake_case: Tuple = """__test_patch_submodule_missing_mock__"""
with patch_submodule(_test_patching , """pandas.read_csv""" , SCREAMING_SNAKE_CASE__):
pass
def A__ ( ) -> int:
# builtin should always be mocked even if they're not in the globals
# in case they're loaded at one point
__snake_case: Tuple = """__test_patch_submodule_missing_builtin_mock__"""
# _test_patching doesn't have "len" in its globals
assert getattr(_test_patching , """len""" , SCREAMING_SNAKE_CASE__) is None
with patch_submodule(_test_patching , """len""" , SCREAMING_SNAKE_CASE__):
assert _test_patching.len is mock
assert _test_patching.len is len
def A__ ( ) -> List[Any]:
__snake_case: Optional[int] = """__test_patch_submodule_start_and_stop_mock__"""
__snake_case: Union[str, Any] = patch_submodule(_test_patching , """open""" , SCREAMING_SNAKE_CASE__)
assert _test_patching.open is open
patch.start()
assert _test_patching.open is mock
patch.stop()
assert _test_patching.open is open
def A__ ( ) -> List[Any]:
from os import rename as original_rename
from os.path import dirname as original_dirname
from os.path import join as original_join
__snake_case: int = """__test_patch_submodule_successive_join__"""
__snake_case: Union[str, Any] = """__test_patch_submodule_successive_dirname__"""
__snake_case: Tuple = """__test_patch_submodule_successive_rename__"""
assert _test_patching.os.path.join is original_join
assert _test_patching.os.path.dirname is original_dirname
assert _test_patching.os.rename is original_rename
with patch_submodule(_test_patching , """os.path.join""" , SCREAMING_SNAKE_CASE__):
with patch_submodule(_test_patching , """os.rename""" , SCREAMING_SNAKE_CASE__):
with patch_submodule(_test_patching , """os.path.dirname""" , SCREAMING_SNAKE_CASE__):
assert _test_patching.os.path.join is mock_join
assert _test_patching.os.path.dirname is mock_dirname
assert _test_patching.os.rename is mock_rename
# try another order
with patch_submodule(_test_patching , """os.rename""" , SCREAMING_SNAKE_CASE__):
with patch_submodule(_test_patching , """os.path.join""" , SCREAMING_SNAKE_CASE__):
with patch_submodule(_test_patching , """os.path.dirname""" , SCREAMING_SNAKE_CASE__):
assert _test_patching.os.path.join is mock_join
assert _test_patching.os.path.dirname is mock_dirname
assert _test_patching.os.rename is mock_rename
assert _test_patching.os.path.join is original_join
assert _test_patching.os.path.dirname is original_dirname
assert _test_patching.os.rename is original_rename
def A__ ( ) -> Optional[Any]:
__snake_case: Tuple = """__test_patch_submodule_doesnt_exist_mock__"""
with patch_submodule(_test_patching , """__module_that_doesn_exist__.__attribute_that_doesn_exist__""" , SCREAMING_SNAKE_CASE__):
pass
with patch_submodule(_test_patching , """os.__attribute_that_doesn_exist__""" , SCREAMING_SNAKE_CASE__):
pass
| 155 | 1 |
import random
import unittest
import torch
from diffusers import IFInpaintingSuperResolutionPipeline
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 a ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ):
lowercase_ : List[Any] = IFInpaintingSuperResolutionPipeline
lowercase_ : str = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'}
lowercase_ : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'original_image'} )
lowercase_ : Any = PipelineTesterMixin.required_optional_params - {'latents'}
def UpperCAmelCase__ ( self : str ):
"""simple docstring"""
return self._get_superresolution_dummy_components()
def UpperCAmelCase__ ( self : Dict , snake_case__ : int , snake_case__ : int=0 ):
"""simple docstring"""
if str(snake_case__ ).startswith("mps" ):
__lowerCAmelCase = torch.manual_seed(snake_case__ )
else:
__lowerCAmelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ )
__lowerCAmelCase = floats_tensor((1, 3, 16, 16) , rng=random.Random(snake_case__ ) ).to(snake_case__ )
__lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ )
__lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ )
__lowerCAmelCase = {
"prompt": "A painting of a squirrel eating a burger",
"image": image,
"original_image": original_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 UpperCAmelCase__ ( self : List[str] ):
"""simple docstring"""
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )
def UpperCAmelCase__ ( self : int ):
"""simple docstring"""
self._test_save_load_optional_components()
@unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" )
def UpperCAmelCase__ ( self : Dict ):
"""simple docstring"""
super().test_save_load_floataa(expected_max_diff=1E-1 )
def UpperCAmelCase__ ( self : Tuple ):
"""simple docstring"""
self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )
def UpperCAmelCase__ ( self : int ):
"""simple docstring"""
self._test_save_load_local()
def UpperCAmelCase__ ( self : str ):
"""simple docstring"""
self._test_inference_batch_single_identical(
expected_max_diff=1E-2 , )
| 611 |
import json
import os
import unittest
from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
VOCAB_FILES_NAMES,
BlenderbotSmallTokenizer,
)
from ...test_tokenization_common import TokenizerTesterMixin
class a ( __UpperCAmelCase , unittest.TestCase ):
lowercase_ : Optional[Any] = BlenderbotSmallTokenizer
lowercase_ : List[str] = False
def UpperCAmelCase__ ( self : List[str] ):
"""simple docstring"""
super().setUp()
__lowerCAmelCase = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"]
__lowerCAmelCase = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) )
__lowerCAmelCase = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""]
__lowerCAmelCase = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"}
__lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__lowerCAmelCase = 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(snake_case__ ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(snake_case__ ) )
def UpperCAmelCase__ ( self : Any , **snake_case__ : Union[str, Any] ):
"""simple docstring"""
kwargs.update(self.special_tokens_map )
return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **snake_case__ )
def UpperCAmelCase__ ( self : List[str] , snake_case__ : str ):
"""simple docstring"""
__lowerCAmelCase = "adapt act apte"
__lowerCAmelCase = "adapt act apte"
return input_text, output_text
def UpperCAmelCase__ ( self : Optional[Any] ):
"""simple docstring"""
__lowerCAmelCase = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map )
__lowerCAmelCase = "adapt act apte"
__lowerCAmelCase = ["adapt", "act", "ap@@", "te"]
__lowerCAmelCase = tokenizer.tokenize(snake_case__ )
self.assertListEqual(snake_case__ , snake_case__ )
__lowerCAmelCase = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
__lowerCAmelCase = [0, 1, 2, 3, 4, 5]
self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case__ ) , snake_case__ )
def UpperCAmelCase__ ( self : Optional[int] ):
"""simple docstring"""
__lowerCAmelCase = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" )
assert tok("sam" ).input_ids == [1_384]
__lowerCAmelCase = "I am a small frog."
__lowerCAmelCase = tok([src_text] , padding=snake_case__ , truncation=snake_case__ )["input_ids"]
__lowerCAmelCase = tok.batch_decode(snake_case__ , skip_special_tokens=snake_case__ , clean_up_tokenization_spaces=snake_case__ )[0]
assert src_text != decoded # I wish it did!
assert decoded == "i am a small frog ."
def UpperCAmelCase__ ( self : int ):
"""simple docstring"""
__lowerCAmelCase = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" )
__lowerCAmelCase = "I am a small frog ."
__lowerCAmelCase = "."
__lowerCAmelCase = tok(snake_case__ )["input_ids"]
__lowerCAmelCase = tok(snake_case__ )["input_ids"]
assert encoded[-1] == encoded_dot[0]
| 611 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
SCREAMING_SNAKE_CASE_ = {
'configuration_maskformer': ['MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MaskFormerConfig'],
'configuration_maskformer_swin': ['MaskFormerSwinConfig'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = ['MaskFormerFeatureExtractor']
SCREAMING_SNAKE_CASE_ = ['MaskFormerImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_ = [
'MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
'MaskFormerForInstanceSegmentation',
'MaskFormerModel',
'MaskFormerPreTrainedModel',
]
SCREAMING_SNAKE_CASE_ = [
'MaskFormerSwinBackbone',
'MaskFormerSwinModel',
'MaskFormerSwinPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
from .configuration_maskformer_swin import MaskFormerSwinConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_maskformer import MaskFormerFeatureExtractor
from .image_processing_maskformer import MaskFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_maskformer import (
MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
MaskFormerForInstanceSegmentation,
MaskFormerModel,
MaskFormerPreTrainedModel,
)
from .modeling_maskformer_swin import (
MaskFormerSwinBackbone,
MaskFormerSwinModel,
MaskFormerSwinPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
| 717 |
import importlib
import math
import os
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, Optional, Tuple, Union
import flax
import jax.numpy as jnp
from ..utils import BaseOutput
SCREAMING_SNAKE_CASE_ = 'scheduler_config.json'
class a ( UpperCAmelCase ):
_lowercase = 1
_lowercase = 2
_lowercase = 3
_lowercase = 4
_lowercase = 5
@dataclass
class a ( UpperCAmelCase ):
_lowercase = 42
class a :
_lowercase = SCHEDULER_CONFIG_NAME
_lowercase = ["dtype"]
_lowercase = []
_lowercase = True
@classmethod
def _UpperCAmelCase ( cls , A_ = None , A_ = None , A_=False , **A_ , ):
'''simple docstring'''
_UpperCAmelCase , _UpperCAmelCase : str = cls.load_config(
pretrained_model_name_or_path=A_ , subfolder=A_ , return_unused_kwargs=A_ , **A_ , )
_UpperCAmelCase , _UpperCAmelCase : Optional[int] = cls.from_config(A_ , return_unused_kwargs=A_ , **A_ )
if hasattr(A_ , "create_state" ) and getattr(A_ , "has_state" , A_ ):
_UpperCAmelCase : Union[str, Any] = scheduler.create_state()
if return_unused_kwargs:
return scheduler, state, unused_kwargs
return scheduler, state
def _UpperCAmelCase ( self , A_ , A_ = False , **A_ ):
'''simple docstring'''
self.save_config(save_directory=A_ , push_to_hub=A_ , **A_ )
@property
def _UpperCAmelCase ( self ):
'''simple docstring'''
return self._get_compatibles()
@classmethod
def _UpperCAmelCase ( cls ):
'''simple docstring'''
_UpperCAmelCase : Union[str, Any] = list(set([cls.__name__] + cls._compatibles ) )
_UpperCAmelCase : Optional[Any] = importlib.import_module(__name__.split("." )[0] )
_UpperCAmelCase : Dict = [
getattr(A_ , A_ ) for c in compatible_classes_str if hasattr(A_ , A_ )
]
return compatible_classes
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: jnp.ndarray , lowerCAmelCase: Tuple[int] ) -> jnp.ndarray:
assert len(lowerCAmelCase ) >= x.ndim
return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(lowerCAmelCase ) - x.ndim) ) , lowerCAmelCase )
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int , lowerCAmelCase: Tuple=0.999 , lowerCAmelCase: int=jnp.floataa ) -> jnp.ndarray:
def alpha_bar(lowerCAmelCase: Union[str, Any] ):
return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2
_UpperCAmelCase : str = []
for i in range(lowerCAmelCase ):
_UpperCAmelCase : Optional[int] = i / num_diffusion_timesteps
_UpperCAmelCase : str = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar(lowerCAmelCase ) / alpha_bar(lowerCAmelCase ) , lowerCAmelCase ) )
return jnp.array(lowerCAmelCase , dtype=lowerCAmelCase )
@flax.struct.dataclass
class a :
_lowercase = 42
_lowercase = 42
_lowercase = 42
@classmethod
def _UpperCAmelCase ( cls , A_ ):
'''simple docstring'''
_UpperCAmelCase : Tuple = scheduler.config
if config.trained_betas is not None:
_UpperCAmelCase : List[Any] = jnp.asarray(config.trained_betas , dtype=scheduler.dtype )
elif config.beta_schedule == "linear":
_UpperCAmelCase : List[Any] = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype )
elif config.beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
_UpperCAmelCase : List[str] = (
jnp.linspace(
config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype )
** 2
)
elif config.beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
_UpperCAmelCase : str = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype )
else:
raise NotImplementedError(
f'beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}' )
_UpperCAmelCase : Optional[int] = 1.0 - betas
_UpperCAmelCase : int = jnp.cumprod(A_ , axis=0 )
return cls(
alphas=A_ , betas=A_ , alphas_cumprod=A_ , )
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: CommonSchedulerState , lowerCAmelCase: jnp.ndarray , lowerCAmelCase: jnp.ndarray , lowerCAmelCase: jnp.ndarray ) -> Union[str, Any]:
_UpperCAmelCase : Optional[int] = state.alphas_cumprod
_UpperCAmelCase : Optional[Any] = alphas_cumprod[timesteps] ** 0.5
_UpperCAmelCase : str = sqrt_alpha_prod.flatten()
_UpperCAmelCase : List[Any] = broadcast_to_shape_from_left(lowerCAmelCase , original_samples.shape )
_UpperCAmelCase : Optional[int] = (1 - alphas_cumprod[timesteps]) ** 0.5
_UpperCAmelCase : List[Any] = sqrt_one_minus_alpha_prod.flatten()
_UpperCAmelCase : int = broadcast_to_shape_from_left(lowerCAmelCase , original_samples.shape )
return sqrt_alpha_prod, sqrt_one_minus_alpha_prod
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: CommonSchedulerState , lowerCAmelCase: jnp.ndarray , lowerCAmelCase: jnp.ndarray , lowerCAmelCase: jnp.ndarray ) -> List[Any]:
_UpperCAmelCase , _UpperCAmelCase : Optional[Any] = get_sqrt_alpha_prod(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
_UpperCAmelCase : Any = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
return noisy_samples
def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: CommonSchedulerState , lowerCAmelCase: jnp.ndarray , lowerCAmelCase: jnp.ndarray , lowerCAmelCase: jnp.ndarray ) -> Dict:
_UpperCAmelCase , _UpperCAmelCase : int = get_sqrt_alpha_prod(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
_UpperCAmelCase : Tuple = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
return velocity
| 467 | 0 |
'''simple docstring'''
__UpperCAmelCase = {
'''meter''': '''m''',
'''kilometer''': '''km''',
'''megametre''': '''Mm''',
'''gigametre''': '''Gm''',
'''terametre''': '''Tm''',
'''petametre''': '''Pm''',
'''exametre''': '''Em''',
'''zettametre''': '''Zm''',
'''yottametre''': '''Ym''',
}
# Exponent of the factor(meter)
__UpperCAmelCase = {
'''m''': 0,
'''km''': 3,
'''Mm''': 6,
'''Gm''': 9,
'''Tm''': 12,
'''Pm''': 15,
'''Em''': 18,
'''Zm''': 21,
'''Ym''': 24,
}
def _snake_case ( A , A , A ) -> float:
lowerCAmelCase__ = from_type.lower().strip('''s''' )
lowerCAmelCase__ = to_type.lower().strip('''s''' )
lowerCAmelCase__ = UNIT_SYMBOL.get(A , A )
lowerCAmelCase__ = UNIT_SYMBOL.get(A , A )
if from_sanitized not in METRIC_CONVERSION:
lowerCAmelCase__ = (
F"""Invalid 'from_type' value: {from_type!r}.\n"""
F"""Conversion abbreviations are: {", ".join(A )}"""
)
raise ValueError(A )
if to_sanitized not in METRIC_CONVERSION:
lowerCAmelCase__ = (
F"""Invalid 'to_type' value: {to_type!r}.\n"""
F"""Conversion abbreviations are: {", ".join(A )}"""
)
raise ValueError(A )
lowerCAmelCase__ = METRIC_CONVERSION[from_sanitized]
lowerCAmelCase__ = METRIC_CONVERSION[to_sanitized]
lowerCAmelCase__ = 1
if from_exponent > to_exponent:
lowerCAmelCase__ = from_exponent - to_exponent
else:
lowerCAmelCase__ = -(to_exponent - from_exponent)
return value * pow(10 , A )
if __name__ == "__main__":
from doctest import testmod
testmod() | 90 |
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
__SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__)
def UpperCAmelCase__ ( __magic_name__ : Optional[int] ):
'''simple docstring'''
if isinstance(__magic_name__ , (list, tuple) ) and isinstance(videos[0] , (list, tuple) ) and is_valid_image(videos[0][0] ):
return videos
elif isinstance(__magic_name__ , (list, tuple) ) and is_valid_image(videos[0] ):
return [videos]
elif is_valid_image(__magic_name__ ):
return [[videos]]
raise ValueError(f'''Could not make batched video from {videos}''' )
class __magic_name__ ( snake_case ):
_lowerCAmelCase = ["pixel_values"]
def __init__( self : str , lowerCamelCase__ : bool = True , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCamelCase__ : bool = True , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : bool = True , lowerCamelCase__ : Union[int, float] = 1 / 2_5_5 , lowerCamelCase__ : bool = True , lowerCamelCase__ : bool = True , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , **lowerCamelCase__ : Optional[Any] , ):
super().__init__(**lowerCamelCase__ )
lowerCAmelCase : List[str] = size if size is not None else {'''shortest_edge''': 2_5_6}
lowerCAmelCase : Dict = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
lowerCAmelCase : List[str] = crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
lowerCAmelCase : int = get_size_dict(lowerCamelCase__ , param_name='''crop_size''' )
lowerCAmelCase : Optional[Any] = do_resize
lowerCAmelCase : Union[str, Any] = size
lowerCAmelCase : Optional[Any] = do_center_crop
lowerCAmelCase : List[str] = crop_size
lowerCAmelCase : List[str] = resample
lowerCAmelCase : int = do_rescale
lowerCAmelCase : Union[str, Any] = rescale_factor
lowerCAmelCase : Optional[Any] = offset
lowerCAmelCase : Dict = do_normalize
lowerCAmelCase : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
lowerCAmelCase : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _A ( self : int , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Dict[str, int] , lowerCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : List[str] , ):
lowerCAmelCase : Union[str, Any] = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
if "shortest_edge" in size:
lowerCAmelCase : Union[str, Any] = get_resize_output_image_size(lowerCamelCase__ , size['''shortest_edge'''] , default_to_square=lowerCamelCase__ )
elif "height" in size and "width" in size:
lowerCAmelCase : int = (size['''height'''], size['''width'''])
else:
raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' )
return resize(lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def _A ( self : int , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Dict[str, int] , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Optional[Any] , ):
lowerCAmelCase : Optional[int] = get_size_dict(lowerCamelCase__ )
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(lowerCamelCase__ , size=(size['''height'''], size['''width''']) , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def _A ( self : Dict , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Union[int, float] , lowerCamelCase__ : bool = True , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Optional[int] , ):
lowerCAmelCase : Union[str, Any] = image.astype(np.floataa )
if offset:
lowerCAmelCase : Any = image - (scale / 2)
return rescale(lowerCamelCase__ , scale=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def _A ( self : Dict , lowerCamelCase__ : np.ndarray , lowerCamelCase__ : Union[float, List[float]] , lowerCamelCase__ : Union[float, List[float]] , lowerCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase__ : Optional[Any] , ):
return normalize(lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def _A ( self : List[str] , lowerCamelCase__ : ImageInput , lowerCamelCase__ : bool = None , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : PILImageResampling = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : float = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , ):
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.
lowerCAmelCase : Tuple = to_numpy_array(lowerCamelCase__ )
if do_resize:
lowerCAmelCase : Any = self.resize(image=lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ )
if do_center_crop:
lowerCAmelCase : Dict = self.center_crop(lowerCamelCase__ , size=lowerCamelCase__ )
if do_rescale:
lowerCAmelCase : Union[str, Any] = self.rescale(image=lowerCamelCase__ , scale=lowerCamelCase__ , offset=lowerCamelCase__ )
if do_normalize:
lowerCAmelCase : Union[str, Any] = self.normalize(image=lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ )
lowerCAmelCase : Optional[int] = to_channel_dimension_format(lowerCamelCase__ , lowerCamelCase__ )
return image
def _A ( self : Tuple , lowerCamelCase__ : ImageInput , lowerCamelCase__ : bool = None , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : PILImageResampling = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : float = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : bool = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[float, List[float]]] = None , lowerCamelCase__ : Optional[Union[str, TensorType]] = None , lowerCamelCase__ : ChannelDimension = ChannelDimension.FIRST , **lowerCamelCase__ : int , ):
lowerCAmelCase : Any = do_resize if do_resize is not None else self.do_resize
lowerCAmelCase : Optional[Any] = resample if resample is not None else self.resample
lowerCAmelCase : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop
lowerCAmelCase : str = do_rescale if do_rescale is not None else self.do_rescale
lowerCAmelCase : str = rescale_factor if rescale_factor is not None else self.rescale_factor
lowerCAmelCase : Optional[Any] = offset if offset is not None else self.offset
lowerCAmelCase : int = do_normalize if do_normalize is not None else self.do_normalize
lowerCAmelCase : Dict = image_mean if image_mean is not None else self.image_mean
lowerCAmelCase : Optional[int] = image_std if image_std is not None else self.image_std
lowerCAmelCase : Any = size if size is not None else self.size
lowerCAmelCase : Optional[Any] = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
lowerCAmelCase : Optional[int] = crop_size if crop_size is not None else self.crop_size
lowerCAmelCase : List[Any] = get_size_dict(lowerCamelCase__ , param_name='''crop_size''' )
if not valid_images(lowerCamelCase__ ):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''' )
lowerCAmelCase : Any = make_batched(lowerCamelCase__ )
lowerCAmelCase : Any = [
[
self._preprocess_image(
image=lowerCamelCase__ , do_resize=lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ , do_center_crop=lowerCamelCase__ , crop_size=lowerCamelCase__ , do_rescale=lowerCamelCase__ , rescale_factor=lowerCamelCase__ , offset=lowerCamelCase__ , do_normalize=lowerCamelCase__ , image_mean=lowerCamelCase__ , image_std=lowerCamelCase__ , data_format=lowerCamelCase__ , )
for img in video
]
for video in videos
]
lowerCAmelCase : Union[str, Any] = {'''pixel_values''': videos}
return BatchFeature(data=lowerCamelCase__ , tensor_type=lowerCamelCase__ )
| 348 | 0 |
import argparse
import logging
from collections import namedtuple
import torch
from model_bertabs import BertAbsSummarizer
from models.model_builder import AbsSummarizer # The authors' implementation
from transformers import BertTokenizer
logging.basicConfig(level=logging.INFO)
__snake_case = logging.getLogger(__name__)
__snake_case = """Hello world! cécé herlolip"""
__snake_case = namedtuple(
"""BertAbsConfig""",
[
"""temp_dir""",
"""large""",
"""use_bert_emb""",
"""finetune_bert""",
"""encoder""",
"""share_emb""",
"""max_pos""",
"""enc_layers""",
"""enc_hidden_size""",
"""enc_heads""",
"""enc_ff_size""",
"""enc_dropout""",
"""dec_layers""",
"""dec_hidden_size""",
"""dec_heads""",
"""dec_ff_size""",
"""dec_dropout""",
],
)
def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ = BertAbsConfig(
temp_dir='.' , finetune_bert=UpperCamelCase_ , large=UpperCamelCase_ , share_emb=UpperCamelCase_ , use_bert_emb=UpperCamelCase_ , encoder='bert' , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , )
SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase_ , lambda UpperCamelCase_ , UpperCamelCase_ : storage )
SCREAMING_SNAKE_CASE__ = AbsSummarizer(UpperCamelCase_ , torch.device('cpu' ) , UpperCamelCase_ )
original.eval()
SCREAMING_SNAKE_CASE__ = BertAbsSummarizer(UpperCamelCase_ , torch.device('cpu' ) )
new_model.eval()
# -------------------
# Convert the weights
# -------------------
logging.info('convert the model' )
new_model.bert.load_state_dict(original.bert.state_dict() )
new_model.decoder.load_state_dict(original.decoder.state_dict() )
new_model.generator.load_state_dict(original.generator.state_dict() )
# ----------------------------------
# Make sure the outpus are identical
# ----------------------------------
logging.info('Make sure that the models\' outputs are identical' )
SCREAMING_SNAKE_CASE__ = BertTokenizer.from_pretrained('bert-base-uncased' )
# prepare the model inputs
SCREAMING_SNAKE_CASE__ = tokenizer.encode('This is sample éàalj\'-.' )
encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(UpperCamelCase_ )) )
SCREAMING_SNAKE_CASE__ = torch.tensor(UpperCamelCase_ ).unsqueeze(0 )
SCREAMING_SNAKE_CASE__ = tokenizer.encode('This is sample 3 éàalj\'-.' )
decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(UpperCamelCase_ )) )
SCREAMING_SNAKE_CASE__ = torch.tensor(UpperCamelCase_ ).unsqueeze(0 )
# failsafe to make sure the weights reset does not affect the
# loaded weights.
assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0
# forward pass
SCREAMING_SNAKE_CASE__ = encoder_input_ids
SCREAMING_SNAKE_CASE__ = decoder_input_ids
SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = None
SCREAMING_SNAKE_CASE__ = None
SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = None
SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = None
SCREAMING_SNAKE_CASE__ = None
# The original model does not apply the geneator layer immediatly but rather in
# the beam search (where it combines softmax + linear layer). Since we already
# apply the softmax in our generation process we only apply the linear layer here.
# We make sure that the outputs of the full stack are identical
SCREAMING_SNAKE_CASE__ = original(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )[0]
SCREAMING_SNAKE_CASE__ = original.generator(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = new_model(
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )[0]
SCREAMING_SNAKE_CASE__ = new_model.generator(UpperCamelCase_ )
SCREAMING_SNAKE_CASE__ = torch.max(torch.abs(output_converted_model - output_original_model ) ).item()
print('Maximum absolute difference beween weights: {:.2f}'.format(UpperCamelCase_ ) )
SCREAMING_SNAKE_CASE__ = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item()
print('Maximum absolute difference beween weights: {:.2f}'.format(UpperCamelCase_ ) )
SCREAMING_SNAKE_CASE__ = torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1e-3 )
if are_identical:
logging.info('all weights are equal up to 1e-3' )
else:
raise ValueError('the weights are different. The new model is likely different from the original one.' )
# The model has been saved with torch.save(model) and this is bound to the exact
# directory structure. We save the state_dict instead.
logging.info('saving the model\'s state dictionary' )
torch.save(
new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' )
if __name__ == "__main__":
__snake_case = argparse.ArgumentParser()
parser.add_argument(
"""--bertabs_checkpoint_path""",
default=None,
type=str,
required=True,
help="""Path the official PyTorch dump.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the output PyTorch model.""",
)
__snake_case = parser.parse_args()
convert_bertabs_checkpoints(
args.bertabs_checkpoint_path,
args.pytorch_dump_folder_path,
)
| 400 |
from typing import TYPE_CHECKING
from ...utils import _LazyModule
__snake_case = {"""processing_wav2vec2_with_lm""": ["""Wav2Vec2ProcessorWithLM"""]}
if TYPE_CHECKING:
from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM
else:
import sys
__snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 400 | 1 |
'''simple docstring'''
def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : int ) -> int:
'''simple docstring'''
return int(input_a == input_a == 0 )
def UpperCamelCase__ ( ) -> None:
'''simple docstring'''
print("""Truth Table of NOR Gate:""" )
print("""| Input 1 | Input 2 | Output |""" )
print(f"| 0 | 0 | {nor_gate(0 , 0 )} |" )
print(f"| 0 | 1 | {nor_gate(0 , 1 )} |" )
print(f"| 1 | 0 | {nor_gate(1 , 0 )} |" )
print(f"| 1 | 1 | {nor_gate(1 , 1 )} |" )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 38 |
"""simple docstring"""
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
class __magic_name__ ( unittest.TestCase , UpperCAmelCase__ ):
'''simple docstring'''
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = load_tool("""text-classification""" )
self.tool.setup()
lowerCamelCase = load_tool("""text-classification""" , remote=_a )
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = self.tool("""That's quite cool""" , ["""positive""", """negative"""] )
self.assertEqual(_a , """positive""" )
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = self.remote_tool("""That's quite cool""" , ["""positive""", """negative"""] )
self.assertEqual(_a , """positive""" )
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = self.tool(text="""That's quite cool""" , labels=["""positive""", """negative"""] )
self.assertEqual(_a , """positive""" )
def _lowerCAmelCase ( self ):
"""simple docstring"""
lowerCamelCase = self.remote_tool(text="""That's quite cool""" , labels=["""positive""", """negative"""] )
self.assertEqual(_a , """positive""" )
| 543 | 0 |
from itertools import product
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> list[int]:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = sides_number
SCREAMING_SNAKE_CASE_ : str = max_face_number * dice_number
SCREAMING_SNAKE_CASE_ : Tuple = [0] * (max_total + 1)
SCREAMING_SNAKE_CASE_ : str = 1
SCREAMING_SNAKE_CASE_ : Optional[int] = range(SCREAMING_SNAKE_CASE , max_face_number + 1 )
for dice_numbers in product(SCREAMING_SNAKE_CASE , repeat=SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : int = sum(SCREAMING_SNAKE_CASE )
totals_frequencies[total] += 1
return totals_frequencies
def __SCREAMING_SNAKE_CASE ( ) -> float:
SCREAMING_SNAKE_CASE_ : List[str] = total_frequency_distribution(
sides_number=4 , dice_number=9 )
SCREAMING_SNAKE_CASE_ : Optional[int] = total_frequency_distribution(
sides_number=6 , dice_number=6 )
SCREAMING_SNAKE_CASE_ : Optional[int] = 0
SCREAMING_SNAKE_CASE_ : Any = 9
SCREAMING_SNAKE_CASE_ : Union[str, Any] = 4 * 9
SCREAMING_SNAKE_CASE_ : List[str] = 6
for peter_total in range(SCREAMING_SNAKE_CASE , max_peter_total + 1 ):
peter_wins_count += peter_totals_frequencies[peter_total] * sum(
colin_totals_frequencies[min_colin_total:peter_total] )
SCREAMING_SNAKE_CASE_ : int = (4**9) * (6**6)
SCREAMING_SNAKE_CASE_ : Any = peter_wins_count / total_games_number
SCREAMING_SNAKE_CASE_ : List[str] = round(SCREAMING_SNAKE_CASE , ndigits=7 )
return rounded_peter_win_probability
if __name__ == "__main__":
print(f'''{solution() = }''')
| 311 |
from __future__ import annotations
from fractions import Fraction
from math import gcd, sqrt
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ) -> bool:
SCREAMING_SNAKE_CASE_ : int = int(number**0.5 )
return number == sq * sq
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> tuple[int, int]:
SCREAMING_SNAKE_CASE_ : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
SCREAMING_SNAKE_CASE_ : int = x_den * y_den * z_den
SCREAMING_SNAKE_CASE_ : int = gcd(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
top //= hcf
bottom //= hcf
return top, bottom
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE = 35 ) -> int:
SCREAMING_SNAKE_CASE_ : set = set()
SCREAMING_SNAKE_CASE_ : int
SCREAMING_SNAKE_CASE_ : Fraction = Fraction(0 )
SCREAMING_SNAKE_CASE_ : tuple[int, int]
for x_num in range(1 , order + 1 ):
for x_den in range(x_num + 1 , order + 1 ):
for y_num in range(1 , order + 1 ):
for y_den in range(y_num + 1 , order + 1 ):
# n=1
SCREAMING_SNAKE_CASE_ : Tuple = x_num * y_den + x_den * y_num
SCREAMING_SNAKE_CASE_ : Optional[int] = x_den * y_den
SCREAMING_SNAKE_CASE_ : Tuple = gcd(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
SCREAMING_SNAKE_CASE_ : int = add_three(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
unique_s.add(SCREAMING_SNAKE_CASE )
# n=2
SCREAMING_SNAKE_CASE_ : Dict = (
x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
)
SCREAMING_SNAKE_CASE_ : Union[str, Any] = x_den * x_den * y_den * y_den
if is_sq(SCREAMING_SNAKE_CASE ) and is_sq(SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : Any = int(sqrt(SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ : Union[str, Any] = int(sqrt(SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ : str = gcd(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
SCREAMING_SNAKE_CASE_ : List[Any] = add_three(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
unique_s.add(SCREAMING_SNAKE_CASE )
# n=-1
SCREAMING_SNAKE_CASE_ : Optional[int] = x_num * y_num
SCREAMING_SNAKE_CASE_ : List[str] = x_den * y_num + x_num * y_den
SCREAMING_SNAKE_CASE_ : Dict = gcd(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
SCREAMING_SNAKE_CASE_ : int = add_three(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
unique_s.add(SCREAMING_SNAKE_CASE )
# n=2
SCREAMING_SNAKE_CASE_ : Dict = x_num * x_num * y_num * y_num
SCREAMING_SNAKE_CASE_ : str = (
x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
)
if is_sq(SCREAMING_SNAKE_CASE ) and is_sq(SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ : Dict = int(sqrt(SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ : List[Any] = int(sqrt(SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ : Any = gcd(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
z_num //= hcf
z_den //= hcf
if 0 < z_num < z_den <= order:
SCREAMING_SNAKE_CASE_ : Tuple = add_three(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
unique_s.add(SCREAMING_SNAKE_CASE )
for num, den in unique_s:
total += Fraction(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
return total.denominator + total.numerator
if __name__ == "__main__":
print(f'''{solution() = }''')
| 311 | 1 |
"""simple docstring"""
# Copyright 2022 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
import os
import platform
import numpy as np
import psutil
import torch
from accelerate import __version__ as version
from accelerate.commands.config import default_config_file, load_config_from_file
from ..utils import is_npu_available, is_xpu_available
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any=None ) -> Tuple:
if subparsers is not None:
_lowerCAmelCase : Optional[Any] = subparsers.add_parser("""env""" )
else:
_lowerCAmelCase : Dict = argparse.ArgumentParser("""Accelerate env command""" )
parser.add_argument(
"""--config_file""" ,default=_lowerCamelCase ,help="""The config file to use for the default values in the launching script.""" )
if subparsers is not None:
parser.set_defaults(func=_lowerCamelCase )
return parser
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ) -> Optional[int]:
_lowerCAmelCase : List[Any] = torch.__version__
_lowerCAmelCase : Union[str, Any] = torch.cuda.is_available()
_lowerCAmelCase : Dict = is_xpu_available()
_lowerCAmelCase : Optional[int] = is_npu_available()
_lowerCAmelCase : Any = """Not found"""
# Get the default from the config file.
if args.config_file is not None or os.path.isfile(_lowerCamelCase ):
_lowerCAmelCase : Optional[int] = load_config_from_file(args.config_file ).to_dict()
_lowerCAmelCase : Union[str, Any] = {
"""`Accelerate` version""": version,
"""Platform""": platform.platform(),
"""Python version""": platform.python_version(),
"""Numpy version""": np.__version__,
"""PyTorch version (GPU?)""": f"{pt_version} ({pt_cuda_available})",
"""PyTorch XPU available""": str(_lowerCamelCase ),
"""PyTorch NPU available""": str(_lowerCamelCase ),
"""System RAM""": f"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB",
}
if pt_cuda_available:
_lowerCAmelCase : Dict = torch.cuda.get_device_name()
print("""\nCopy-and-paste the text below in your GitHub issue\n""" )
print("""\n""".join([f"- {prop}: {val}" for prop, val in info.items()] ) )
print("""- `Accelerate` default config:""" if args.config_file is None else """- `Accelerate` config passed:""" )
_lowerCAmelCase : Optional[int] = (
"""\n""".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()] )
if isinstance(_lowerCamelCase ,_lowerCamelCase )
else f"\t{accelerate_config}"
)
print(_lowerCamelCase )
_lowerCAmelCase : Tuple = accelerate_config
return info
def SCREAMING_SNAKE_CASE ( ) -> int:
_lowerCAmelCase : Optional[int] = env_command_parser()
_lowerCAmelCase : List[str] = parser.parse_args()
env_command(_lowerCamelCase )
return 0
if __name__ == "__main__":
raise SystemExit(main())
| 213 | """simple docstring"""
# Copyright (c) 2021-, NVIDIA CORPORATION. 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.
####################################################################################################
#
# Note: If when running this conversion script you're getting an exception:
# ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#
import argparse
import os
import re
import zipfile
import torch
from transformers import AutoTokenizer, GPTaConfig
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : int=0 ) -> List[str]:
# Format the message.
if name is None:
_lowerCAmelCase : Optional[Any] = None
else:
_lowerCAmelCase : int = """.""" * max(0 ,spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}"""
_lowerCAmelCase : int = fmt.format(_lowerCamelCase )
# Print and recurse (if needed).
if isinstance(_lowerCamelCase ,_lowerCamelCase ):
if msg is not None:
print(_lowerCamelCase )
for k in val.keys():
recursive_print(_lowerCamelCase ,val[k] ,spaces + 2 )
elif isinstance(_lowerCamelCase ,torch.Tensor ):
print(_lowerCamelCase ,""":""" ,val.size() )
else:
print(_lowerCamelCase ,""":""" ,_lowerCamelCase )
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Any ,_lowerCamelCase : Optional[int] ,_lowerCamelCase : Any ,_lowerCamelCase : Tuple ,_lowerCamelCase : Optional[Any] ) -> int:
# Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :]
# for compatibility with later versions of NVIDIA Megatron-LM.
# The inverse operation is performed inside Megatron-LM to read checkpoints:
# https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209
# If param is the weight tensor of the self-attention block, the returned tensor
# will have to be transposed one more time to be read by HuggingFace GPT2.
_lowerCAmelCase : str = param.size()
if checkpoint_version == 1.0:
# version 1.0 stores [num_heads * hidden_size * num_splits, :]
_lowerCAmelCase : int = (num_heads, hidden_size, num_splits) + input_shape[1:]
_lowerCAmelCase : Tuple = param.view(*_lowerCamelCase )
_lowerCAmelCase : str = param.transpose(0 ,2 )
_lowerCAmelCase : str = param.transpose(1 ,2 ).contiguous()
elif checkpoint_version >= 2.0:
# other versions store [num_heads * num_splits * hidden_size, :]
_lowerCAmelCase : List[str] = (num_heads, num_splits, hidden_size) + input_shape[1:]
_lowerCAmelCase : str = param.view(*_lowerCamelCase )
_lowerCAmelCase : Optional[Any] = param.transpose(0 ,1 ).contiguous()
_lowerCAmelCase : Optional[Any] = param.view(*_lowerCamelCase )
return param
def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Tuple ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : str ) -> Any:
# The converted output model.
_lowerCAmelCase : Optional[int] = {}
# old versions did not store training args
_lowerCAmelCase : Dict = input_state_dict.get("""args""" ,_lowerCamelCase )
if ds_args is not None:
# do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
# from pprint import pprint
# pprint(vars(ds_args))
_lowerCAmelCase : Optional[Any] = ds_args.padded_vocab_size
_lowerCAmelCase : Tuple = ds_args.max_position_embeddings
_lowerCAmelCase : Optional[Any] = ds_args.hidden_size
_lowerCAmelCase : Union[str, Any] = ds_args.num_layers
_lowerCAmelCase : Dict = ds_args.num_attention_heads
_lowerCAmelCase : Optional[Any] = ds_args.ffn_hidden_size
# pprint(config)
# The number of heads.
_lowerCAmelCase : List[str] = config.n_head
# The hidden_size per head.
_lowerCAmelCase : Any = config.n_embd // config.n_head
# Megatron-LM checkpoint version
if "checkpoint_version" in input_state_dict.keys():
_lowerCAmelCase : Tuple = input_state_dict["""checkpoint_version"""]
else:
_lowerCAmelCase : Union[str, Any] = 0.0
# The model.
_lowerCAmelCase : Any = input_state_dict["""model"""]
# The language model.
_lowerCAmelCase : Any = model["""language_model"""]
# The embeddings.
_lowerCAmelCase : Union[str, Any] = lm["""embedding"""]
# The word embeddings.
_lowerCAmelCase : int = embeddings["""word_embeddings"""]["""weight"""]
# Truncate the embedding table to vocab_size rows.
_lowerCAmelCase : Dict = word_embeddings[: config.vocab_size, :]
_lowerCAmelCase : Optional[int] = word_embeddings
# The position embeddings.
_lowerCAmelCase : Tuple = embeddings["""position_embeddings"""]["""weight"""]
# Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size]
_lowerCAmelCase : Union[str, Any] = pos_embeddings.size(0 )
if n_positions != config.n_positions:
raise ValueError(
f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" )
# Store the position embeddings.
_lowerCAmelCase : Optional[Any] = pos_embeddings
# The transformer.
_lowerCAmelCase : Optional[Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""]
# The regex to extract layer names.
_lowerCAmelCase : Any = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" )
# The simple map of names for "automated" rules.
_lowerCAmelCase : Optional[Any] = {
"""attention.dense""": """.attn.c_proj.""",
"""self_attention.dense""": """.attn.c_proj.""",
"""mlp.dense_h_to_4h""": """.mlp.c_fc.""",
"""mlp.dense_4h_to_h""": """.mlp.c_proj.""",
}
# Extract the layers.
for key, val in transformer.items():
# Match the name.
_lowerCAmelCase : Tuple = layer_re.match(_lowerCamelCase )
# Stop if that's not a layer
if m is None:
break
# The index of the layer.
_lowerCAmelCase : Optional[int] = int(m.group(1 ) )
# The name of the operation.
_lowerCAmelCase : Tuple = m.group(2 )
# Is it a weight or a bias?
_lowerCAmelCase : List[Any] = m.group(3 )
# The name of the layer.
_lowerCAmelCase : str = f"transformer.h.{layer_idx}"
# For layernorm(s), simply store the layer norm.
if op_name.endswith("""layernorm""" ):
_lowerCAmelCase : Optional[Any] = """ln_1""" if op_name.startswith("""input""" ) else """ln_2"""
_lowerCAmelCase : List[Any] = val
# Transpose the QKV matrix.
elif (
op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
) and weight_or_bias == "weight":
# Insert a tensor of 1x1xDxD bias.
_lowerCAmelCase : Optional[int] = torch.tril(torch.ones((n_positions, n_positions) ,dtype=torch.floataa ) ).view(
1 ,1 ,_lowerCamelCase ,_lowerCamelCase )
_lowerCAmelCase : Union[str, Any] = causal_mask
# Insert a "dummy" tensor for masked_bias.
_lowerCAmelCase : Dict = torch.tensor(-1e4 ,dtype=torch.floataa )
_lowerCAmelCase : Dict = masked_bias
_lowerCAmelCase : List[Any] = fix_query_key_value_ordering(_lowerCamelCase ,_lowerCamelCase ,3 ,_lowerCamelCase ,_lowerCamelCase )
# Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
_lowerCAmelCase : int = out_val.transpose(0 ,1 ).contiguous()
# Store.
_lowerCAmelCase : List[str] = out_val
# Transpose the bias.
elif (
op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
) and weight_or_bias == "bias":
_lowerCAmelCase : Union[str, Any] = fix_query_key_value_ordering(_lowerCamelCase ,_lowerCamelCase ,3 ,_lowerCamelCase ,_lowerCamelCase )
# Store. No change of shape.
_lowerCAmelCase : str = out_val
# Transpose the weights.
elif weight_or_bias == "weight":
_lowerCAmelCase : Any = megatron_to_transformers[op_name]
_lowerCAmelCase : Optional[Any] = val.transpose(0 ,1 )
# Copy the bias.
elif weight_or_bias == "bias":
_lowerCAmelCase : str = megatron_to_transformers[op_name]
_lowerCAmelCase : Union[str, Any] = val
# DEBUG.
assert config.n_layer == layer_idx + 1
# The final layernorm.
_lowerCAmelCase : int = transformer["""final_layernorm.weight"""]
_lowerCAmelCase : Union[str, Any] = transformer["""final_layernorm.bias"""]
# For LM head, transformers' wants the matrix to weight embeddings.
_lowerCAmelCase : int = word_embeddings
# It should be done!
return output_state_dict
def SCREAMING_SNAKE_CASE ( ) -> List[str]:
# Create the argument parser.
_lowerCAmelCase : int = argparse.ArgumentParser()
parser.add_argument("""--print-checkpoint-structure""" ,action="""store_true""" )
parser.add_argument(
"""path_to_checkpoint""" ,type=_lowerCamelCase ,help="""Path to the checkpoint file (.zip archive or direct .pt file)""" ,)
parser.add_argument(
"""--config_file""" ,default="""""" ,type=_lowerCamelCase ,help="""An optional config json file describing the pre-trained model.""" ,)
_lowerCAmelCase : List[Any] = parser.parse_args()
# Extract the basename.
_lowerCAmelCase : Optional[int] = os.path.dirname(args.path_to_checkpoint )
# Load the model.
# the .zip is very optional, let's keep it for backward compatibility
print(f"Extracting PyTorch state dictionary from {args.path_to_checkpoint}" )
if args.path_to_checkpoint.endswith(""".zip""" ):
with zipfile.ZipFile(args.path_to_checkpoint ,"""r""" ) as checkpoint:
with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict:
_lowerCAmelCase : Any = torch.load(_lowerCamelCase ,map_location="""cpu""" )
else:
_lowerCAmelCase : Optional[int] = torch.load(args.path_to_checkpoint ,map_location="""cpu""" )
_lowerCAmelCase : Optional[int] = input_state_dict.get("""args""" ,_lowerCamelCase )
# Read the config, or default to the model released by NVIDIA.
if args.config_file == "":
if ds_args is not None:
if ds_args.bias_gelu_fusion:
_lowerCAmelCase : Optional[Any] = """gelu_fast"""
elif ds_args.openai_gelu:
_lowerCAmelCase : Any = """gelu_new"""
else:
_lowerCAmelCase : str = """gelu"""
else:
# in the very early days this used to be "gelu_new"
_lowerCAmelCase : Any = """gelu_new"""
# Spell out all parameters in case the defaults change.
_lowerCAmelCase : Tuple = GPTaConfig(
vocab_size=50257 ,n_positions=1024 ,n_embd=1024 ,n_layer=24 ,n_head=16 ,n_inner=4096 ,activation_function=_lowerCamelCase ,resid_pdrop=0.1 ,embd_pdrop=0.1 ,attn_pdrop=0.1 ,layer_norm_epsilon=1e-5 ,initializer_range=0.02 ,summary_type="""cls_index""" ,summary_use_proj=_lowerCamelCase ,summary_activation=_lowerCamelCase ,summary_proj_to_labels=_lowerCamelCase ,summary_first_dropout=0.1 ,scale_attn_weights=_lowerCamelCase ,use_cache=_lowerCamelCase ,bos_token_id=50256 ,eos_token_id=50256 ,)
else:
_lowerCAmelCase : Optional[Any] = GPTaConfig.from_json_file(args.config_file )
_lowerCAmelCase : Tuple = ["""GPT2LMHeadModel"""]
# Convert.
print("""Converting""" )
_lowerCAmelCase : Tuple = convert_megatron_checkpoint(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase )
# Print the structure of converted state dict.
if args.print_checkpoint_structure:
recursive_print(_lowerCamelCase ,_lowerCamelCase )
# Add tokenizer class info to config
# see https://github.com/huggingface/transformers/issues/13906)
if ds_args is not None:
_lowerCAmelCase : Optional[Any] = ds_args.tokenizer_type
if tokenizer_type == "GPT2BPETokenizer":
_lowerCAmelCase : Dict = """gpt2"""
elif tokenizer_type == "PretrainedFromHF":
_lowerCAmelCase : List[str] = ds_args.tokenizer_name_or_path
else:
raise ValueError(f"Unrecognized tokenizer_type {tokenizer_type}" )
else:
_lowerCAmelCase : Optional[Any] = """gpt2"""
_lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained(_lowerCamelCase )
_lowerCAmelCase : Union[str, Any] = type(_lowerCamelCase ).__name__
_lowerCAmelCase : Dict = tokenizer_class
# Store the config to file.
print("""Saving config""" )
config.save_pretrained(_lowerCamelCase )
# Save tokenizer based on args
print(f"Adding {tokenizer_class} tokenizer files" )
tokenizer.save_pretrained(_lowerCamelCase )
# Store the state_dict to file.
_lowerCAmelCase : List[str] = os.path.join(_lowerCamelCase ,"""pytorch_model.bin""" )
print(f"Saving checkpoint to \"{output_checkpoint_file}\"" )
torch.save(_lowerCamelCase ,_lowerCamelCase )
####################################################################################################
if __name__ == "__main__":
main()
####################################################################################################
| 213 | 1 |
"""simple docstring"""
from __future__ import annotations
from collections import deque
class snake_case__ :
def __init__( self : Dict , lowercase : list[str] ):
'''simple docstring'''
UpperCAmelCase : list[dict] = []
self.adlist.append(
{"value": "", "next_states": [], "fail_state": 0, "output": []} )
for keyword in keywords:
self.add_keyword(lowercase )
self.set_fail_transitions()
def __lowerCAmelCase ( self : Union[str, Any] , lowercase : int , lowercase : str ):
'''simple docstring'''
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def __lowerCAmelCase ( self : Optional[int] , lowercase : str ):
'''simple docstring'''
UpperCAmelCase : Dict = 0
for character in keyword:
UpperCAmelCase : Dict = self.find_next_state(lowercase , lowercase )
if next_state is None:
self.adlist.append(
{
"value": character,
"next_states": [],
"fail_state": 0,
"output": [],
} )
self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 )
UpperCAmelCase : List[str] = len(self.adlist ) - 1
else:
UpperCAmelCase : List[Any] = next_state
self.adlist[current_state]["output"].append(lowercase )
def __lowerCAmelCase ( self : Any ):
'''simple docstring'''
UpperCAmelCase : deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(lowercase )
UpperCAmelCase : int = 0
while q:
UpperCAmelCase : Dict = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(lowercase )
UpperCAmelCase : Any = self.adlist[r]["fail_state"]
while (
self.find_next_state(lowercase , self.adlist[child]["value"] ) is None
and state != 0
):
UpperCAmelCase : Optional[int] = self.adlist[state]["fail_state"]
UpperCAmelCase : Optional[Any] = self.find_next_state(
lowercase , self.adlist[child]["value"] )
if self.adlist[child]["fail_state"] is None:
UpperCAmelCase : List[str] = 0
UpperCAmelCase : List[str] = (
self.adlist[child]["output"]
+ self.adlist[self.adlist[child]["fail_state"]]["output"]
)
def __lowerCAmelCase ( self : List[str] , lowercase : str ):
'''simple docstring'''
UpperCAmelCase : dict = {} # returns a dict with keywords and list of its occurrences
UpperCAmelCase : str = 0
for i in range(len(lowercase ) ):
while (
self.find_next_state(lowercase , string[i] ) is None
and current_state != 0
):
UpperCAmelCase : str = self.adlist[current_state]["fail_state"]
UpperCAmelCase : str = self.find_next_state(lowercase , string[i] )
if next_state is None:
UpperCAmelCase : str = 0
else:
UpperCAmelCase : List[str] = next_state
for key in self.adlist[current_state]["output"]:
if key not in result:
UpperCAmelCase : int = []
result[key].append(i - len(lowercase ) + 1 )
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| 292 |
"""simple docstring"""
def lowercase_ ( _lowercase : list , _lowercase : int , _lowercase : int = 0 , _lowercase : int = 0 ):
'''simple docstring'''
UpperCAmelCase : Tuple = right or len(_lowercase ) - 1
if left > right:
return -1
elif list_data[left] == key:
return left
elif list_data[right] == key:
return right
else:
return search(_lowercase , _lowercase , left + 1 , right - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 292 | 1 |
"""simple docstring"""
import itertools
import json
import os
import unittest
from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class lowercase_ ( __lowerCAmelCase , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase : int = RobertaTokenizer
UpperCAmelCase : List[Any] = RobertaTokenizerFast
UpperCAmelCase : List[str] = True
UpperCAmelCase : int = {'''cls_token''': '''<s>'''}
def lowerCAmelCase_ ( self : Union[str, Any] ):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_A = [
'l',
'o',
'w',
'e',
'r',
's',
't',
'i',
'd',
'n',
'\u0120',
'\u0120l',
'\u0120n',
'\u0120lo',
'\u0120low',
'er',
'\u0120lowest',
'\u0120newer',
'\u0120wider',
'<unk>',
]
_A = dict(zip(_UpperCAmelCase , range(len(_UpperCAmelCase ) ) ) )
_A = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
_A = {'unk_token': '<unk>'}
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
_A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp:
fp.write(json.dumps(_UpperCAmelCase ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(_UpperCAmelCase ) )
def lowerCAmelCase_ ( self : Union[str, Any] , **_UpperCAmelCase : str ):
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def lowerCAmelCase_ ( self : str , **_UpperCAmelCase : Optional[Any] ):
kwargs.update(self.special_tokens_map )
return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **_UpperCAmelCase )
def lowerCAmelCase_ ( self : Optional[int] , _UpperCAmelCase : List[Any] ):
_A = 'lower newer'
_A = 'lower newer'
return input_text, output_text
def lowerCAmelCase_ ( self : Any ):
_A = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map )
_A = 'lower newer'
_A = ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er']
_A = tokenizer.tokenize(_UpperCAmelCase ) # , add_prefix_space=True)
self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase )
_A = tokens + [tokenizer.unk_token]
_A = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) , _UpperCAmelCase )
def lowerCAmelCase_ ( self : Tuple ):
_A = self.get_tokenizer()
self.assertListEqual(tokenizer.encode('Hello world!' , add_special_tokens=_UpperCAmelCase ) , [0, 31_414, 232, 328, 2] )
self.assertListEqual(
tokenizer.encode('Hello world! cécé herlolip 418' , add_special_tokens=_UpperCAmelCase ) , [0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2] , )
@slow
def lowerCAmelCase_ ( self : Optional[Any] ):
_A = self.tokenizer_class.from_pretrained('roberta-base' )
_A = tokenizer.encode('sequence builders' , add_special_tokens=_UpperCAmelCase )
_A = tokenizer.encode('multi-sequence build' , add_special_tokens=_UpperCAmelCase )
_A = tokenizer.encode(
'sequence builders' , add_special_tokens=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase )
_A = tokenizer.encode(
'sequence builders' , 'multi-sequence build' , add_special_tokens=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase )
_A = tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase )
_A = tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase , _UpperCAmelCase )
assert encoded_sentence == encoded_text_from_decode
assert encoded_pair == encoded_pair_from_decode
def lowerCAmelCase_ ( self : List[str] ):
_A = self.get_tokenizer()
_A = 'Encode this sequence.'
_A = tokenizer.byte_encoder[' '.encode('utf-8' )[0]]
# Testing encoder arguments
_A = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase )
_A = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase )
_A = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase )
_A = tokenizer.convert_ids_to_tokens(encoded[0] )[0]
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
tokenizer.add_special_tokens({'bos_token': '<s>'} )
_A = tokenizer.encode(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
_A = tokenizer.convert_ids_to_tokens(encoded[1] )[0]
self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase )
# Testing spaces after special tokens
_A = '<mask>'
tokenizer.add_special_tokens(
{'mask_token': AddedToken(_UpperCAmelCase , lstrip=_UpperCAmelCase , rstrip=_UpperCAmelCase )} ) # mask token has a left space
_A = tokenizer.convert_tokens_to_ids(_UpperCAmelCase )
_A = 'Encode <mask> sequence'
_A = 'Encode <mask>sequence'
_A = tokenizer.encode(_UpperCAmelCase )
_A = encoded.index(_UpperCAmelCase )
_A = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
_A = tokenizer.encode(_UpperCAmelCase )
_A = encoded.index(_UpperCAmelCase )
_A = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0]
self.assertNotEqual(_UpperCAmelCase , _UpperCAmelCase )
def lowerCAmelCase_ ( self : int ):
pass
def lowerCAmelCase_ ( self : List[Any] ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_A = self.rust_tokenizer_class.from_pretrained(_UpperCAmelCase , **_UpperCAmelCase )
_A = self.tokenizer_class.from_pretrained(_UpperCAmelCase , **_UpperCAmelCase )
_A = 'A, <mask> AllenNLP sentence.'
_A = tokenizer_r.encode_plus(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase )
_A = tokenizer_p.encode_plus(_UpperCAmelCase , add_special_tokens=_UpperCAmelCase , return_token_type_ids=_UpperCAmelCase )
# token_type_ids should put 0 everywhere
self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) )
# attention_mask should put 1 everywhere, so sum over length should be 1
self.assertEqual(
sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , )
_A = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] )
_A = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] )
# Rust correctly handles the space before the mask while python doesnt
self.assertSequenceEqual(tokens_p['input_ids'] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] )
self.assertSequenceEqual(tokens_r['input_ids'] , [0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2] )
self.assertSequenceEqual(
_UpperCAmelCase , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
self.assertSequenceEqual(
_UpperCAmelCase , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
def lowerCAmelCase_ ( self : Tuple ):
for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ):
_A = self.rust_tokenizer_class.from_pretrained(
self.tmpdirname , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() )
_A = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() )
self.assertEqual(pre_tokenizer_state['add_prefix_space'] , _UpperCAmelCase )
self.assertEqual(post_processor_state['add_prefix_space'] , _UpperCAmelCase )
self.assertEqual(post_processor_state['trim_offsets'] , _UpperCAmelCase )
def lowerCAmelCase_ ( self : Union[str, Any] ):
# Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and
# `trim_offsets`
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
_A = 'hello' # `hello` is a token in the vocabulary of `pretrained_name`
_A = F'''{text_of_1_token} {text_of_1_token}'''
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(_UpperCAmelCase ) + 1, len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(_UpperCAmelCase ) + 1, len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(_UpperCAmelCase ), len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (len(_UpperCAmelCase ), len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
_A = F''' {text}'''
# tokenizer_r = self.rust_tokenizer_class.from_pretrained(
# pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True
# )
# encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)
# self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))
# self.assertEqual(
# encoding.offset_mapping[1],
# (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),
# )
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(_UpperCAmelCase ) + 1, 1 + len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(_UpperCAmelCase ), 1 + len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
_A = self.rust_tokenizer_class.from_pretrained(
_UpperCAmelCase , use_fast=_UpperCAmelCase , add_prefix_space=_UpperCAmelCase , trim_offsets=_UpperCAmelCase )
_A = tokenizer_r(_UpperCAmelCase , return_offsets_mapping=_UpperCAmelCase , add_special_tokens=_UpperCAmelCase )
self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(_UpperCAmelCase )) )
self.assertEqual(
encoding.offset_mapping[1] , (1 + len(_UpperCAmelCase ), 1 + len(_UpperCAmelCase ) + 1 + len(_UpperCAmelCase )) , )
| 7 |
"""simple docstring"""
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import KarrasVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class lowercase_ ( __lowerCAmelCase ):
'''simple docstring'''
UpperCAmelCase : UNetaDModel
UpperCAmelCase : KarrasVeScheduler
def __init__( self : Any , _UpperCAmelCase : UNetaDModel , _UpperCAmelCase : KarrasVeScheduler ):
super().__init__()
self.register_modules(unet=_UpperCAmelCase , scheduler=_UpperCAmelCase )
@torch.no_grad()
def __call__( self : Optional[int] , _UpperCAmelCase : int = 1 , _UpperCAmelCase : int = 50 , _UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _UpperCAmelCase : Optional[str] = "pil" , _UpperCAmelCase : bool = True , **_UpperCAmelCase : Optional[Any] , ):
_A = self.unet.config.sample_size
_A = (batch_size, 3, img_size, img_size)
_A = self.unet
# sample x_0 ~ N(0, sigma_0^2 * I)
_A = randn_tensor(_UpperCAmelCase , generator=_UpperCAmelCase , device=self.device ) * self.scheduler.init_noise_sigma
self.scheduler.set_timesteps(_UpperCAmelCase )
for t in self.progress_bar(self.scheduler.timesteps ):
# here sigma_t == t_i from the paper
_A = self.scheduler.schedule[t]
_A = self.scheduler.schedule[t - 1] if t > 0 else 0
# 1. Select temporarily increased noise level sigma_hat
# 2. Add new noise to move from sample_i to sample_hat
_A , _A = self.scheduler.add_noise_to_input(_UpperCAmelCase , _UpperCAmelCase , generator=_UpperCAmelCase )
# 3. Predict the noise residual given the noise magnitude `sigma_hat`
# The model inputs and output are adjusted by following eq. (213) in [1].
_A = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample
# 4. Evaluate dx/dt at sigma_hat
# 5. Take Euler step from sigma to sigma_prev
_A = self.scheduler.step(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
if sigma_prev != 0:
# 6. Apply 2nd order correction
# The model inputs and output are adjusted by following eq. (213) in [1].
_A = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample
_A = self.scheduler.step_correct(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , step_output.prev_sample , step_output['derivative'] , )
_A = step_output.prev_sample
_A = (sample / 2 + 0.5).clamp(0 , 1 )
_A = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
_A = self.numpy_to_pil(_UpperCAmelCase )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=_UpperCAmelCase )
| 7 | 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 (
ImageTextPipelineOutput,
UniDiffuserPipeline,
)
else:
from .modeling_text_decoder import UniDiffuserTextDecoder
from .modeling_uvit import UniDiffuserModel, UTransformeraDModel
from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
| 248 |
"""simple docstring"""
import math
from collections.abc import Iterator
from itertools import takewhile
def _lowerCAmelCase ( UpperCamelCase_ ):
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(UpperCamelCase_ ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def _lowerCAmelCase ( ):
__SCREAMING_SNAKE_CASE = 2
while True:
if is_prime(UpperCamelCase_ ):
yield num
num += 1
def _lowerCAmelCase ( UpperCamelCase_ = 200_0000 ):
return sum(takewhile(lambda UpperCamelCase_ : x < n , prime_generator() ) )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 248 | 1 |
from collections.abc import Sequence
from queue import Queue
class __a:
"""simple docstring"""
def __init__( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ) -> Tuple:
UpperCAmelCase_ : Optional[int] = start
UpperCAmelCase_ : Optional[int] = end
UpperCAmelCase_ : Any = val
UpperCAmelCase_ : Tuple = (start + end) // 2
UpperCAmelCase_ : int = left
UpperCAmelCase_ : Dict = right
def __repr__( self ) -> Union[str, Any]:
return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})'''
class __a:
"""simple docstring"""
def __init__( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any:
UpperCAmelCase_ : int = collection
UpperCAmelCase_ : int = function
if self.collection:
UpperCAmelCase_ : Optional[Any] = self._build_tree(0 ,len(_SCREAMING_SNAKE_CASE ) - 1 )
def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any:
self._update_tree(self.root ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any:
return self._query_range(self.root ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> List[Any]:
if start == end:
return SegmentTreeNode(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,self.collection[start] )
UpperCAmelCase_ : Optional[int] = (start + end) // 2
UpperCAmelCase_ : str = self._build_tree(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Optional[int] = self._build_tree(mid + 1 ,_SCREAMING_SNAKE_CASE )
return SegmentTreeNode(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,self.fn(left.val ,right.val ) ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Dict:
if node.start == i and node.end == i:
UpperCAmelCase_ : Optional[Any] = val
return
if i <= node.mid:
self._update_tree(node.left ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
else:
self._update_tree(node.right ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Any = self.fn(node.left.val ,node.right.val )
def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Tuple:
if node.start == i and node.end == j:
return node.val
if i <= node.mid:
if j <= node.mid:
# range in left child tree
return self._query_range(node.left ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
else:
# range in left child tree and right child tree
return self.fn(
self._query_range(node.left ,_SCREAMING_SNAKE_CASE ,node.mid ) ,self._query_range(node.right ,node.mid + 1 ,_SCREAMING_SNAKE_CASE ) ,)
else:
# range in right child tree
return self._query_range(node.right ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
def a__ ( self ) -> int:
if self.root is not None:
UpperCAmelCase_ : int = Queue()
queue.put(self.root )
while not queue.empty():
UpperCAmelCase_ : Tuple = queue.get()
yield node
if node.left is not None:
queue.put(node.left )
if node.right is not None:
queue.put(node.right )
if __name__ == "__main__":
import operator
for fn in [operator.add, max, min]:
print('*' * 50)
__a = SegmentTree([2, 1, 5, 3, 4], fn)
for node in arr.traverse():
print(node)
print()
arr.update(1, 5)
for node in arr.traverse():
print(node)
print()
print(arr.query_range(3, 4)) # 7
print(arr.query_range(2, 2)) # 5
print(arr.query_range(1, 3)) # 13
print() | 30 |
import numpy as np
import datasets
__a = '\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n'
__a = '\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n'
__a = '\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __a( datasets.Metric ):
"""simple docstring"""
def a__ ( self ) -> Union[str, Any]:
return datasets.MetricInfo(
description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features(
{
'''X''': datasets.Sequence(datasets.Value('''float''' ,id='''sequence''' ) ,id='''X''' ),
} ) ,)
def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any:
# convert to numpy arrays
UpperCAmelCase_ : str = np.array(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : List[Any] = np.array(_SCREAMING_SNAKE_CASE )
# Assert that arrays are 2D
if len(X.shape ) != 2:
raise ValueError('''Expected `X` to be a 2D vector''' )
if len(reference_distribution.shape ) != 2:
raise ValueError('''Expected `reference_distribution` to be a 2D vector''' )
if reference_distribution.shape[0] < 2:
raise ValueError(
'''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' )
# Get mahalanobis distance for each prediction
UpperCAmelCase_ : List[str] = X - np.mean(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Dict = np.cov(reference_distribution.T )
try:
UpperCAmelCase_ : Any = np.linalg.inv(_SCREAMING_SNAKE_CASE )
except np.linalg.LinAlgError:
UpperCAmelCase_ : List[str] = np.linalg.pinv(_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : Union[str, Any] = np.dot(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE )
UpperCAmelCase_ : List[Any] = np.dot(_SCREAMING_SNAKE_CASE ,X_minus_mu.T ).diagonal()
return {"mahalanobis": mahal_dist} | 30 | 1 |
from __future__ import annotations
def _SCREAMING_SNAKE_CASE ( snake_case ) -> str:
if len(lowerCAmelCase__ ) < 2:
raise ValueError("""Monogons and Digons are not polygons in the Euclidean space""" )
if any(i <= 0 for i in nums ):
raise ValueError("""All values must be greater than 0""" )
_UpperCAmelCase = nums.copy()
copy_nums.sort()
return copy_nums[-1] < sum(copy_nums[:-1] )
if __name__ == "__main__":
import doctest
doctest.testmod() | 706 |
import argparse
import fairseq
import torch
from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, 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.k_proj": "encoder.layers.*.attention.k_proj",
"self_attn.v_proj": "encoder.layers.*.attention.v_proj",
"self_attn.q_proj": "encoder.layers.*.attention.q_proj",
"self_attn.out_proj": "encoder.layers.*.attention.out_proj",
"self_attn_layer_norm": "encoder.layers.*.layer_norm",
"fc1": "encoder.layers.*.feed_forward.intermediate_dense",
"fc2": "encoder.layers.*.feed_forward.output_dense",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"encoder.layer_norm_for_extract": "layer_norm_for_extract",
"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",
"label_embs_concat": "label_embeddings_concat",
"mask_emb": "masked_spec_embed",
"spk_proj": "speaker_proj",
}
a = [
"lm_head",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
"label_embeddings_concat",
"speaker_proj",
"layer_norm_for_extract",
]
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , snake_case , snake_case ) -> List[str]:
for attribute in key.split(""".""" ):
_UpperCAmelCase = getattr(snake_case , snake_case )
if weight_type is not None:
_UpperCAmelCase = getattr(snake_case , snake_case ).shape
else:
_UpperCAmelCase = 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":
_UpperCAmelCase = value
elif weight_type == "weight_g":
_UpperCAmelCase = value
elif weight_type == "weight_v":
_UpperCAmelCase = value
elif weight_type == "bias":
_UpperCAmelCase = value
else:
_UpperCAmelCase = value
logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." )
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> Optional[int]:
_UpperCAmelCase = []
_UpperCAmelCase = fairseq_model.state_dict()
_UpperCAmelCase = hf_model.unispeech_sat.feature_extractor
for name, value in fairseq_dict.items():
_UpperCAmelCase = False
if "conv_layers" in name:
load_conv_layer(
snake_case , snake_case , snake_case , snake_case , hf_model.config.feat_extract_norm == """group""" , )
_UpperCAmelCase = True
else:
for key, mapped_key in MAPPING.items():
_UpperCAmelCase = """unispeech_sat.""" + 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]:
if "layer_norm_for_extract" in name and (".".join(name.split(""".""" )[:-1] ) != key):
# special case since naming is very similar
continue
_UpperCAmelCase = True
if "*" in mapped_key:
_UpperCAmelCase = name.split(snake_case )[0].split(""".""" )[-2]
_UpperCAmelCase = mapped_key.replace("""*""" , snake_case )
if "weight_g" in name:
_UpperCAmelCase = """weight_g"""
elif "weight_v" in name:
_UpperCAmelCase = """weight_v"""
elif "bias" in name:
_UpperCAmelCase = """bias"""
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
_UpperCAmelCase = """weight"""
else:
_UpperCAmelCase = None
set_recursively(snake_case , snake_case , snake_case , snake_case , snake_case )
continue
if not is_used:
unused_weights.append(snake_case )
logger.warning(f"Unused weights: {unused_weights}" )
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case , snake_case , snake_case ) -> str:
_UpperCAmelCase = full_name.split("""conv_layers.""" )[-1]
_UpperCAmelCase = name.split(""".""" )
_UpperCAmelCase = int(items[0] )
_UpperCAmelCase = int(items[1] )
if type_id == 0:
if "bias" in name:
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." )
_UpperCAmelCase = 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." )
_UpperCAmelCase = value
logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
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[layer_id].layer_norm.bias.data.shape} was found." )
_UpperCAmelCase = value
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
elif "weight" in name:
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[layer_id].layer_norm.weight.data.shape} was found." )
_UpperCAmelCase = value
logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
else:
unused_weights.append(snake_case )
@torch.no_grad()
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case=None , snake_case=None , snake_case=True ) -> List[Any]:
if config_path is not None:
_UpperCAmelCase = UniSpeechSatConfig.from_pretrained(snake_case )
else:
_UpperCAmelCase = UniSpeechSatConfig()
_UpperCAmelCase = """"""
if is_finetuned:
_UpperCAmelCase = UniSpeechSatForCTC(snake_case )
else:
_UpperCAmelCase = UniSpeechSatForPreTraining(snake_case )
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} )
_UpperCAmelCase = model[0].eval()
recursively_load_weights(snake_case , snake_case )
hf_wavavec.save_pretrained(snake_case )
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_unispeech_sat_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
) | 175 | 0 |
'''simple docstring'''
import argparse
import glob
import logging
import os
import time
from argparse import Namespace
import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from torch.utils.data import DataLoader, TensorDataset
from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes, glue_tasks_num_labels
from transformers import glue_processors as processors
__lowerCamelCase = logging.getLogger(__name__)
class A__ ( _snake_case ):
lowercase = "sequence-classification"
def __init__( self , UpperCamelCase__ ) -> int:
'''simple docstring'''
if type(UpperCamelCase__ ) == dict:
A_ = Namespace(**UpperCamelCase__ )
A_ = glue_output_modes[hparams.task]
A_ = glue_tasks_num_labels[hparams.task]
super().__init__(UpperCamelCase__ , UpperCamelCase__ , self.mode )
def snake_case_ ( self , **UpperCamelCase__ ) -> Dict:
'''simple docstring'''
return self.model(**UpperCamelCase__ )
def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ ) -> str:
'''simple docstring'''
A_ = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
A_ = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None
A_ = self(**UpperCamelCase__ )
A_ = outputs[0]
A_ = self.trainer.lr_schedulers[0]["""scheduler"""]
A_ = {"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]}
return {"loss": loss, "log": tensorboard_logs}
def snake_case_ ( self ) -> Optional[int]:
'''simple docstring'''
A_ = self.hparams
A_ = processors[args.task]()
A_ = processor.get_labels()
for mode in ["train", "dev"]:
A_ = self._feature_file(UpperCamelCase__ )
if os.path.exists(UpperCamelCase__ ) and not args.overwrite_cache:
logger.info("""Loading features from cached file %s""" , UpperCamelCase__ )
else:
logger.info("""Creating features from dataset file at %s""" , args.data_dir )
A_ = (
processor.get_dev_examples(args.data_dir )
if mode == """dev"""
else processor.get_train_examples(args.data_dir )
)
A_ = convert_examples_to_features(
UpperCamelCase__ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , )
logger.info("""Saving features into cached file %s""" , UpperCamelCase__ )
torch.save(UpperCamelCase__ , UpperCamelCase__ )
def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = False ) -> DataLoader:
'''simple docstring'''
A_ = """dev""" if mode == """test""" else mode
A_ = self._feature_file(UpperCamelCase__ )
logger.info("""Loading features from cached file %s""" , UpperCamelCase__ )
A_ = torch.load(UpperCamelCase__ )
A_ = torch.tensor([f.input_ids for f in features] , dtype=torch.long )
A_ = torch.tensor([f.attention_mask for f in features] , dtype=torch.long )
A_ = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long )
if self.hparams.glue_output_mode == "classification":
A_ = torch.tensor([f.label for f in features] , dtype=torch.long )
elif self.hparams.glue_output_mode == "regression":
A_ = torch.tensor([f.label for f in features] , dtype=torch.float )
return DataLoader(
TensorDataset(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , batch_size=UpperCamelCase__ , shuffle=UpperCamelCase__ , )
def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Any:
'''simple docstring'''
A_ = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]}
if self.config.model_type not in ["distilbert", "bart"]:
A_ = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None
A_ = self(**UpperCamelCase__ )
A_ , A_ = outputs[:2]
A_ = logits.detach().cpu().numpy()
A_ = inputs["""labels"""].detach().cpu().numpy()
return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
def snake_case_ ( self , UpperCamelCase__ ) -> tuple:
'''simple docstring'''
A_ = torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item()
A_ = np.concatenate([x["""pred"""] for x in outputs] , axis=0 )
if self.hparams.glue_output_mode == "classification":
A_ = np.argmax(UpperCamelCase__ , axis=1 )
elif self.hparams.glue_output_mode == "regression":
A_ = np.squeeze(UpperCamelCase__ )
A_ = np.concatenate([x["""target"""] for x in outputs] , axis=0 )
A_ = [[] for _ in range(out_label_ids.shape[0] )]
A_ = [[] for _ in range(out_label_ids.shape[0] )]
A_ = {**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , UpperCamelCase__ , UpperCamelCase__ )}
A_ = dict(results.items() )
A_ = results
return ret, preds_list, out_label_list
def snake_case_ ( self , UpperCamelCase__ ) -> dict:
'''simple docstring'''
A_ , A_ , A_ = self._eval_end(UpperCamelCase__ )
A_ = ret["""log"""]
return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
def snake_case_ ( self , UpperCamelCase__ ) -> dict:
'''simple docstring'''
A_ , A_ , A_ = self._eval_end(UpperCamelCase__ )
A_ = ret["""log"""]
# `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
@staticmethod
def snake_case_ ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]:
'''simple docstring'''
BaseTransformer.add_model_specific_args(UpperCamelCase__ , UpperCamelCase__ )
parser.add_argument(
"""--max_seq_length""" , default=128 , type=UpperCamelCase__ , help=(
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
) , )
parser.add_argument(
"""--task""" , default="""""" , type=UpperCamelCase__ , required=UpperCamelCase__ , help="""The GLUE task to run""" , )
parser.add_argument(
"""--gpus""" , default=0 , type=UpperCamelCase__ , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , )
parser.add_argument(
"""--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" )
return parser
def UpperCAmelCase__ ( ) -> List[str]:
A_ = argparse.ArgumentParser()
add_generic_args(UpperCAmelCase__, os.getcwd() )
A_ = GLUETransformer.add_model_specific_args(UpperCAmelCase__, os.getcwd() )
A_ = parser.parse_args()
# If output_dir not provided, a folder will be generated in pwd
if args.output_dir is None:
A_ = os.path.join(
"""./results""", F'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''', )
os.makedirs(args.output_dir )
A_ = GLUETransformer(UpperCAmelCase__ )
A_ = generic_train(UpperCAmelCase__, UpperCAmelCase__ )
# Optionally, predict on dev set and write to output_dir
if args.do_predict:
A_ = sorted(glob.glob(os.path.join(args.output_dir, """checkpoint-epoch=*.ckpt""" ), recursive=UpperCAmelCase__ ) )
A_ = model.load_from_checkpoint(checkpoints[-1] )
return trainer.test(UpperCAmelCase__ )
if __name__ == "__main__":
main()
| 288 |
'''simple docstring'''
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
__lowerCamelCase = logging.get_logger(__name__)
__lowerCamelCase = {
'''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''',
'''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''',
'''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''',
'''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''',
'''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''',
'''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''',
'''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''',
'''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''',
'''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''',
'''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''',
'''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''',
'''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''',
}
class A__ ( _snake_case ):
lowercase = "codegen"
lowercase = {
"max_position_embeddings": "n_positions",
"hidden_size": "n_embd",
"num_attention_heads": "n_head",
"num_hidden_layers": "n_layer",
}
def __init__( self , UpperCamelCase__=50400 , UpperCamelCase__=2048 , UpperCamelCase__=2048 , UpperCamelCase__=4096 , UpperCamelCase__=28 , UpperCamelCase__=16 , UpperCamelCase__=64 , UpperCamelCase__=None , UpperCamelCase__="gelu_new" , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=0.0 , UpperCamelCase__=1e-5 , UpperCamelCase__=0.02 , UpperCamelCase__=True , UpperCamelCase__=50256 , UpperCamelCase__=50256 , UpperCamelCase__=False , **UpperCamelCase__ , ) -> Tuple:
'''simple docstring'''
A_ = vocab_size
A_ = n_ctx
A_ = n_positions
A_ = n_embd
A_ = n_layer
A_ = n_head
A_ = n_inner
A_ = rotary_dim
A_ = activation_function
A_ = resid_pdrop
A_ = embd_pdrop
A_ = attn_pdrop
A_ = layer_norm_epsilon
A_ = initializer_range
A_ = use_cache
A_ = bos_token_id
A_ = eos_token_id
super().__init__(
bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , tie_word_embeddings=UpperCamelCase__ , **UpperCamelCase__ )
class A__ ( _snake_case ):
def __init__( self , UpperCamelCase__ , UpperCamelCase__ = "default" , UpperCamelCase__ = None , UpperCamelCase__ = False , ) -> Tuple:
'''simple docstring'''
super().__init__(UpperCamelCase__ , task=UpperCamelCase__ , patching_specs=UpperCamelCase__ , use_past=UpperCamelCase__ )
if not getattr(self._config , """pad_token_id""" , UpperCamelCase__ ):
# TODO: how to do that better?
A_ = 0
@property
def snake_case_ ( self ) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
A_ = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} )
if self.use_past:
self.fill_with_past_key_values_(UpperCamelCase__ , direction="""inputs""" )
A_ = {0: """batch""", 1: """past_sequence + sequence"""}
else:
A_ = {0: """batch""", 1: """sequence"""}
return common_inputs
@property
def snake_case_ ( self ) -> int:
'''simple docstring'''
return self._config.n_layer
@property
def snake_case_ ( self ) -> int:
'''simple docstring'''
return self._config.n_head
def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ = -1 , UpperCamelCase__ = -1 , UpperCamelCase__ = False , UpperCamelCase__ = None , ) -> Mapping[str, Any]:
'''simple docstring'''
A_ = super(UpperCamelCase__ , self ).generate_dummy_inputs(
UpperCamelCase__ , batch_size=UpperCamelCase__ , seq_length=UpperCamelCase__ , is_pair=UpperCamelCase__ , framework=UpperCamelCase__ )
# We need to order the input in the way they appears in the forward()
A_ = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} )
# Need to add the past_keys
if self.use_past:
if not is_torch_available():
raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" )
else:
import torch
A_ , A_ = common_inputs["""input_ids"""].shape
# Not using the same length for past_key_values
A_ = seqlen + 2
A_ = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
A_ = [
(torch.zeros(UpperCamelCase__ ), torch.zeros(UpperCamelCase__ )) for _ in range(self.num_layers )
]
A_ = common_inputs["""attention_mask"""]
if self.use_past:
A_ = ordered_inputs["""attention_mask"""].dtype
A_ = torch.cat(
[ordered_inputs["""attention_mask"""], torch.ones(UpperCamelCase__ , UpperCamelCase__ , dtype=UpperCamelCase__ )] , dim=1 )
return ordered_inputs
@property
def snake_case_ ( self ) -> int:
'''simple docstring'''
return 13
| 288 | 1 |
'''simple docstring'''
def a__ ( __UpperCamelCase , __UpperCamelCase ):
if mass < 0:
raise ValueError("The mass of a body cannot be negative" )
return 0.5 * mass * abs(lowerCAmelCase_ ) * abs(lowerCAmelCase_ )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 703 | import dataclasses
import re
import string
from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple
import numpy as np
from . import residue_constants
A : int = Mapping[str, np.ndarray]
A : Any = Mapping[str, Any] # Is a nested dict.
A : Dict = 0.01
@dataclasses.dataclass(frozen=SCREAMING_SNAKE_CASE__ )
class lowerCamelCase :
"""simple docstring"""
lowerCamelCase__ = 42 # [num_res, num_atom_type, 3]
# Amino-acid type for each residue represented as an integer between 0 and
# 20, where 20 is 'X'.
lowerCamelCase__ = 42 # [num_res]
# Binary float mask to indicate presence of a particular atom. 1.0 if an atom
# is present and 0.0 if not. This should be used for loss masking.
lowerCamelCase__ = 42 # [num_res, num_atom_type]
# Residue index as used in PDB. It is not necessarily continuous or 0-indexed.
lowerCamelCase__ = 42 # [num_res]
# B-factors, or temperature factors, of each residue (in sq. angstroms units),
# representing the displacement of the residue from its ground truth mean
# value.
lowerCamelCase__ = 42 # [num_res, num_atom_type]
# Chain indices for multi-chain predictions
lowerCamelCase__ = None
# Optional remark about the protein. Included as a comment in output PDB
# files
lowerCamelCase__ = None
# Templates used to generate this protein (prediction-only)
lowerCamelCase__ = None
# Chain corresponding to each parent
lowerCamelCase__ = None
def a__ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = r"(\[[A-Z]+\]\n)"
SCREAMING_SNAKE_CASE_ = [tag.strip() for tag in re.split(__UpperCamelCase , __UpperCamelCase ) if len(__UpperCamelCase ) > 0]
SCREAMING_SNAKE_CASE_ = zip(tags[0::2] , [l.split("\n" ) for l in tags[1::2]] )
SCREAMING_SNAKE_CASE_ = ["N", "CA", "C"]
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
for g in groups:
if "[PRIMARY]" == g[0]:
SCREAMING_SNAKE_CASE_ = g[1][0].strip()
for i in range(len(__UpperCamelCase ) ):
if seq[i] not in residue_constants.restypes:
SCREAMING_SNAKE_CASE_ = "X" # FIXME: strings are immutable
SCREAMING_SNAKE_CASE_ = np.array(
[residue_constants.restype_order.get(__UpperCamelCase , residue_constants.restype_num ) for res_symbol in seq] )
elif "[TERTIARY]" == g[0]:
SCREAMING_SNAKE_CASE_ = []
for axis in range(3 ):
tertiary.append(list(map(__UpperCamelCase , g[1][axis].split() ) ) )
SCREAMING_SNAKE_CASE_ = np.array(__UpperCamelCase )
SCREAMING_SNAKE_CASE_ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa )
for i, atom in enumerate(__UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = np.transpose(tertiary_np[:, i::3] )
atom_positions *= PICO_TO_ANGSTROM
elif "[MASK]" == g[0]:
SCREAMING_SNAKE_CASE_ = np.array(list(map({"-": 0, "+": 1}.get , g[1][0].strip() ) ) )
SCREAMING_SNAKE_CASE_ = np.zeros(
(
len(__UpperCamelCase ),
residue_constants.atom_type_num,
) ).astype(np.floataa )
for i, atom in enumerate(__UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = 1
atom_mask *= mask[..., None]
assert aatype is not None
return Protein(
atom_positions=__UpperCamelCase , atom_mask=__UpperCamelCase , aatype=__UpperCamelCase , residue_index=np.arange(len(__UpperCamelCase ) ) , b_factors=__UpperCamelCase , )
def a__ ( __UpperCamelCase , __UpperCamelCase = 0 ):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = prot.remark
if remark is not None:
pdb_headers.append(F'''REMARK {remark}''' )
SCREAMING_SNAKE_CASE_ = prot.parents
SCREAMING_SNAKE_CASE_ = prot.parents_chain_index
if parents is not None and parents_chain_index is not None:
SCREAMING_SNAKE_CASE_ = [p for i, p in zip(__UpperCamelCase , __UpperCamelCase ) if i == chain_id]
if parents is None or len(__UpperCamelCase ) == 0:
SCREAMING_SNAKE_CASE_ = ["N/A"]
pdb_headers.append(F'''PARENT {" ".join(__UpperCamelCase )}''' )
return pdb_headers
def a__ ( __UpperCamelCase , __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = pdb_str.split("\n" )
SCREAMING_SNAKE_CASE_ = prot.remark
if remark is not None:
out_pdb_lines.append(F'''REMARK {remark}''' )
SCREAMING_SNAKE_CASE_ = 42
if prot.parents is not None and len(prot.parents ) > 0:
SCREAMING_SNAKE_CASE_ = []
if prot.parents_chain_index is not None:
SCREAMING_SNAKE_CASE_ = {}
for p, i in zip(prot.parents , prot.parents_chain_index ):
parent_dict.setdefault(str(__UpperCamelCase ) , [] )
parent_dict[str(__UpperCamelCase )].append(__UpperCamelCase )
SCREAMING_SNAKE_CASE_ = max([int(__UpperCamelCase ) for chain_idx in parent_dict] )
for i in range(max_idx + 1 ):
SCREAMING_SNAKE_CASE_ = parent_dict.get(str(__UpperCamelCase ) , ["N/A"] )
parents_per_chain.append(__UpperCamelCase )
else:
parents_per_chain.append(list(prot.parents ) )
else:
SCREAMING_SNAKE_CASE_ = [["N/A"]]
def make_parent_line(__UpperCamelCase ) -> str:
return F'''PARENT {" ".join(__UpperCamelCase )}'''
out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) )
SCREAMING_SNAKE_CASE_ = 0
for i, l in enumerate(__UpperCamelCase ):
if "PARENT" not in l and "REMARK" not in l:
out_pdb_lines.append(__UpperCamelCase )
if "TER" in l and "END" not in lines[i + 1]:
chain_counter += 1
if not chain_counter >= len(__UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = parents_per_chain[chain_counter]
else:
SCREAMING_SNAKE_CASE_ = ["N/A"]
out_pdb_lines.append(make_parent_line(__UpperCamelCase ) )
return "\n".join(__UpperCamelCase )
def a__ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = residue_constants.restypes + ["X"]
def res_atoa(__UpperCamelCase ) -> str:
return residue_constants.restype_atoa.get(restypes[r] , "UNK" )
SCREAMING_SNAKE_CASE_ = residue_constants.atom_types
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = prot.atom_mask
SCREAMING_SNAKE_CASE_ = prot.aatype
SCREAMING_SNAKE_CASE_ = prot.atom_positions
SCREAMING_SNAKE_CASE_ = prot.residue_index.astype(np.intaa )
SCREAMING_SNAKE_CASE_ = prot.b_factors
SCREAMING_SNAKE_CASE_ = prot.chain_index
if np.any(aatype > residue_constants.restype_num ):
raise ValueError("Invalid aatypes." )
SCREAMING_SNAKE_CASE_ = get_pdb_headers(__UpperCamelCase )
if len(__UpperCamelCase ) > 0:
pdb_lines.extend(__UpperCamelCase )
SCREAMING_SNAKE_CASE_ = aatype.shape[0]
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = string.ascii_uppercase
SCREAMING_SNAKE_CASE_ = None
# Add all atom sites.
for i in range(__UpperCamelCase ):
SCREAMING_SNAKE_CASE_ = res_atoa(aatype[i] )
for atom_name, pos, mask, b_factor in zip(__UpperCamelCase , atom_positions[i] , atom_mask[i] , b_factors[i] ):
if mask < 0.5:
continue
SCREAMING_SNAKE_CASE_ = "ATOM"
SCREAMING_SNAKE_CASE_ = atom_name if len(__UpperCamelCase ) == 4 else F''' {atom_name}'''
SCREAMING_SNAKE_CASE_ = ""
SCREAMING_SNAKE_CASE_ = ""
SCREAMING_SNAKE_CASE_ = 1.00
SCREAMING_SNAKE_CASE_ = atom_name[0] # Protein supports only C, N, O, S, this works.
SCREAMING_SNAKE_CASE_ = ""
SCREAMING_SNAKE_CASE_ = "A"
if chain_index is not None:
SCREAMING_SNAKE_CASE_ = chain_tags[chain_index[i]]
# PDB is a columnar format, every space matters here!
SCREAMING_SNAKE_CASE_ = (
F'''{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}'''
F'''{res_name_a:>3} {chain_tag:>1}'''
F'''{residue_index[i]:>4}{insertion_code:>1} '''
F'''{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}'''
F'''{occupancy:>6.2f}{b_factor:>6.2f} '''
F'''{element:>2}{charge:>2}'''
)
pdb_lines.append(__UpperCamelCase )
atom_index += 1
SCREAMING_SNAKE_CASE_ = i == n - 1
if chain_index is not None:
if i != n - 1 and chain_index[i + 1] != prev_chain_index:
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = chain_index[i + 1]
if should_terminate:
# Close the chain.
SCREAMING_SNAKE_CASE_ = "TER"
SCREAMING_SNAKE_CASE_ = (
F'''{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}'''
)
pdb_lines.append(__UpperCamelCase )
atom_index += 1
if i != n - 1:
# "prev" is a misnomer here. This happens at the beginning of
# each new chain.
pdb_lines.extend(get_pdb_headers(__UpperCamelCase , __UpperCamelCase ) )
pdb_lines.append("END" )
pdb_lines.append("" )
return "\n".join(__UpperCamelCase )
def a__ ( __UpperCamelCase ):
return residue_constants.STANDARD_ATOM_MASK[prot.aatype]
def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase = None , ):
return Protein(
aatype=features["aatype"] , atom_positions=result["final_atom_positions"] , atom_mask=result["final_atom_mask"] , residue_index=features["residue_index"] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result["final_atom_mask"] ) , chain_index=__UpperCamelCase , remark=__UpperCamelCase , parents=__UpperCamelCase , parents_chain_index=__UpperCamelCase , )
| 356 | 0 |
import warnings
from contextlib import contextmanager
from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer
class SCREAMING_SNAKE_CASE ( a_ ):
"""simple docstring"""
lowerCamelCase : List[str] ="Wav2Vec2FeatureExtractor"
lowerCamelCase : Optional[int] ="AutoTokenizer"
def __init__( self : Optional[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : List[Any] ) -> int:
"""simple docstring"""
super().__init__(lowerCAmelCase , lowerCAmelCase )
__lowerCAmelCase : Dict = self.feature_extractor
__lowerCAmelCase : Optional[int] = False
@classmethod
def SCREAMING_SNAKE_CASE ( cls : Optional[int] , lowerCAmelCase : Tuple , **lowerCAmelCase : List[Any] ) -> str:
"""simple docstring"""
try:
return super().from_pretrained(lowerCAmelCase , **lowerCAmelCase )
except OSError:
warnings.warn(
f'''Loading a tokenizer inside {cls.__name__} from a config that does not'''
""" include a `tokenizer_class` attribute is deprecated and will be """
"""removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`"""
""" attribute to either your `config.json` or `tokenizer_config.json` """
"""file to suppress this warning: """ , lowerCAmelCase , )
__lowerCAmelCase : Tuple = WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase , **lowerCAmelCase )
__lowerCAmelCase : List[str] = WavaVecaCTCTokenizer.from_pretrained(lowerCAmelCase , **lowerCAmelCase )
return cls(feature_extractor=lowerCAmelCase , tokenizer=lowerCAmelCase )
def __call__( self : Optional[int] , *lowerCAmelCase : Optional[Any] , **lowerCAmelCase : Optional[int] ) -> Tuple:
"""simple docstring"""
if self._in_target_context_manager:
return self.current_processor(*lowerCAmelCase , **lowerCAmelCase )
if "raw_speech" in kwargs:
warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" )
__lowerCAmelCase : List[Any] = kwargs.pop("""raw_speech""" )
else:
__lowerCAmelCase : List[str] = kwargs.pop("""audio""" , lowerCAmelCase )
__lowerCAmelCase : Any = kwargs.pop("""sampling_rate""" , lowerCAmelCase )
__lowerCAmelCase : Dict = kwargs.pop("""text""" , lowerCAmelCase )
if len(lowerCAmelCase ) > 0:
__lowerCAmelCase : Union[str, Any] = args[0]
__lowerCAmelCase : 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:
__lowerCAmelCase : Any = self.feature_extractor(lowerCAmelCase , *lowerCAmelCase , sampling_rate=lowerCAmelCase , **lowerCAmelCase )
if text is not None:
__lowerCAmelCase : Dict = self.tokenizer(lowerCAmelCase , **lowerCAmelCase )
if text is None:
return inputs
elif audio is None:
return encodings
else:
__lowerCAmelCase : Dict = encodings["""input_ids"""]
return inputs
def SCREAMING_SNAKE_CASE ( self : List[Any] , *lowerCAmelCase : Optional[Any] , **lowerCAmelCase : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
if self._in_target_context_manager:
return self.current_processor.pad(*lowerCAmelCase , **lowerCAmelCase )
__lowerCAmelCase : Optional[Any] = kwargs.pop("""input_features""" , lowerCAmelCase )
__lowerCAmelCase : List[Any] = kwargs.pop("""labels""" , lowerCAmelCase )
if len(lowerCAmelCase ) > 0:
__lowerCAmelCase : Dict = args[0]
__lowerCAmelCase : List[str] = args[1:]
if input_features is not None:
__lowerCAmelCase : str = self.feature_extractor.pad(lowerCAmelCase , *lowerCAmelCase , **lowerCAmelCase )
if labels is not None:
__lowerCAmelCase : Optional[Any] = self.tokenizer.pad(lowerCAmelCase , **lowerCAmelCase )
if labels is None:
return input_features
elif input_features is None:
return labels
else:
__lowerCAmelCase : Tuple = labels["""input_ids"""]
return input_features
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowerCAmelCase : Any , **lowerCAmelCase : List[Any] ) -> Dict:
"""simple docstring"""
return self.tokenizer.batch_decode(*lowerCAmelCase , **lowerCAmelCase )
def SCREAMING_SNAKE_CASE ( self : Tuple , *lowerCAmelCase : Tuple , **lowerCAmelCase : List[str] ) -> Tuple:
"""simple docstring"""
return self.tokenizer.decode(*lowerCAmelCase , **lowerCAmelCase )
@contextmanager
def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str:
"""simple docstring"""
warnings.warn(
"""`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
"""labels by using the argument `text` of the regular `__call__` method (either in the same call as """
"""your audio inputs, or in a separate call.""" )
__lowerCAmelCase : Optional[Any] = True
__lowerCAmelCase : Optional[Any] = self.tokenizer
yield
__lowerCAmelCase : str = self.feature_extractor
__lowerCAmelCase : Any = False
| 651 |
from __future__ import annotations
def snake_case_ (__A : list[int] , __A : list[int] , __A : list[int] , __A : list[list[str]] , __A : int , ) -> None:
__lowerCAmelCase : Any = len(__A )
# 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(__A ):
# 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] , __A , __A , )
def snake_case_ (__A : int ) -> None:
__lowerCAmelCase : list[list[str]] = []
depth_first_search([] , [] , [] , __A , __A )
# Print all the boards
for board in boards:
for column in board:
print(__A )
print("""""" )
print(len(__A ) , """solutions were found.""" )
if __name__ == "__main__":
import doctest
doctest.testmod()
n_queens_solution(4)
| 651 | 1 |
import copy
from typing import Any, Dict, List, Optional, Union
import numpy as np
import torch
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging
UpperCAmelCase = logging.get_logger(__name__)
class __snake_case ( UpperCamelCase__):
'''simple docstring'''
UpperCamelCase__ : List[str] = ["""input_features""", """is_longer"""]
def __init__( self , a_=64 , a_=48_000 , a_=480 , a_=10 , a_=1_024 , a_=0.0 , a_=False , a_ = 0 , a_ = 14_000 , a_ = None , a_ = "fusion" , a_ = "repeatpad" , **a_ , ):
super().__init__(
feature_size=__A , sampling_rate=__A , padding_value=__A , return_attention_mask=__A , **__A , )
a__ = top_db
a__ = truncation
a__ = padding
a__ = fft_window_size
a__ = (fft_window_size >> 1) + 1
a__ = hop_length
a__ = max_length_s
a__ = max_length_s * sampling_rate
a__ = sampling_rate
a__ = frequency_min
a__ = frequency_max
a__ = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__A , min_frequency=__A , max_frequency=__A , sampling_rate=__A , norm=__A , mel_scale="""htk""" , )
a__ = mel_filter_bank(
num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__A , min_frequency=__A , max_frequency=__A , sampling_rate=__A , norm="""slaney""" , mel_scale="""slaney""" , )
def _a ( self ):
a__ = copy.deepcopy(self.__dict__ )
a__ = 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 _a ( self , a_ , a_ = None ):
a__ = spectrogram(
__A , window_function(self.fft_window_size , """hann""" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=__A , log_mel="""dB""" , )
return log_mel_spectrogram.T
def _a ( self , a_ , a_ , a_ ):
a__ = 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__ = [0]
if len(ranges[2] ) == 0:
# if the audio is too short, we just use the first chunk
a__ = [0]
# randomly choose index for each part
a__ = np.random.choice(ranges[0] )
a__ = np.random.choice(ranges[1] )
a__ = np.random.choice(ranges[2] )
a__ = mel[idx_front : idx_front + chunk_frames, :]
a__ = mel[idx_middle : idx_middle + chunk_frames, :]
a__ = mel[idx_back : idx_back + chunk_frames, :]
a__ = torch.tensor(mel[None, None, :] )
a__ = torch.nn.functional.interpolate(
__A , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=__A )
a__ = mel_shrink[0][0].numpy()
a__ = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 )
return mel_fusion
def _a ( self , a_ , a_ , a_ , a_ ):
if waveform.shape[0] > max_length:
if truncation == "rand_trunc":
a__ = True
# random crop to max_length (for compatibility) -> this should be handled by self.pad
a__ = len(__A ) - max_length
a__ = np.random.randint(0 , overflow + 1 )
a__ = waveform[idx : idx + max_length]
a__ = self._np_extract_fbank_features(__A , self.mel_filters_slaney )[None, :]
elif truncation == "fusion":
a__ = self._np_extract_fbank_features(__A , self.mel_filters )
a__ = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed
a__ = 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__ = np.stack([mel, mel, mel, mel] , axis=0 )
a__ = False
else:
a__ = self._random_mel_fusion(__A , __A , __A )
a__ = True
else:
raise NotImplementedError(F'''data_truncating {truncation} not implemented''' )
else:
a__ = 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__ = int(max_length / len(__A ) )
a__ = np.stack(np.tile(__A , n_repeat + 1 ) )[:max_length]
if padding == "repeatpad":
a__ = int(max_length / len(__A ) )
a__ = np.stack(np.tile(__A , __A ) )
a__ = np.pad(__A , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0 )
if truncation == "fusion":
a__ = self._np_extract_fbank_features(__A , self.mel_filters )
a__ = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 )
else:
a__ = self._np_extract_fbank_features(__A , self.mel_filters_slaney )[None, :]
return input_mel, longer
def __call__( self , a_ , a_ = None , a_ = None , a_ = None , a_ = None , a_ = None , **a_ , ):
a__ = truncation if truncation is not None else self.truncation
a__ = 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__ = isinstance(__A , 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__ = is_batched_numpy or (
isinstance(__A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
a__ = [np.asarray(__A , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(__A , np.ndarray ):
a__ = np.asarray(__A , dtype=np.floataa )
elif isinstance(__A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
a__ = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
a__ = [np.asarray(__A )]
# convert to mel spectrogram, truncate and pad if needed.
a__ = [
self._get_input_mel(__A , max_length if max_length else self.nb_max_samples , __A , __A )
for waveform in raw_speech
]
a__ = []
a__ = []
for mel, longer in padded_inputs:
input_mel.append(__A )
is_longer.append(__A )
if truncation == "fusion" and sum(__A ) == 0:
# if no audio is longer than 10s, then randomly select one audio to be longer
a__ = np.random.randint(0 , len(__A ) )
a__ = True
if isinstance(input_mel[0] , __A ):
a__ = [np.asarray(__A , dtype=np.floataa ) for feature in input_mel]
# is_longer is a list of bool
a__ = [[longer] for longer in is_longer]
a__ = {"""input_features""": input_mel, """is_longer""": is_longer}
a__ = BatchFeature(__A )
if return_tensors is not None:
a__ = input_features.convert_to_tensors(__A )
return input_features
| 715 |
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.local_sgd import LocalSGD
########################################################################
# This is a fully working simple example to use Accelerate
# with LocalSGD, which is a method to synchronize model
# parameters every K batches. It is different, but complementary
# to gradient accumulation.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
UpperCAmelCase = 16
UpperCAmelCase = 32
def A_ ( __a : Accelerator , __a : int = 16 ):
"""simple docstring"""
a__ = AutoTokenizer.from_pretrained("""bert-base-cased""" )
a__ = load_dataset("""glue""" , """mrpc""" )
def tokenize_function(__a : int ):
# max_length=None => use the model max length (it's actually the default)
a__ = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__a , max_length=__a )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
a__ = datasets.map(
__a , batched=__a , remove_columns=["""idx""", """sentence1""", """sentence2"""] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
a__ = tokenized_datasets.rename_column("""label""" , """labels""" )
def collate_fn(__a : Optional[int] ):
# On TPU it's best to pad everything to the same length or training will be very slow.
a__ = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
a__ = 16
elif accelerator.mixed_precision != "no":
a__ = 8
else:
a__ = None
return tokenizer.pad(
__a , padding="""longest""" , max_length=__a , pad_to_multiple_of=__a , return_tensors="""pt""" , )
# Instantiate dataloaders.
a__ = DataLoader(
tokenized_datasets["""train"""] , shuffle=__a , collate_fn=__a , batch_size=__a )
a__ = DataLoader(
tokenized_datasets["""validation"""] , shuffle=__a , collate_fn=__a , batch_size=__a )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
UpperCAmelCase = mocked_dataloaders # noqa: F811
def A_ ( __a : List[Any] , __a : Tuple ):
"""simple docstring"""
# For testing only
if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __a ) == "1":
a__ = 2
# New Code #
a__ = int(args.gradient_accumulation_steps )
a__ = int(args.local_sgd_steps )
# Initialize accelerator
a__ = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=__a )
if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]:
raise NotImplementedError("""LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)""" )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
a__ = config["""lr"""]
a__ = int(config["""num_epochs"""] )
a__ = int(config["""seed"""] )
a__ = int(config["""batch_size"""] )
a__ = evaluate.load("""glue""" , """mrpc""" )
set_seed(__a )
a__ , a__ = get_dataloaders(__a , __a )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
a__ = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__a )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
a__ = model.to(accelerator.device )
# Instantiate optimizer
a__ = AdamW(params=model.parameters() , lr=__a )
# Instantiate scheduler
a__ = get_linear_schedule_with_warmup(
optimizer=__a , num_warmup_steps=100 , num_training_steps=(len(__a ) * num_epochs) , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
a__ , a__ , a__ , a__ , a__ = accelerator.prepare(
__a , __a , __a , __a , __a )
# Now we train the model
for epoch in range(__a ):
model.train()
with LocalSGD(
accelerator=__a , model=__a , local_sgd_steps=__a , enabled=local_sgd_steps is not None ) as local_sgd:
for step, batch in enumerate(__a ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
# New code #
# We use the new `accumulate` context manager to perform gradient accumulation
# We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
with accelerator.accumulate(__a ):
a__ = model(**__a )
a__ = output.loss
accelerator.backward(__a )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
# LocalSGD-specific line
local_sgd.step()
model.eval()
for step, batch in enumerate(__a ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
a__ = model(**__a )
a__ = outputs.logits.argmax(dim=-1 )
a__ , a__ = accelerator.gather_for_metrics((predictions, batch["""labels"""]) )
metric.add_batch(
predictions=__a , references=__a , )
a__ = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}:''' , __a )
def A_ ( ):
"""simple docstring"""
a__ = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument(
"""--mixed_precision""" , type=__a , default=__a , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose"""
"""between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
"""and an Nvidia Ampere GPU.""" , )
# New Code #
parser.add_argument(
"""--gradient_accumulation_steps""" , type=__a , default=1 , help="""The number of minibatches to be ran before gradients are accumulated.""" , )
parser.add_argument(
"""--local_sgd_steps""" , type=__a , default=8 , help="""Number of local SGD steps or None to disable local SGD""" )
parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" )
a__ = parser.parse_args()
a__ = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
training_function(__a , __a )
if __name__ == "__main__":
main()
| 351 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.