code stringlengths 81 54k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : Optional[Any] = logging.get_logger(__name__)
UpperCamelCase__ : str = {
"tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json",
"tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json",
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : List[Any] = 'falcon'
__lowerCAmelCase : str = ['past_key_values']
def __init__( self , _A=65024 , _A=4544 , _A=32 , _A=71 , _A=1E-5 , _A=0.0_2 , _A=True , _A=0.0 , _A=0.0 , _A=None , _A=False , _A=False , _A=True , _A=True , _A=False , _A=11 , _A=11 , **_A , ):
SCREAMING_SNAKE_CASE_ = vocab_size
# Backward compatibility with n_embed kwarg
SCREAMING_SNAKE_CASE_ = kwargs.pop('n_embed' , _A)
SCREAMING_SNAKE_CASE_ = hidden_size if n_embed is None else n_embed
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = layer_norm_epsilon
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = hidden_dropout
SCREAMING_SNAKE_CASE_ = attention_dropout
SCREAMING_SNAKE_CASE_ = bos_token_id
SCREAMING_SNAKE_CASE_ = eos_token_id
SCREAMING_SNAKE_CASE_ = num_attention_heads if num_kv_heads is None else num_kv_heads
SCREAMING_SNAKE_CASE_ = alibi
SCREAMING_SNAKE_CASE_ = new_decoder_architecture
SCREAMING_SNAKE_CASE_ = multi_query # Ignored when new_decoder_architecture is True
SCREAMING_SNAKE_CASE_ = parallel_attn
SCREAMING_SNAKE_CASE_ = bias
super().__init__(bos_token_id=_A , eos_token_id=_A , **_A)
@property
def lowerCAmelCase__ ( self):
return self.hidden_size // self.num_attention_heads
@property
def lowerCAmelCase__ ( self):
return not self.alibi
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
UpperCamelCase__ : List[str] = {
"microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json",
# See all BioGPT models at https://huggingface.co/models?filter=biogpt
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Any = 'biogpt'
def __init__( self , _A=42384 , _A=1024 , _A=24 , _A=16 , _A=4096 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1024 , _A=0.0_2 , _A=1E-12 , _A=True , _A=True , _A=0.0 , _A=0.0 , _A=1 , _A=0 , _A=2 , **_A , ):
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = scale_embedding
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = layerdrop
SCREAMING_SNAKE_CASE_ = activation_dropout
super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A)
| 620 | 1 |
import copy
import json
import os
import tempfile
from transformers import is_torch_available
from .test_configuration_utils import config_common_kwargs
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A=None , _A=True , _A=None , **_A):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = config_class
SCREAMING_SNAKE_CASE_ = has_text_modality
SCREAMING_SNAKE_CASE_ = kwargs
SCREAMING_SNAKE_CASE_ = common_properties
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict)
SCREAMING_SNAKE_CASE_ = (
['hidden_size', 'num_attention_heads', 'num_hidden_layers']
if self.common_properties is None
else self.common_properties
)
# Add common fields for text models
if self.has_text_modality:
common_properties.extend(['vocab_size'])
# Test that config has the common properties as getters
for prop in common_properties:
self.parent.assertTrue(hasattr(_A , _A) , msg=f"""`{prop}` does not exist""")
# Test that config has the common properties as setter
for idx, name in enumerate(_A):
try:
setattr(_A , _A , _A)
self.parent.assertEqual(
getattr(_A , _A) , _A , msg=f"""`{name} value {idx} expected, but was {getattr(_A , _A)}""")
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
# Test if config class can be called with Config(prop_name=..)
for idx, name in enumerate(_A):
try:
SCREAMING_SNAKE_CASE_ = self.config_class(**{name: idx})
self.parent.assertEqual(
getattr(_A , _A) , _A , msg=f"""`{name} value {idx} expected, but was {getattr(_A , _A)}""")
except NotImplementedError:
# Some models might not be able to implement setters for common_properties
# In that case, a NotImplementedError is raised
pass
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict)
SCREAMING_SNAKE_CASE_ = json.loads(config.to_json_string())
for key, value in self.inputs_dict.items():
self.parent.assertEqual(obj[key] , _A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
SCREAMING_SNAKE_CASE_ = os.path.join(_A , 'config.json')
config_first.to_json_file(_A)
SCREAMING_SNAKE_CASE_ = self.config_class.from_json_file(_A)
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict())
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict)
with tempfile.TemporaryDirectory() as tmpdirname:
config_first.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = self.config_class.from_pretrained(_A)
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict())
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict)
SCREAMING_SNAKE_CASE_ = 'test'
with tempfile.TemporaryDirectory() as tmpdirname:
SCREAMING_SNAKE_CASE_ = os.path.join(_A , _A)
config_first.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = self.config_class.from_pretrained(_A , subfolder=_A)
self.parent.assertEqual(config_second.to_dict() , config_first.to_dict())
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.config_class(**self.inputs_dict , num_labels=5)
self.parent.assertEqual(len(config.idalabel) , 5)
self.parent.assertEqual(len(config.labelaid) , 5)
SCREAMING_SNAKE_CASE_ = 3
self.parent.assertEqual(len(config.idalabel) , 3)
self.parent.assertEqual(len(config.labelaid) , 3)
def lowerCAmelCase__ ( self):
if self.config_class.is_composition:
return
SCREAMING_SNAKE_CASE_ = self.config_class()
self.parent.assertIsNotNone(_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = copy.deepcopy(_A)
SCREAMING_SNAKE_CASE_ = self.config_class(**_A)
SCREAMING_SNAKE_CASE_ = []
for key, value in config_common_kwargs.items():
if key == "torch_dtype":
if not is_torch_available():
continue
else:
import torch
if config.torch_dtype != torch.floataa:
wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa))
elif getattr(_A , _A) != value:
wrong_values.append((key, getattr(_A , _A), value))
if len(_A) > 0:
SCREAMING_SNAKE_CASE_ = '\n'.join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values])
raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""")
def lowerCAmelCase__ ( self):
self.create_and_test_config_common_properties()
self.create_and_test_config_to_json_string()
self.create_and_test_config_to_json_file()
self.create_and_test_config_from_and_save_pretrained()
self.create_and_test_config_from_and_save_pretrained_subfolder()
self.create_and_test_config_with_num_labels()
self.check_config_can_be_init_without_params()
self.check_config_arguments_init()
| 620 |
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A , _A , _A = None , ):
super().__init__()
self.register_modules(transformer=_A , vae=_A , scheduler=_A)
# create a imagenet -> id dictionary for easier use
SCREAMING_SNAKE_CASE_ = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(','):
SCREAMING_SNAKE_CASE_ = int(_A)
SCREAMING_SNAKE_CASE_ = dict(sorted(self.labels.items()))
def lowerCAmelCase__ ( self , _A):
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = list(_A)
for l in label:
if l not in self.labels:
raise ValueError(
f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""")
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self , _A , _A = 4.0 , _A = None , _A = 50 , _A = "pil" , _A = True , ):
SCREAMING_SNAKE_CASE_ = len(_A)
SCREAMING_SNAKE_CASE_ = self.transformer.config.sample_size
SCREAMING_SNAKE_CASE_ = self.transformer.config.in_channels
SCREAMING_SNAKE_CASE_ = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=_A , device=self.device , dtype=self.transformer.dtype , )
SCREAMING_SNAKE_CASE_ = torch.cat([latents] * 2) if guidance_scale > 1 else latents
SCREAMING_SNAKE_CASE_ = torch.tensor(_A , device=self.device).reshape(-1)
SCREAMING_SNAKE_CASE_ = torch.tensor([1000] * batch_size , device=self.device)
SCREAMING_SNAKE_CASE_ = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(_A)
for t in self.progress_bar(self.scheduler.timesteps):
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ = latent_model_input[: len(_A) // 2]
SCREAMING_SNAKE_CASE_ = torch.cat([half, half] , dim=0)
SCREAMING_SNAKE_CASE_ = self.scheduler.scale_model_input(_A , _A)
SCREAMING_SNAKE_CASE_ = t
if not torch.is_tensor(_A):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
SCREAMING_SNAKE_CASE_ = latent_model_input.device.type == 'mps'
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = torch.floataa if is_mps else torch.floataa
else:
SCREAMING_SNAKE_CASE_ = torch.intaa if is_mps else torch.intaa
SCREAMING_SNAKE_CASE_ = torch.tensor([timesteps] , dtype=_A , device=latent_model_input.device)
elif len(timesteps.shape) == 0:
SCREAMING_SNAKE_CASE_ = timesteps[None].to(latent_model_input.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
SCREAMING_SNAKE_CASE_ = timesteps.expand(latent_model_input.shape[0])
# predict noise model_output
SCREAMING_SNAKE_CASE_ = self.transformer(
_A , timestep=_A , class_labels=_A).sample
# perform guidance
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , len(_A) // 2 , dim=0)
SCREAMING_SNAKE_CASE_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
SCREAMING_SNAKE_CASE_ = torch.cat([half_eps, half_eps] , dim=0)
SCREAMING_SNAKE_CASE_ = torch.cat([eps, rest] , dim=1)
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , _A , dim=1)
else:
SCREAMING_SNAKE_CASE_ = noise_pred
# compute previous image: x_t -> x_t-1
SCREAMING_SNAKE_CASE_ = self.scheduler.step(_A , _A , _A).prev_sample
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = latent_model_input.chunk(2 , dim=0)
else:
SCREAMING_SNAKE_CASE_ = latent_model_input
SCREAMING_SNAKE_CASE_ = 1 / self.vae.config.scaling_factor * latents
SCREAMING_SNAKE_CASE_ = self.vae.decode(_A).sample
SCREAMING_SNAKE_CASE_ = (samples / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
SCREAMING_SNAKE_CASE_ = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_A)
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=_A)
| 620 | 1 |
import gc
import unittest
from diffusers import FlaxStableDiffusionInpaintPipeline
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 __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/sd2-inpaint/init_image.png')
SCREAMING_SNAKE_CASE_ = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png')
SCREAMING_SNAKE_CASE_ = 'xvjiarui/stable-diffusion-2-inpainting'
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = FlaxStableDiffusionInpaintPipeline.from_pretrained(_A , safety_checker=_A)
SCREAMING_SNAKE_CASE_ = 'Face of a yellow cat, high resolution, sitting on a park bench'
SCREAMING_SNAKE_CASE_ = jax.random.PRNGKey(0)
SCREAMING_SNAKE_CASE_ = 50
SCREAMING_SNAKE_CASE_ = jax.device_count()
SCREAMING_SNAKE_CASE_ = num_samples * [prompt]
SCREAMING_SNAKE_CASE_ = num_samples * [init_image]
SCREAMING_SNAKE_CASE_ = num_samples * [mask_image]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = pipeline.prepare_inputs(_A , _A , _A)
# shard inputs and rng
SCREAMING_SNAKE_CASE_ = replicate(_A)
SCREAMING_SNAKE_CASE_ = jax.random.split(_A , jax.device_count())
SCREAMING_SNAKE_CASE_ = shard(_A)
SCREAMING_SNAKE_CASE_ = shard(_A)
SCREAMING_SNAKE_CASE_ = shard(_A)
SCREAMING_SNAKE_CASE_ = pipeline(
_A , _A , _A , _A , _A , _A , jit=_A)
SCREAMING_SNAKE_CASE_ = output.images.reshape(_A , 512 , 512 , 3)
SCREAMING_SNAKE_CASE_ = images[0, 253:256, 253:256, -1]
SCREAMING_SNAKE_CASE_ = jnp.asarray(jax.device_get(image_slice.flatten()))
SCREAMING_SNAKE_CASE_ = jnp.array(
[0.3_6_1_1_3_0_7, 0.3_7_6_4_9_7_3_6, 0.3_7_5_7_4_0_8, 0.3_8_2_1_3_9_5_3, 0.3_9_2_9_5_1_6_7, 0.3_8_4_1_6_3_1, 0.4_1_5_5_4_9_7_8, 0.4_1_3_7_4_7_5, 0.4_2_1_7_0_8_4])
print(f"""output_slice: {output_slice}""")
assert jnp.abs(output_slice - expected_slice).max() < 1E-2
| 620 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class __snake_case :
def __init__( self , _A , _A , _A , _A , _A , _A=0.2 , _A=0.2):
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = conva_get[:2]
SCREAMING_SNAKE_CASE_ = conva_get[2]
SCREAMING_SNAKE_CASE_ = size_pa
SCREAMING_SNAKE_CASE_ = rate_w
SCREAMING_SNAKE_CASE_ = rate_t
SCREAMING_SNAKE_CASE_ = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5)
for i in range(self.conva[1])
]
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.conva[1]) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
def lowerCAmelCase__ ( self , _A):
# save model dict with pickle
SCREAMING_SNAKE_CASE_ = {
'num_bp1': self.num_bpa,
'num_bp2': self.num_bpa,
'num_bp3': self.num_bpa,
'conv1': self.conva,
'step_conv1': self.step_conva,
'size_pooling1': self.size_poolinga,
'rate_weight': self.rate_weight,
'rate_thre': self.rate_thre,
'w_conv1': self.w_conva,
'wkj': self.wkj,
'vji': self.vji,
'thre_conv1': self.thre_conva,
'thre_bp2': self.thre_bpa,
'thre_bp3': self.thre_bpa,
}
with open(_A , 'wb') as f:
pickle.dump(_A , _A)
print(f"""Model saved: {save_path}""")
@classmethod
def lowerCAmelCase__ ( cls , _A):
# read saved model
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = pickle.load(_A) # noqa: S301
SCREAMING_SNAKE_CASE_ = model_dic.get('conv1')
conv_get.append(model_dic.get('step_conv1'))
SCREAMING_SNAKE_CASE_ = model_dic.get('size_pooling1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp3')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_weight')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_thre')
# create model instance
SCREAMING_SNAKE_CASE_ = CNN(_A , _A , _A , _A , _A , _A , _A)
# modify model parameter
SCREAMING_SNAKE_CASE_ = model_dic.get('w_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('wkj')
SCREAMING_SNAKE_CASE_ = model_dic.get('vji')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp3')
return conv_ins
def lowerCAmelCase__ ( self , _A):
return 1 / (1 + np.exp(-1 * x))
def lowerCAmelCase__ ( self , _A):
return round(_A , 3)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
# convolution process
SCREAMING_SNAKE_CASE_ = convs[0]
SCREAMING_SNAKE_CASE_ = convs[1]
SCREAMING_SNAKE_CASE_ = np.shape(_A)[0]
# get the data slice of original image data, data_focus
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , size_data - size_conv + 1 , _A):
for j_focus in range(0 , size_data - size_conv + 1 , _A):
SCREAMING_SNAKE_CASE_ = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(_A)
# calculate the feature map of every single kernel, and saved as list of matrix
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = int((size_data - size_conv) / conv_step + 1)
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(len(_A)):
SCREAMING_SNAKE_CASE_ = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map]))
- thre_convs[i_map]
)
featuremap.append(self.sig(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(
_A , _A)
data_featuremap.append(_A)
# expanding the data slice to One dimenssion
SCREAMING_SNAKE_CASE_ = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(_A))
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return focus_list, data_featuremap
def lowerCAmelCase__ ( self , _A , _A , _A="average_pool"):
# pooling process
SCREAMING_SNAKE_CASE_ = len(featuremaps[0])
SCREAMING_SNAKE_CASE_ = int(size_map / size_pooling)
SCREAMING_SNAKE_CASE_ = []
for i_map in range(len(_A)):
SCREAMING_SNAKE_CASE_ = featuremaps[i_map]
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , _A , _A):
for j_focus in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(_A))
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(_A , _A)
featuremap_pooled.append(_A)
return featuremap_pooled
def lowerCAmelCase__ ( self , _A):
# expanding three dimension data to one dimension list
SCREAMING_SNAKE_CASE_ = []
for i in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.shape(data[i])
SCREAMING_SNAKE_CASE_ = data[i].reshape(1 , shapes[0] * shapes[1])
SCREAMING_SNAKE_CASE_ = data_listed.getA().tolist()[0]
data_expanded.extend(_A)
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return data_expanded
def lowerCAmelCase__ ( self , _A):
# expanding matrix to one dimension list
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = data_mat.reshape(1 , shapes[0] * shapes[1])
return data_expanded
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = np.ones((size_map, size_map))
for i in range(0 , _A , _A):
for j in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = pd_pool[
i_pool
]
SCREAMING_SNAKE_CASE_ = i_pool + 1
SCREAMING_SNAKE_CASE_ = np.multiply(
_A , np.multiply(out_map[i_map] , (1 - out_map[i_map])))
pd_all.append(_A)
return pd_all
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , _A=bool):
# model traning
print('----------------------Start Training-------------------------')
print((' - - Shape: Train_Data ', np.shape(_A)))
print((' - - Shape: Teach_Data ', np.shape(_A)))
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 10000
while rp < n_repeat and mse >= error_accuracy:
SCREAMING_SNAKE_CASE_ = 0
print(f"""-------------Learning Time {rp}--------------""")
for p in range(len(_A)):
# print('------------Learning Image: %d--------------'%p)
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_train[p])
SCREAMING_SNAKE_CASE_ = np.asarray(datas_teach[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.wkj.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
SCREAMING_SNAKE_CASE_ = np.multiply(
(data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.multiply(
np.dot(_A , self.wkj) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji)
SCREAMING_SNAKE_CASE_ = pd_i_all / (self.size_poolinga * self.size_poolinga)
SCREAMING_SNAKE_CASE_ = pd_conva_pooled.T.getA().tolist()
SCREAMING_SNAKE_CASE_ = self._calculate_gradient_from_pool(
_A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1]):
SCREAMING_SNAKE_CASE_ = self._expand_mat(pd_conva_all[k_conv])
SCREAMING_SNAKE_CASE_ = self.rate_weight * np.dot(_A , _A)
SCREAMING_SNAKE_CASE_ = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]))
SCREAMING_SNAKE_CASE_ = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv]) * self.rate_thre
)
# all connected layer
SCREAMING_SNAKE_CASE_ = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.vji + pd_j_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_k_all * self.rate_thre
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
SCREAMING_SNAKE_CASE_ = np.sum(abs(data_teach - bp_outa))
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
SCREAMING_SNAKE_CASE_ = rp + 1
SCREAMING_SNAKE_CASE_ = error_count / patterns
all_mse.append(_A)
def draw_error():
SCREAMING_SNAKE_CASE_ = [error_accuracy for i in range(int(n_repeat * 1.2))]
plt.plot(_A , '+-')
plt.plot(_A , 'r--')
plt.xlabel('Learning Times')
plt.ylabel('All_mse')
plt.grid(_A , alpha=0.5)
plt.show()
print('------------------Training Complished---------------------')
print((' - - Training epoch: ', rp, f""" - - Mse: {mse:.6f}"""))
if draw_e:
draw_error()
return mse
def lowerCAmelCase__ ( self , _A):
# model predict
SCREAMING_SNAKE_CASE_ = []
print('-------------------Start Testing-------------------------')
print((' - - Shape: Test_Data ', np.shape(_A)))
for p in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_test[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = bp_outa * self.vji.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = bp_outa * self.wkj.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
produce_out.extend(bp_outa.getA().tolist())
SCREAMING_SNAKE_CASE_ = [list(map(self.do_round , _A)) for each in produce_out]
return np.asarray(_A)
def lowerCAmelCase__ ( self , _A):
# return the data of image after convoluting process so we can check it out
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if index == number_of_items:
return 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 )
if weights[index] <= max_weight:
SCREAMING_SNAKE_CASE_ = values[index] + knapsack(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 )
return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
import os
import zipfile
import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int=7 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = None
if token is not None:
SCREAMING_SNAKE_CASE_ = {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}
# The id of a workflow (not of a workflow run)
SCREAMING_SNAKE_CASE_ = '636036'
SCREAMING_SNAKE_CASE_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""
SCREAMING_SNAKE_CASE_ = requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).json()
return result["workflow_runs"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_daily_ci_runs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = None
for workflow_run in workflow_runs:
if workflow_run["status"] == "completed":
SCREAMING_SNAKE_CASE_ = workflow_run['id']
break
return workflow_run_id
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE )
if workflow_run_id is not None:
SCREAMING_SNAKE_CASE_ = get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
for artifact_name in artifact_names:
if artifact_name in artifacts_links:
SCREAMING_SNAKE_CASE_ = artifacts_links[artifact_name]
download_artifact(
artifact_name=_SCREAMING_SNAKE_CASE , artifact_url=_SCREAMING_SNAKE_CASE , output_dir=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
for artifact_name in artifact_names:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{artifact_name}.zip""" )
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = {}
with zipfile.ZipFile(_SCREAMING_SNAKE_CASE ) as z:
for filename in z.namelist():
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
# read the file
with z.open(_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ = f.read().decode('UTF-8' )
return results
| 620 | 1 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import cached_download, hf_hub_url
from PIL import Image
from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = DPTConfig(embedding_type='hybrid' )
if "large" in checkpoint_url:
SCREAMING_SNAKE_CASE_ = 1_024
SCREAMING_SNAKE_CASE_ = 4_096
SCREAMING_SNAKE_CASE_ = 24
SCREAMING_SNAKE_CASE_ = 16
SCREAMING_SNAKE_CASE_ = [5, 11, 17, 23]
SCREAMING_SNAKE_CASE_ = [256, 512, 1_024, 1_024]
SCREAMING_SNAKE_CASE_ = (1, 384, 384)
if "nyu" or "midas" in checkpoint_url:
SCREAMING_SNAKE_CASE_ = 768
SCREAMING_SNAKE_CASE_ = [1, 1, 1, 0.5]
SCREAMING_SNAKE_CASE_ = [256, 512, 768, 768]
SCREAMING_SNAKE_CASE_ = 150
SCREAMING_SNAKE_CASE_ = 16
SCREAMING_SNAKE_CASE_ = (1, 384, 384)
SCREAMING_SNAKE_CASE_ = False
SCREAMING_SNAKE_CASE_ = 'project'
if "ade" in checkpoint_url:
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = 768
SCREAMING_SNAKE_CASE_ = [1, 1, 1, 0.5]
SCREAMING_SNAKE_CASE_ = 150
SCREAMING_SNAKE_CASE_ = 16
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = 'ade20k-id2label.json'
SCREAMING_SNAKE_CASE_ = json.load(open(cached_download(hf_hub_url(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = [1, 150, 480, 480]
return config, expected_shape
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = ['pretrained.model.head.weight', 'pretrained.model.head.bias']
for k in ignore_keys:
state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if (
"pretrained.model" in name
and "cls_token" not in name
and "pos_embed" not in name
and "patch_embed" not in name
):
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.model' , 'dpt.encoder' )
if "pretrained.model" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.model' , 'dpt.embeddings' )
if "patch_embed" in name:
SCREAMING_SNAKE_CASE_ = name.replace('patch_embed' , '' )
if "pos_embed" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pos_embed' , 'position_embeddings' )
if "attn.proj" in name:
SCREAMING_SNAKE_CASE_ = name.replace('attn.proj' , 'attention.output.dense' )
if "proj" in name and "project" not in name:
SCREAMING_SNAKE_CASE_ = name.replace('proj' , 'projection' )
if "blocks" in name:
SCREAMING_SNAKE_CASE_ = name.replace('blocks' , 'layer' )
if "mlp.fc1" in name:
SCREAMING_SNAKE_CASE_ = name.replace('mlp.fc1' , 'intermediate.dense' )
if "mlp.fc2" in name:
SCREAMING_SNAKE_CASE_ = name.replace('mlp.fc2' , 'output.dense' )
if "norm1" in name and "backbone" not in name:
SCREAMING_SNAKE_CASE_ = name.replace('norm1' , 'layernorm_before' )
if "norm2" in name and "backbone" not in name:
SCREAMING_SNAKE_CASE_ = name.replace('norm2' , 'layernorm_after' )
if "scratch.output_conv" in name:
SCREAMING_SNAKE_CASE_ = name.replace('scratch.output_conv' , 'head' )
if "scratch" in name:
SCREAMING_SNAKE_CASE_ = name.replace('scratch' , 'neck' )
if "layer1_rn" in name:
SCREAMING_SNAKE_CASE_ = name.replace('layer1_rn' , 'convs.0' )
if "layer2_rn" in name:
SCREAMING_SNAKE_CASE_ = name.replace('layer2_rn' , 'convs.1' )
if "layer3_rn" in name:
SCREAMING_SNAKE_CASE_ = name.replace('layer3_rn' , 'convs.2' )
if "layer4_rn" in name:
SCREAMING_SNAKE_CASE_ = name.replace('layer4_rn' , 'convs.3' )
if "refinenet" in name:
SCREAMING_SNAKE_CASE_ = int(name[len('neck.refinenet' ) : len('neck.refinenet' ) + 1] )
# tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
SCREAMING_SNAKE_CASE_ = name.replace(f"""refinenet{layer_idx}""" , f"""fusion_stage.layers.{abs(layer_idx-4 )}""" )
if "out_conv" in name:
SCREAMING_SNAKE_CASE_ = name.replace('out_conv' , 'projection' )
if "resConfUnit1" in name:
SCREAMING_SNAKE_CASE_ = name.replace('resConfUnit1' , 'residual_layer1' )
if "resConfUnit2" in name:
SCREAMING_SNAKE_CASE_ = name.replace('resConfUnit2' , 'residual_layer2' )
if "conv1" in name:
SCREAMING_SNAKE_CASE_ = name.replace('conv1' , 'convolution1' )
if "conv2" in name:
SCREAMING_SNAKE_CASE_ = name.replace('conv2' , 'convolution2' )
# readout blocks
if "pretrained.act_postprocess1.0.project.0" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess1.0.project.0' , 'neck.reassemble_stage.readout_projects.0.0' )
if "pretrained.act_postprocess2.0.project.0" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess2.0.project.0' , 'neck.reassemble_stage.readout_projects.1.0' )
if "pretrained.act_postprocess3.0.project.0" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess3.0.project.0' , 'neck.reassemble_stage.readout_projects.2.0' )
if "pretrained.act_postprocess4.0.project.0" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess4.0.project.0' , 'neck.reassemble_stage.readout_projects.3.0' )
# resize blocks
if "pretrained.act_postprocess1.3" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess1.3' , 'neck.reassemble_stage.layers.0.projection' )
if "pretrained.act_postprocess1.4" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess1.4' , 'neck.reassemble_stage.layers.0.resize' )
if "pretrained.act_postprocess2.3" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess2.3' , 'neck.reassemble_stage.layers.1.projection' )
if "pretrained.act_postprocess2.4" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess2.4' , 'neck.reassemble_stage.layers.1.resize' )
if "pretrained.act_postprocess3.3" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess3.3' , 'neck.reassemble_stage.layers.2.projection' )
if "pretrained.act_postprocess4.3" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess4.3' , 'neck.reassemble_stage.layers.3.projection' )
if "pretrained.act_postprocess4.4" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained.act_postprocess4.4' , 'neck.reassemble_stage.layers.3.resize' )
if "pretrained" in name:
SCREAMING_SNAKE_CASE_ = name.replace('pretrained' , 'dpt' )
if "bn" in name:
SCREAMING_SNAKE_CASE_ = name.replace('bn' , 'batch_norm' )
if "head" in name:
SCREAMING_SNAKE_CASE_ = name.replace('head' , 'head.head' )
if "encoder.norm" in name:
SCREAMING_SNAKE_CASE_ = name.replace('encoder.norm' , 'layernorm' )
if "auxlayer" in name:
SCREAMING_SNAKE_CASE_ = name.replace('auxlayer' , 'auxiliary_head.head' )
if "backbone" in name:
SCREAMING_SNAKE_CASE_ = name.replace('backbone' , 'backbone.bit.encoder' )
if ".." in name:
SCREAMING_SNAKE_CASE_ = name.replace('..' , '.' )
if "stem.conv" in name:
SCREAMING_SNAKE_CASE_ = name.replace('stem.conv' , 'bit.embedder.convolution' )
if "blocks" in name:
SCREAMING_SNAKE_CASE_ = name.replace('blocks' , 'layers' )
if "convolution" in name and "backbone" in name:
SCREAMING_SNAKE_CASE_ = name.replace('convolution' , 'conv' )
if "layer" in name and "backbone" in name:
SCREAMING_SNAKE_CASE_ = name.replace('layer' , 'layers' )
if "backbone.bit.encoder.bit" in name:
SCREAMING_SNAKE_CASE_ = name.replace('backbone.bit.encoder.bit' , 'backbone.bit' )
if "embedder.conv" in name:
SCREAMING_SNAKE_CASE_ = name.replace('embedder.conv' , 'embedder.convolution' )
if "backbone.bit.encoder.stem.norm" in name:
SCREAMING_SNAKE_CASE_ = name.replace('backbone.bit.encoder.stem.norm' , 'backbone.bit.embedder.norm' )
return name
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
for i in range(config.num_hidden_layers ):
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
SCREAMING_SNAKE_CASE_ = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.weight""" )
SCREAMING_SNAKE_CASE_ = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.bias""" )
# next, add query, keys and values (in that order) to the state dict
SCREAMING_SNAKE_CASE_ = in_proj_weight[: config.hidden_size, :]
SCREAMING_SNAKE_CASE_ = in_proj_bias[: config.hidden_size]
SCREAMING_SNAKE_CASE_ = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
SCREAMING_SNAKE_CASE_ = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
SCREAMING_SNAKE_CASE_ = in_proj_weight[
-config.hidden_size :, :
]
SCREAMING_SNAKE_CASE_ = in_proj_bias[-config.hidden_size :]
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = get_dpt_config(_SCREAMING_SNAKE_CASE )
# load original state_dict from URL
# state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
# remove certain keys
remove_ignore_keys_(_SCREAMING_SNAKE_CASE )
# rename keys
for key in state_dict.copy().keys():
SCREAMING_SNAKE_CASE_ = state_dict.pop(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = val
# read in qkv matrices
read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
SCREAMING_SNAKE_CASE_ = DPTForSemanticSegmentation(_SCREAMING_SNAKE_CASE ) if 'ade' in checkpoint_url else DPTForDepthEstimation(_SCREAMING_SNAKE_CASE )
model.load_state_dict(_SCREAMING_SNAKE_CASE )
model.eval()
# Check outputs on an image
SCREAMING_SNAKE_CASE_ = 480 if 'ade' in checkpoint_url else 384
SCREAMING_SNAKE_CASE_ = DPTImageProcessor(size=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = image_processor(_SCREAMING_SNAKE_CASE , return_tensors='pt' )
# forward pass
SCREAMING_SNAKE_CASE_ = model(**_SCREAMING_SNAKE_CASE ).logits if 'ade' in checkpoint_url else model(**_SCREAMING_SNAKE_CASE ).predicted_depth
if show_prediction:
SCREAMING_SNAKE_CASE_ = (
torch.nn.functional.interpolate(
outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode='bicubic' , align_corners=_SCREAMING_SNAKE_CASE , )
.squeeze()
.cpu()
.numpy()
)
Image.fromarray((prediction / prediction.max()) * 255 ).show()
if pytorch_dump_folder_path is not None:
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
print(f"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(_SCREAMING_SNAKE_CASE )
if push_to_hub:
model.push_to_hub('ybelkada/dpt-hybrid-midas' )
image_processor.push_to_hub('ybelkada/dpt-hybrid-midas' )
if __name__ == "__main__":
UpperCamelCase__ : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--checkpoint_url",
default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
type=str,
help="URL of the original DPT checkpoint you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default=None,
type=str,
required=False,
help="Path to the output PyTorch model directory.",
)
parser.add_argument(
"--push_to_hub",
action="store_true",
)
parser.add_argument(
"--model_name",
default="dpt-large",
type=str,
help="Name of the model, in case you're pushing to the hub.",
)
parser.add_argument(
"--show_prediction",
action="store_true",
)
UpperCamelCase__ : str = parser.parse_args()
convert_dpt_checkpoint(
args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction
)
| 620 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase__ : Any = {
"configuration_mvp": ["MVP_PRETRAINED_CONFIG_ARCHIVE_MAP", "MvpConfig", "MvpOnnxConfig"],
"tokenization_mvp": ["MvpTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[int] = ["MvpTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"MVP_PRETRAINED_MODEL_ARCHIVE_LIST",
"MvpForCausalLM",
"MvpForConditionalGeneration",
"MvpForQuestionAnswering",
"MvpForSequenceClassification",
"MvpModel",
"MvpPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
import argparse
import torch
from transformers import (
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForAudioFrameClassification,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
logging,
)
logging.set_verbosity_info()
UpperCamelCase__ : Dict = logging.get_logger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = WavaVecaForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = downstream_dict['projector.weight']
SCREAMING_SNAKE_CASE_ = downstream_dict['projector.bias']
SCREAMING_SNAKE_CASE_ = downstream_dict['model.post_net.linear.weight']
SCREAMING_SNAKE_CASE_ = downstream_dict['model.post_net.linear.bias']
return model
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = WavaVecaForAudioFrameClassification.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = downstream_dict['model.linear.weight']
SCREAMING_SNAKE_CASE_ = downstream_dict['model.linear.bias']
return model
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = WavaVecaForXVector.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = downstream_dict['connector.weight']
SCREAMING_SNAKE_CASE_ = downstream_dict['connector.bias']
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
SCREAMING_SNAKE_CASE_ = downstream_dict[
f"""model.framelevel_feature_extractor.module.{i}.kernel.weight"""
]
SCREAMING_SNAKE_CASE_ = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""]
SCREAMING_SNAKE_CASE_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight']
SCREAMING_SNAKE_CASE_ = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias']
SCREAMING_SNAKE_CASE_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight']
SCREAMING_SNAKE_CASE_ = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias']
SCREAMING_SNAKE_CASE_ = downstream_dict['objective.W']
return model
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
SCREAMING_SNAKE_CASE_ = checkpoint['Downstream']
SCREAMING_SNAKE_CASE_ = WavaVecaConfig.from_pretrained(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor.from_pretrained(
_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = hf_config.architectures[0]
if arch.endswith('ForSequenceClassification' ):
SCREAMING_SNAKE_CASE_ = convert_classification(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif arch.endswith('ForAudioFrameClassification' ):
SCREAMING_SNAKE_CASE_ = convert_diarization(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif arch.endswith('ForXVector' ):
SCREAMING_SNAKE_CASE_ = convert_xvector(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else:
raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" )
if hf_config.use_weighted_layer_sum:
SCREAMING_SNAKE_CASE_ = checkpoint['Featurizer']['weights']
hf_feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : Optional[int] = argparse.ArgumentParser()
parser.add_argument(
"--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model."
)
parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.")
parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.")
UpperCamelCase__ : Optional[Any] = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 620 |
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Dict = inspect.getfile(accelerate.test_utils )
__lowerCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
__lowerCAmelCase : Tuple = ['accelerate', 'launch']
__lowerCAmelCase : Union[str, Any] = Path.home() / '.cache/huggingface/accelerate'
__lowerCAmelCase : List[str] = 'default_config.yaml'
__lowerCAmelCase : List[Any] = config_folder / config_file
__lowerCAmelCase : str = config_folder / '_default_config.yaml'
__lowerCAmelCase : Optional[int] = Path('tests/test_configs' )
@classmethod
def lowerCAmelCase__ ( cls):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path)
@classmethod
def lowerCAmelCase__ ( cls):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
for config in sorted(self.test_config_path.glob('**/*.yaml')):
with self.subTest(config_file=_A):
execute_subprocess_async(
self.base_cmd + ['--config_file', str(_A), self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy())
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[Any] = 'test-tpu'
__lowerCAmelCase : str = 'us-central1-a'
__lowerCAmelCase : Union[str, Any] = 'ls'
__lowerCAmelCase : Union[str, Any] = ['accelerate', 'tpu-config']
__lowerCAmelCase : Union[str, Any] = 'cd /usr/share'
__lowerCAmelCase : List[Any] = 'tests/test_samples/test_command_file.sh'
__lowerCAmelCase : Dict = 'Running gcloud compute tpus tpu-vm ssh'
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command',
self.command,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A)
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--command',
self.command,
'--command',
'echo "Hello World"',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command_file',
self.command_file,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--install_accelerate',
'--accelerate_version',
'12.0.0',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
| 620 | 1 |
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Dict = inspect.getfile(accelerate.test_utils )
__lowerCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
__lowerCAmelCase : Tuple = ['accelerate', 'launch']
__lowerCAmelCase : Union[str, Any] = Path.home() / '.cache/huggingface/accelerate'
__lowerCAmelCase : List[str] = 'default_config.yaml'
__lowerCAmelCase : List[Any] = config_folder / config_file
__lowerCAmelCase : str = config_folder / '_default_config.yaml'
__lowerCAmelCase : Optional[int] = Path('tests/test_configs' )
@classmethod
def lowerCAmelCase__ ( cls):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path)
@classmethod
def lowerCAmelCase__ ( cls):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
for config in sorted(self.test_config_path.glob('**/*.yaml')):
with self.subTest(config_file=_A):
execute_subprocess_async(
self.base_cmd + ['--config_file', str(_A), self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy())
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[Any] = 'test-tpu'
__lowerCAmelCase : str = 'us-central1-a'
__lowerCAmelCase : Union[str, Any] = 'ls'
__lowerCAmelCase : Union[str, Any] = ['accelerate', 'tpu-config']
__lowerCAmelCase : Union[str, Any] = 'cd /usr/share'
__lowerCAmelCase : List[Any] = 'tests/test_samples/test_command_file.sh'
__lowerCAmelCase : Dict = 'Running gcloud compute tpus tpu-vm ssh'
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command',
self.command,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A)
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--command',
self.command,
'--command',
'echo "Hello World"',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command_file',
self.command_file,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--install_accelerate',
'--accelerate_version',
'12.0.0',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
| 620 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCamelCase__ : Tuple = {
"configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
"processing_trocr": ["TrOCRProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
"TrOCRForCausalLM",
"TrOCRPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCamelCase__ : Tuple = {
"configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
"processing_trocr": ["TrOCRProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
"TrOCRForCausalLM",
"TrOCRPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 |
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
UpperCamelCase__ : int = Lock()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0 , 10 ):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
SCREAMING_SNAKE_CASE_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# after all swaps are performed, send the values back to main
result_pipe[1].send(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe() )
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ):
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(
len(_SCREAMING_SNAKE_CASE ) - 1,
arr[len(_SCREAMING_SNAKE_CASE ) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1],
) , ) )
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE_ = result_pipe[p][0].recv()
process_array_[p].join()
return arr
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = list(range(10 , 0 , -1 ) )
print('Initial List' )
print(*_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = odd_even_transposition(_SCREAMING_SNAKE_CASE )
print('Sorted List\n' )
print(*_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 | 1 |
import flax.linen as nn
import jax
import jax.numpy as jnp
class __snake_case ( nn.Module ):
__lowerCAmelCase : int
__lowerCAmelCase : jnp.dtype = jnp.floataa
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self , _A):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = hidden_states.shape
SCREAMING_SNAKE_CASE_ = jax.image.resize(
_A , shape=(batch, height * 2, width * 2, channels) , method='nearest' , )
SCREAMING_SNAKE_CASE_ = self.conv(_A)
return hidden_states
class __snake_case ( nn.Module ):
__lowerCAmelCase : int
__lowerCAmelCase : jnp.dtype = jnp.floataa
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = nn.Conv(
self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
def __call__( self , _A):
# pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
# hidden_states = jnp.pad(hidden_states, pad_width=pad)
SCREAMING_SNAKE_CASE_ = self.conv(_A)
return hidden_states
class __snake_case ( nn.Module ):
__lowerCAmelCase : int
__lowerCAmelCase : int = None
__lowerCAmelCase : float = 0.0
__lowerCAmelCase : bool = None
__lowerCAmelCase : jnp.dtype = jnp.floataa
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.in_channels if self.out_channels is None else self.out_channels
SCREAMING_SNAKE_CASE_ = nn.GroupNorm(num_groups=32 , epsilon=1E-5)
SCREAMING_SNAKE_CASE_ = nn.Conv(
_A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
SCREAMING_SNAKE_CASE_ = nn.Dense(_A , dtype=self.dtype)
SCREAMING_SNAKE_CASE_ = nn.GroupNorm(num_groups=32 , epsilon=1E-5)
SCREAMING_SNAKE_CASE_ = nn.Dropout(self.dropout_prob)
SCREAMING_SNAKE_CASE_ = nn.Conv(
_A , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , )
SCREAMING_SNAKE_CASE_ = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
SCREAMING_SNAKE_CASE_ = None
if use_nin_shortcut:
SCREAMING_SNAKE_CASE_ = nn.Conv(
_A , kernel_size=(1, 1) , strides=(1, 1) , padding='VALID' , dtype=self.dtype , )
def __call__( self , _A , _A , _A=True):
SCREAMING_SNAKE_CASE_ = hidden_states
SCREAMING_SNAKE_CASE_ = self.norma(_A)
SCREAMING_SNAKE_CASE_ = nn.swish(_A)
SCREAMING_SNAKE_CASE_ = self.conva(_A)
SCREAMING_SNAKE_CASE_ = self.time_emb_proj(nn.swish(_A))
SCREAMING_SNAKE_CASE_ = jnp.expand_dims(jnp.expand_dims(_A , 1) , 1)
SCREAMING_SNAKE_CASE_ = hidden_states + temb
SCREAMING_SNAKE_CASE_ = self.norma(_A)
SCREAMING_SNAKE_CASE_ = nn.swish(_A)
SCREAMING_SNAKE_CASE_ = self.dropout(_A , _A)
SCREAMING_SNAKE_CASE_ = self.conva(_A)
if self.conv_shortcut is not None:
SCREAMING_SNAKE_CASE_ = self.conv_shortcut(_A)
return hidden_states + residual
| 620 |
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
UpperCamelCase__ : int = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n"
class __snake_case ( unittest.TestCase , lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering')
self.tool.setup()
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering' , remote=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
| 620 | 1 |
from __future__ import annotations
from collections import Counter
from random import random
class __snake_case :
def __init__( self):
SCREAMING_SNAKE_CASE_ = {}
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = {}
def lowerCAmelCase__ ( self , _A , _A , _A):
if nodea not in self.connections:
self.add_node(_A)
if nodea not in self.connections:
self.add_node(_A)
SCREAMING_SNAKE_CASE_ = probability
def lowerCAmelCase__ ( self):
return list(self.connections)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = random()
for dest in self.connections[node]:
current_probability += self.connections[node][dest]
if current_probability > random_value:
return dest
return ""
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : list[tuple[str, str, float]] , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = MarkovChainGraphUndirectedUnweighted()
for nodea, nodea, probability in transitions:
graph.add_transition_probability(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = Counter(graph.get_nodes() )
SCREAMING_SNAKE_CASE_ = start
for _ in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = graph.transition(_SCREAMING_SNAKE_CASE )
visited[node] += 1
return visited
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import BeitImageProcessor
class __snake_case ( unittest.TestCase ):
def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=False , ):
SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 20, 'width': 20}
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 18, 'width': 18}
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = min_resolution
SCREAMING_SNAKE_CASE_ = max_resolution
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean
SCREAMING_SNAKE_CASE_ = image_std
SCREAMING_SNAKE_CASE_ = do_reduce_labels
def lowerCAmelCase__ ( self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_reduce_labels": self.do_reduce_labels,
}
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[1]['file'] )
return image, map
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[1]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[2]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[3]['file'] )
return [imagea, imagea], [mapa, mapa]
@require_torch
@require_vision
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Union[str, Any] = BeitImageProcessor if is_vision_available() else None
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BeitImageProcessingTester(self)
@property
def lowerCAmelCase__ ( self):
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(_A , 'do_resize'))
self.assertTrue(hasattr(_A , 'size'))
self.assertTrue(hasattr(_A , 'do_center_crop'))
self.assertTrue(hasattr(_A , 'center_crop'))
self.assertTrue(hasattr(_A , 'do_normalize'))
self.assertTrue(hasattr(_A , 'image_mean'))
self.assertTrue(hasattr(_A , 'image_std'))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 20, 'width': 20})
self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18})
self.assertEqual(image_processor.do_reduce_labels , _A)
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A)
self.assertEqual(image_processor.size , {'height': 42, 'width': 42})
self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84})
self.assertEqual(image_processor.do_reduce_labels , _A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A)
for image in image_inputs:
self.assertIsInstance(_A , Image.Image)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A)
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
SCREAMING_SNAKE_CASE_ = []
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
maps.append(torch.zeros(image.shape[-2:]).long())
# Test not batched input
SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , maps[0] , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test not batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_batch_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
2,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
2,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 150)
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
| 620 | 1 |
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401
deprecate(
"stable diffusion controlnet",
"0.22.0",
"Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.",
standard_warn=False,
stacklevel=3,
)
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 200 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [1, 2, 5, 10, 20, 50, 100, 200]
SCREAMING_SNAKE_CASE_ = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(_SCREAMING_SNAKE_CASE , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73_682
| 620 | 1 |
import json
import sys
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f:
SCREAMING_SNAKE_CASE_ = json.load(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = ['<details>', '<summary>Show updated benchmarks!</summary>', ' ']
for benchmark_name in sorted(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = results[benchmark_name]
SCREAMING_SNAKE_CASE_ = benchmark_name.split('/' )[-1]
output_md.append(f"""### Benchmark: {benchmark_file_name}""" )
SCREAMING_SNAKE_CASE_ = '| metric |'
SCREAMING_SNAKE_CASE_ = '|--------|'
SCREAMING_SNAKE_CASE_ = '| new / old (diff) |'
for metric_name in sorted(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = benchmark_res[metric_name]
SCREAMING_SNAKE_CASE_ = metric_vals['new']
SCREAMING_SNAKE_CASE_ = metric_vals.get('old' , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = metric_vals.get('diff' , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = f""" {new_val:f}""" if isinstance(_SCREAMING_SNAKE_CASE , (int, float) ) else 'None'
if old_val is not None:
val_str += f""" / {old_val:f}""" if isinstance(_SCREAMING_SNAKE_CASE , (int, float) ) else "None"
if dif_val is not None:
val_str += f""" ({dif_val:f})""" if isinstance(_SCREAMING_SNAKE_CASE , (int, float) ) else "None"
title += " " + metric_name + " |"
lines += "---|"
value += val_str + " |"
output_md += [title, lines, value, " "]
output_md.append('</details>' )
with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as f:
f.writelines('\n'.join(_SCREAMING_SNAKE_CASE ) )
if __name__ == "__main__":
UpperCamelCase__ : Tuple = sys.argv[1]
UpperCamelCase__ : Union[str, Any] = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if index == number_of_items:
return 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 )
if weights[index] <= max_weight:
SCREAMING_SNAKE_CASE_ = values[index] + knapsack(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 )
return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 10 , _SCREAMING_SNAKE_CASE : int = 22 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = range(1 , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = range(1 , _SCREAMING_SNAKE_CASE )
return sum(
1 for power in powers for base in bases if len(str(base**power ) ) == power )
if __name__ == "__main__":
print(F'{solution(10, 22) = }')
| 620 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase__ : List[Any] = torch.device("cpu")
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = dct.pop(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = val
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for k in state_dict.keys():
SCREAMING_SNAKE_CASE_ = k
if ".pwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.pwconv' , '.point_wise_conv' )
if ".dwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.dwconv' , '.depth_wise_conv' )
if ".Proj." in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.Proj.' , '.proj.' )
if "patch_embed" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' )
if "network" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.split('.' )
if ls[2].isdigit():
SCREAMING_SNAKE_CASE_ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] )
else:
SCREAMING_SNAKE_CASE_ = k_new.replace('network' , 'swiftformer.encoder.network' )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
SCREAMING_SNAKE_CASE_ = 1_000
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json'
SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
SCREAMING_SNAKE_CASE_ = [3, 3, 6, 4]
SCREAMING_SNAKE_CASE_ = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
SCREAMING_SNAKE_CASE_ = [3, 3, 9, 6]
SCREAMING_SNAKE_CASE_ = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
SCREAMING_SNAKE_CASE_ = [4, 3, 10, 5]
SCREAMING_SNAKE_CASE_ = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
SCREAMING_SNAKE_CASE_ = [4, 4, 12, 6]
SCREAMING_SNAKE_CASE_ = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith('https' ):
SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
SCREAMING_SNAKE_CASE_ = checkpoint
SCREAMING_SNAKE_CASE_ = create_rename_keys(_SCREAMING_SNAKE_CASE )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
SCREAMING_SNAKE_CASE_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval()
hf_model.load_state_dict(_SCREAMING_SNAKE_CASE )
# prepare test inputs
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = ViTImageProcessor.from_pretrained('preprocessor_config' )
SCREAMING_SNAKE_CASE_ = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
# compare outputs from both models
SCREAMING_SNAKE_CASE_ = get_expected_output(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = hf_model(inputs['pixel_values'] ).logits
assert hf_logits.shape == torch.Size([1, 1_000] )
assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1E-3 )
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--swiftformer_name",
default="swiftformer_xs",
choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"],
type=str,
help="Name of the SwiftFormer model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="./converted_outputs/",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.")
UpperCamelCase__ : Union[str, Any] = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 620 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
UpperCamelCase__ : List[Any] = {
"configuration_layoutlmv3": [
"LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP",
"LayoutLMv3Config",
"LayoutLMv3OnnxConfig",
],
"processing_layoutlmv3": ["LayoutLMv3Processor"],
"tokenization_layoutlmv3": ["LayoutLMv3Tokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : int = ["LayoutLMv3TokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : List[Any] = [
"LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST",
"LayoutLMv3ForQuestionAnswering",
"LayoutLMv3ForSequenceClassification",
"LayoutLMv3ForTokenClassification",
"LayoutLMv3Model",
"LayoutLMv3PreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFLayoutLMv3ForQuestionAnswering",
"TFLayoutLMv3ForSequenceClassification",
"TFLayoutLMv3ForTokenClassification",
"TFLayoutLMv3Model",
"TFLayoutLMv3PreTrainedModel",
]
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = ["LayoutLMv3FeatureExtractor"]
UpperCamelCase__ : Tuple = ["LayoutLMv3ImageProcessor"]
if TYPE_CHECKING:
from .configuration_layoutlmva import (
LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
LayoutLMvaConfig,
LayoutLMvaOnnxConfig,
)
from .processing_layoutlmva import LayoutLMvaProcessor
from .tokenization_layoutlmva import LayoutLMvaTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_layoutlmva import (
LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaModel,
LayoutLMvaPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_layoutlmva import (
TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
TFLayoutLMvaForQuestionAnswering,
TFLayoutLMvaForSequenceClassification,
TFLayoutLMvaForTokenClassification,
TFLayoutLMvaModel,
TFLayoutLMvaPreTrainedModel,
)
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
from .image_processing_layoutlmva import LayoutLMvaImageProcessor
else:
import sys
UpperCamelCase__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 |
def _UpperCAmelCase ( ):
"""simple docstring"""
for n in range(1 , 1_000_000 ):
yield n * (n + 1) // 2
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 2
while i * i <= n:
SCREAMING_SNAKE_CASE_ = 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 _UpperCAmelCase ( ):
"""simple docstring"""
return next(i for i in triangle_number_generator() if count_divisors(_SCREAMING_SNAKE_CASE ) > 500 )
if __name__ == "__main__":
print(solution())
| 620 | 1 |
import warnings
from ...utils import logging
from .image_processing_layoutlmva import LayoutLMvaImageProcessor
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , *_A , **_A):
warnings.warn(
'The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
' Please use LayoutLMv2ImageProcessor instead.' , _A , )
super().__init__(*_A , **_A)
| 620 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
UpperCamelCase__ : Optional[int] = datasets.utils.logging.get_logger(__name__)
@dataclass
class __snake_case ( datasets.BuilderConfig ):
__lowerCAmelCase : Optional[datasets.Features] = None
__lowerCAmelCase : str = "utf-8"
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : bool = True # deprecated
__lowerCAmelCase : Optional[int] = None # deprecated
__lowerCAmelCase : int = 10 << 20 # 10MB
__lowerCAmelCase : Optional[bool] = None
class __snake_case ( datasets.ArrowBasedBuilder ):
__lowerCAmelCase : int = JsonConfig
def lowerCAmelCase__ ( self):
if self.config.block_size is not None:
logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead')
SCREAMING_SNAKE_CASE_ = self.config.block_size
if self.config.use_threads is not True:
logger.warning(
'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.')
if self.config.newlines_in_values is not None:
raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported')
return datasets.DatasetInfo(features=self.config.features)
def lowerCAmelCase__ ( self , _A):
if not self.config.data_files:
raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
SCREAMING_SNAKE_CASE_ = dl_manager.download_and_extract(self.config.data_files)
if isinstance(_A , (str, list, tuple)):
SCREAMING_SNAKE_CASE_ = data_files
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files})]
SCREAMING_SNAKE_CASE_ = []
for split_name, files in data_files.items():
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'files': files}))
return splits
def lowerCAmelCase__ ( self , _A):
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features) - set(pa_table.column_names):
SCREAMING_SNAKE_CASE_ = self.config.features.arrow_schema.field(_A).type
SCREAMING_SNAKE_CASE_ = pa_table.append_column(_A , pa.array([None] * len(_A) , type=_A))
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
SCREAMING_SNAKE_CASE_ = table_cast(_A , self.config.features.arrow_schema)
return pa_table
def lowerCAmelCase__ ( self , _A):
for file_idx, file in enumerate(itertools.chain.from_iterable(_A)):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
# We keep only the field we are interested in
SCREAMING_SNAKE_CASE_ = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(_A , (list, tuple)):
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
else:
SCREAMING_SNAKE_CASE_ = dataset
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
yield file_idx, self._cast_table(_A)
# If the file has one json object per line
else:
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = 0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
SCREAMING_SNAKE_CASE_ = max(self.config.chunksize // 32 , 16 << 10)
SCREAMING_SNAKE_CASE_ = (
self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
)
while True:
SCREAMING_SNAKE_CASE_ = f.read(self.config.chunksize)
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(_A)
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
SCREAMING_SNAKE_CASE_ = batch.decode(self.config.encoding , errors=_A).encode('utf-8')
try:
while True:
try:
SCREAMING_SNAKE_CASE_ = paj.read_json(
io.BytesIO(_A) , read_options=paj.ReadOptions(block_size=_A))
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(_A , pa.ArrowInvalid)
and "straddling" not in str(_A)
or block_size > len(_A)
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
f"""Batch of {len(_A)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""")
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
except json.JSONDecodeError:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(_A , _A): # list is the only sequence type supported in JSON
try:
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(f"""Not able to read records in the JSON file at {file}.""") from None
yield file_idx, self._cast_table(_A)
break
else:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(
f"""Not able to read records in the JSON file at {file}. """
f"""You should probably indicate the field of the JSON file containing your records. """
f"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """
f"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_A)
batch_idx += 1
| 620 | 1 |
from __future__ import annotations
import math
class __snake_case :
def __init__( self , _A):
SCREAMING_SNAKE_CASE_ = size
# approximate the overall size of segment tree with given value
SCREAMING_SNAKE_CASE_ = [0 for i in range(0 , 4 * size)]
# create array to store lazy update
SCREAMING_SNAKE_CASE_ = [0 for i in range(0 , 4 * size)]
SCREAMING_SNAKE_CASE_ = [0 for i in range(0 , 4 * size)] # flag for lazy update
def lowerCAmelCase__ ( self , _A):
return idx * 2
def lowerCAmelCase__ ( self , _A):
return idx * 2 + 1
def lowerCAmelCase__ ( self , _A , _A , _A , _A):
if left_element == right_element:
SCREAMING_SNAKE_CASE_ = a[left_element - 1]
else:
SCREAMING_SNAKE_CASE_ = (left_element + right_element) // 2
self.build(self.left(_A) , _A , _A , _A)
self.build(self.right(_A) , mid + 1 , _A , _A)
SCREAMING_SNAKE_CASE_ = max(
self.segment_tree[self.left(_A)] , self.segment_tree[self.right(_A)])
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , _A):
if self.flag[idx] is True:
SCREAMING_SNAKE_CASE_ = self.lazy[idx]
SCREAMING_SNAKE_CASE_ = False
if left_element != right_element:
SCREAMING_SNAKE_CASE_ = self.lazy[idx]
SCREAMING_SNAKE_CASE_ = self.lazy[idx]
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = True
if right_element < a or left_element > b:
return True
if left_element >= a and right_element <= b:
SCREAMING_SNAKE_CASE_ = val
if left_element != right_element:
SCREAMING_SNAKE_CASE_ = val
SCREAMING_SNAKE_CASE_ = val
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = True
return True
SCREAMING_SNAKE_CASE_ = (left_element + right_element) // 2
self.update(self.left(_A) , _A , _A , _A , _A , _A)
self.update(self.right(_A) , mid + 1 , _A , _A , _A , _A)
SCREAMING_SNAKE_CASE_ = max(
self.segment_tree[self.left(_A)] , self.segment_tree[self.right(_A)])
return True
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
if self.flag[idx] is True:
SCREAMING_SNAKE_CASE_ = self.lazy[idx]
SCREAMING_SNAKE_CASE_ = False
if left_element != right_element:
SCREAMING_SNAKE_CASE_ = self.lazy[idx]
SCREAMING_SNAKE_CASE_ = self.lazy[idx]
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = True
if right_element < a or left_element > b:
return -math.inf
if left_element >= a and right_element <= b:
return self.segment_tree[idx]
SCREAMING_SNAKE_CASE_ = (left_element + right_element) // 2
SCREAMING_SNAKE_CASE_ = self.query(self.left(_A) , _A , _A , _A , _A)
SCREAMING_SNAKE_CASE_ = self.query(self.right(_A) , mid + 1 , _A , _A , _A)
return max(_A , _A)
def __str__( self):
return str([self.query(1 , 1 , self.size , _A , _A) for i in range(1 , self.size + 1)])
if __name__ == "__main__":
UpperCamelCase__ : Tuple = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8]
UpperCamelCase__ : int = 15
UpperCamelCase__ : Tuple = SegmentTree(size)
segt.build(1, 1, size, A)
print(segt.query(1, 1, size, 4, 6))
print(segt.query(1, 1, size, 7, 11))
print(segt.query(1, 1, size, 7, 12))
segt.update(1, 1, size, 1, 3, 111)
print(segt.query(1, 1, size, 1, 15))
segt.update(1, 1, size, 7, 8, 235)
print(segt)
| 620 |
import unittest
from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM
@require_torch
class __snake_case :
def __init__( self , _A , _A=99 , _A=13 , _A=16 , _A=7 , _A=True , _A=True , _A=True , _A=False , _A=True , _A=2 , _A=32 , _A=4 , _A=4 , _A=30 , _A=0 , _A=1 , _A=2 , _A=None , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE_ = self.decoder_seq_length
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_attention_mask
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_ffn_dim
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = eos_token_id
SCREAMING_SNAKE_CASE_ = bos_token_id
SCREAMING_SNAKE_CASE_ = pad_token_id
SCREAMING_SNAKE_CASE_ = decoder_start_token_id
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = decoder_seq_length
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_attention_mask:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2)
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = TrOCRConfig(
vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , )
return (config, input_ids, attention_mask, lm_labels)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , ):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = TrOCRDecoder(config=_A).to(_A).eval()
SCREAMING_SNAKE_CASE_ = input_ids[:2]
input_ids[input_ids == 0] += 1
# first forward pass
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
self.parent.assertTrue(len(_A) == len(_A))
self.parent.assertTrue(len(_A) == len(_A) + 1)
SCREAMING_SNAKE_CASE_ = outputs['past_key_values']
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE_ = ids_tensor((2, 1) , config.vocab_size - 1) + 1
# append to next input_ids and
SCREAMING_SNAKE_CASE_ = torch.cat([input_ids, next_tokens] , dim=-1)
SCREAMING_SNAKE_CASE_ = model(_A)['last_hidden_state']
SCREAMING_SNAKE_CASE_ = model(_A , past_key_values=_A)['last_hidden_state']
# select random slice
SCREAMING_SNAKE_CASE_ = ids_tensor((1,) , output_from_past.shape[-1]).item()
SCREAMING_SNAKE_CASE_ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE_ = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(_A , _A , atol=1E-3)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
@require_torch
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Tuple = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
__lowerCAmelCase : Union[str, Any] = (TrOCRForCausalLM,) if is_torch_available() else ()
__lowerCAmelCase : str = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
__lowerCAmelCase : Any = True
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TrOCRStandaloneDecoderModelTester(self , is_training=_A)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*_A)
def lowerCAmelCase__ ( self):
return
@unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :)
def lowerCAmelCase__ ( self):
pass
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 200 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [1, 2, 5, 10, 20, 50, 100, 200]
SCREAMING_SNAKE_CASE_ = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(_SCREAMING_SNAKE_CASE , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73_682
| 620 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : torch.FloatTensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ):
super().__init__()
# pass init params to Encoder
SCREAMING_SNAKE_CASE_ = Encoder(
in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , )
SCREAMING_SNAKE_CASE_ = vq_embed_dim if vq_embed_dim is not None else latent_channels
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
SCREAMING_SNAKE_CASE_ = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A)
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
# pass init params to Decoder
SCREAMING_SNAKE_CASE_ = Decoder(
in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , )
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = self.encoder(_A)
SCREAMING_SNAKE_CASE_ = self.quant_conv(_A)
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_A)
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = False , _A = True):
# also go through quantization layer
if not force_not_quantize:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.quantize(_A)
else:
SCREAMING_SNAKE_CASE_ = h
SCREAMING_SNAKE_CASE_ = self.post_quant_conv(_A)
SCREAMING_SNAKE_CASE_ = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None)
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = sample
SCREAMING_SNAKE_CASE_ = self.encode(_A).latents
SCREAMING_SNAKE_CASE_ = self.decode(_A).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
| 620 | 1 |
import argparse
import os
import torch
from transformers.utils import WEIGHTS_NAME
UpperCamelCase__ : str = ["small", "medium", "large"]
UpperCamelCase__ : Tuple = "lm_head.decoder.weight"
UpperCamelCase__ : List[Any] = "lm_head.weight"
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = d.pop(_SCREAMING_SNAKE_CASE )
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
torch.save(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
if __name__ == "__main__":
UpperCamelCase__ : int = argparse.ArgumentParser()
parser.add_argument("--dialogpt_path", default=".", type=str)
UpperCamelCase__ : Optional[Any] = parser.parse_args()
for MODEL in DIALOGPT_MODELS:
UpperCamelCase__ : Union[str, Any] = os.path.join(args.dialogpt_path, F'{MODEL}_ft.pkl')
UpperCamelCase__ : Dict = F'./DialoGPT-{MODEL}'
convert_dialogpt_checkpoint(
checkpoint_path,
pytorch_dump_folder_path,
)
| 620 |
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
UpperCamelCase__ : Optional[int] = logging.getLogger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : torch.nn.Module , _SCREAMING_SNAKE_CASE : BnbQuantizationConfig , _SCREAMING_SNAKE_CASE : Union[str, os.PathLike] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[str, Union[int, str, torch.device]]] = None , _SCREAMING_SNAKE_CASE : Optional[List[str]] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[Union[int, str], Union[int, str]]] = None , _SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , _SCREAMING_SNAKE_CASE : bool = False , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.load_in_abit
SCREAMING_SNAKE_CASE_ = 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.' )
SCREAMING_SNAKE_CASE_ = []
# custom device map
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1:
SCREAMING_SNAKE_CASE_ = [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:
SCREAMING_SNAKE_CASE_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE )
# compatibility with peft
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = get_parameter_device(_SCREAMING_SNAKE_CASE )
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.' )
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
# convert param to the right dtype
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = name.replace('.weight' , '' ).replace('.bias' , '' )
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ):
param.to(_SCREAMING_SNAKE_CASE )
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():
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = get_quantized_model_device_map(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] )
load_checkpoint_in_model(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
SCREAMING_SNAKE_CASE_ = {'': 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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
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\'.' )
SCREAMING_SNAKE_CASE_ = {}
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 )
} )
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = special_dtypes
SCREAMING_SNAKE_CASE_ = no_split_module_classes
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
SCREAMING_SNAKE_CASE_ = get_balanced_memory(
_SCREAMING_SNAKE_CASE , low_zero=(device_map == 'balanced_low_0') , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = max_memory
SCREAMING_SNAKE_CASE_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
# check if don't have any quantized module on the cpu
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
SCREAMING_SNAKE_CASE_ = {
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if modules_to_not_convert is None:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : str=None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = False
for name, module in model.named_children():
if current_key_name is None:
SCREAMING_SNAKE_CASE_ = []
current_key_name.append(_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
SCREAMING_SNAKE_CASE_ = '.'.join(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = 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' )
SCREAMING_SNAKE_CASE_ = module.weight.data
if module.bias is not None:
SCREAMING_SNAKE_CASE_ = module.bias.data
bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE )
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = True
if len(list(module.children() ) ) > 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
with init_empty_weights():
SCREAMING_SNAKE_CASE_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
SCREAMING_SNAKE_CASE_ = find_tied_parameters(_SCREAMING_SNAKE_CASE )
# For compatibility with Accelerate < 0.18
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
SCREAMING_SNAKE_CASE_ = sum(_SCREAMING_SNAKE_CASE , [] )
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE ) > 0
# Check if it is a base model
SCREAMING_SNAKE_CASE_ = False
if hasattr(_SCREAMING_SNAKE_CASE , 'base_model_prefix' ):
SCREAMING_SNAKE_CASE_ = not hasattr(_SCREAMING_SNAKE_CASE , 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
SCREAMING_SNAKE_CASE_ = list(model.named_children() )
SCREAMING_SNAKE_CASE_ = [list_modules[-1][0]]
# add last module together with tied weights
SCREAMING_SNAKE_CASE_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE )
# remove ".weight" from the keys
SCREAMING_SNAKE_CASE_ = ['.weight', '.bias']
SCREAMING_SNAKE_CASE_ = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
SCREAMING_SNAKE_CASE_ = name.replace(_SCREAMING_SNAKE_CASE , '' )
filtered_module_names.append(_SCREAMING_SNAKE_CASE )
return filtered_module_names
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for m in model.modules():
if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ):
return True
return False
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : nn.Module ):
"""simple docstring"""
return next(parameter.parameters() ).device
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = param_name
SCREAMING_SNAKE_CASE_ = model
if "." in tensor_name:
SCREAMING_SNAKE_CASE_ = tensor_name.split('.' )
for split in splits[:-1]:
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
SCREAMING_SNAKE_CASE_ = new_module
SCREAMING_SNAKE_CASE_ = splits[-1]
# offload weights
SCREAMING_SNAKE_CASE_ = False
offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
if hasattr(module._parameters[tensor_name] , 'SCB' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , )
else:
offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'meta' , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
| 620 | 1 |
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : List[str] = ['image_processor', 'tokenizer']
__lowerCAmelCase : List[str] = 'BlipImageProcessor'
__lowerCAmelCase : Tuple = ('BertTokenizer', 'BertTokenizerFast')
def __init__( self , _A , _A):
SCREAMING_SNAKE_CASE_ = False
super().__init__(_A , _A)
SCREAMING_SNAKE_CASE_ = self.image_processor
def __call__( self , _A = None , _A = None , _A = True , _A = False , _A = None , _A = None , _A = 0 , _A = None , _A = None , _A = False , _A = False , _A = False , _A = False , _A = False , _A = True , _A = None , **_A , ):
if images is None and text is None:
raise ValueError('You have to specify either images or text.')
# Get only text
if images is None:
SCREAMING_SNAKE_CASE_ = self.tokenizer
SCREAMING_SNAKE_CASE_ = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
return text_encoding
# add pixel_values
SCREAMING_SNAKE_CASE_ = self.image_processor(_A , return_tensors=_A)
if text is not None:
SCREAMING_SNAKE_CASE_ = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
else:
SCREAMING_SNAKE_CASE_ = None
if text_encoding is not None:
encoding_image_processor.update(_A)
return encoding_image_processor
def lowerCAmelCase__ ( self , *_A , **_A):
return self.tokenizer.batch_decode(*_A , **_A)
def lowerCAmelCase__ ( self , *_A , **_A):
return self.tokenizer.decode(*_A , **_A)
@property
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tokenizer.model_input_names
SCREAMING_SNAKE_CASE_ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 620 |
import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
UpperCamelCase__ : Optional[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
# See all BART models at https://huggingface.co/models?filter=bart
UpperCamelCase__ : List[str] = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
}
UpperCamelCase__ : str = {
"facebook/bart-base": 1_024,
"facebook/bart-large": 1_024,
"facebook/bart-large-mnli": 1_024,
"facebook/bart-large-cnn": 1_024,
"facebook/bart-large-xsum": 1_024,
"yjernite/bart_eli5": 1_024,
}
@lru_cache()
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (
list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) )
)
SCREAMING_SNAKE_CASE_ = bs[:]
SCREAMING_SNAKE_CASE_ = 0
for b in range(2**8 ):
if b not in bs:
bs.append(_SCREAMING_SNAKE_CASE )
cs.append(2**8 + n )
n += 1
SCREAMING_SNAKE_CASE_ = [chr(_SCREAMING_SNAKE_CASE ) for n in cs]
return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = set()
SCREAMING_SNAKE_CASE_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
SCREAMING_SNAKE_CASE_ = char
return pairs
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = VOCAB_FILES_NAMES
__lowerCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP
__lowerCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask']
def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ):
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else bos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else eos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else sep_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else cls_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else unk_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token
super().__init__(
errors=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , **_A , )
with open(_A , encoding='utf-8') as vocab_handle:
SCREAMING_SNAKE_CASE_ = json.load(_A)
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()}
SCREAMING_SNAKE_CASE_ = errors # how to handle errors in decoding
SCREAMING_SNAKE_CASE_ = bytes_to_unicode()
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.byte_encoder.items()}
with open(_A , encoding='utf-8') as merges_handle:
SCREAMING_SNAKE_CASE_ = merges_handle.read().split('\n')[1:-1]
SCREAMING_SNAKE_CASE_ = [tuple(merge.split()) for merge in bpe_merges]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
SCREAMING_SNAKE_CASE_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+')
@property
def lowerCAmelCase__ ( self):
return len(self.encoder)
def lowerCAmelCase__ ( self):
return dict(self.encoder , **self.added_tokens_encoder)
def lowerCAmelCase__ ( self , _A):
if token in self.cache:
return self.cache[token]
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
if not pairs:
return token
while True:
SCREAMING_SNAKE_CASE_ = min(_A , key=lambda _A: self.bpe_ranks.get(_A , float('inf')))
if bigram not in self.bpe_ranks:
break
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
while i < len(_A):
try:
SCREAMING_SNAKE_CASE_ = word.index(_A , _A)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
SCREAMING_SNAKE_CASE_ = j
if word[i] == first and i < len(_A) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = new_word
if len(_A) == 1:
break
else:
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
SCREAMING_SNAKE_CASE_ = ' '.join(_A)
SCREAMING_SNAKE_CASE_ = word
return word
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = []
for token in re.findall(self.pat , _A):
SCREAMING_SNAKE_CASE_ = ''.join(
self.byte_encoder[b] for b in token.encode('utf-8')) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A).split(' '))
return bpe_tokens
def lowerCAmelCase__ ( self , _A):
return self.encoder.get(_A , self.encoder.get(self.unk_token))
def lowerCAmelCase__ ( self , _A):
return self.decoder.get(_A)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = ''.join(_A)
SCREAMING_SNAKE_CASE_ = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8' , errors=self.errors)
return text
def lowerCAmelCase__ ( self , _A , _A = None):
if not os.path.isdir(_A):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""")
return
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'])
with open(_A , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A) + '\n')
SCREAMING_SNAKE_CASE_ = 0
with open(_A , 'w' , encoding='utf-8') as writer:
writer.write('#version: 0.2\n')
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A: kv[1]):
if index != token_index:
logger.warning(
f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
' Please check that the tokenizer is not corrupted!')
SCREAMING_SNAKE_CASE_ = token_index
writer.write(' '.join(_A) + '\n')
index += 1
return vocab_file, merge_file
def lowerCAmelCase__ ( self , _A , _A = None):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowerCAmelCase__ ( self , _A , _A = None , _A = False):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A)
if token_ids_a is None:
return [1] + ([0] * len(_A)) + [1]
return [1] + ([0] * len(_A)) + [1, 1] + ([0] * len(_A)) + [1]
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
def lowerCAmelCase__ ( self , _A , _A=False , **_A):
SCREAMING_SNAKE_CASE_ = kwargs.pop('add_prefix_space' , self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(_A) > 0 and not text[0].isspace()):
SCREAMING_SNAKE_CASE_ = ' ' + text
return (text, kwargs)
| 620 | 1 |
from typing import Any
class __snake_case :
def __init__( self , _A):
SCREAMING_SNAKE_CASE_ = data
SCREAMING_SNAKE_CASE_ = None
def __repr__( self):
return f"""Node({self.data})"""
class __snake_case :
def __init__( self):
SCREAMING_SNAKE_CASE_ = None
def __iter__( self):
SCREAMING_SNAKE_CASE_ = self.head
while node:
yield node.data
SCREAMING_SNAKE_CASE_ = node.next
def __len__( self):
return sum(1 for _ in self)
def __repr__( self):
return "->".join([str(_A) for item in self])
def __getitem__( self , _A):
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 , _A , _A):
if not 0 <= index < len(self):
raise ValueError('list index out of range.')
SCREAMING_SNAKE_CASE_ = self.head
for _ in range(_A):
SCREAMING_SNAKE_CASE_ = current.next
SCREAMING_SNAKE_CASE_ = data
def lowerCAmelCase__ ( self , _A):
self.insert_nth(len(self) , _A)
def lowerCAmelCase__ ( self , _A):
self.insert_nth(0 , _A)
def lowerCAmelCase__ ( self , _A , _A):
if not 0 <= index <= len(self):
raise IndexError('list index out of range')
SCREAMING_SNAKE_CASE_ = Node(_A)
if self.head is None:
SCREAMING_SNAKE_CASE_ = new_node
elif index == 0:
SCREAMING_SNAKE_CASE_ = self.head # link new_node to head
SCREAMING_SNAKE_CASE_ = new_node
else:
SCREAMING_SNAKE_CASE_ = self.head
for _ in range(index - 1):
SCREAMING_SNAKE_CASE_ = temp.next
SCREAMING_SNAKE_CASE_ = temp.next
SCREAMING_SNAKE_CASE_ = new_node
def lowerCAmelCase__ ( self): # print every node data
print(self)
def lowerCAmelCase__ ( self):
return self.delete_nth(0)
def lowerCAmelCase__ ( self): # delete from tail
return self.delete_nth(len(self) - 1)
def lowerCAmelCase__ ( self , _A = 0):
if not 0 <= index <= len(self) - 1: # test if index is valid
raise IndexError('List index out of range.')
SCREAMING_SNAKE_CASE_ = self.head # default first node
if index == 0:
SCREAMING_SNAKE_CASE_ = self.head.next
else:
SCREAMING_SNAKE_CASE_ = self.head
for _ in range(index - 1):
SCREAMING_SNAKE_CASE_ = temp.next
SCREAMING_SNAKE_CASE_ = temp.next
SCREAMING_SNAKE_CASE_ = temp.next.next
return delete_node.data
def lowerCAmelCase__ ( self):
return self.head is None
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = self.head
while current:
# Store the current node's next node.
SCREAMING_SNAKE_CASE_ = current.next
# Make the current node's next point backwards
SCREAMING_SNAKE_CASE_ = prev
# Make the previous node be the current node
SCREAMING_SNAKE_CASE_ = current
# Make the current node the next node (to progress iteration)
SCREAMING_SNAKE_CASE_ = next_node
# Return prev in order to put the head at the end
SCREAMING_SNAKE_CASE_ = prev
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = LinkedList()
assert linked_list.is_empty() is True
assert str(_SCREAMING_SNAKE_CASE ) == ""
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(_SCREAMING_SNAKE_CASE ) == i
linked_list.insert_nth(_SCREAMING_SNAKE_CASE , i + 1 )
assert str(_SCREAMING_SNAKE_CASE ) == "->".join(str(_SCREAMING_SNAKE_CASE ) for i in range(1 , 11 ) )
linked_list.insert_head(0 )
linked_list.insert_tail(11 )
assert str(_SCREAMING_SNAKE_CASE ) == "->".join(str(_SCREAMING_SNAKE_CASE ) 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(_SCREAMING_SNAKE_CASE ) == 9
assert str(_SCREAMING_SNAKE_CASE ) == "->".join(str(_SCREAMING_SNAKE_CASE ) 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 ):
SCREAMING_SNAKE_CASE_ = -i
assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True
linked_list.reverse()
assert str(_SCREAMING_SNAKE_CASE ) == "->".join(str(_SCREAMING_SNAKE_CASE ) for i in range(-8 , 1 ) )
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [
-9,
100,
Node(77_345_112 ),
'dlrow olleH',
7,
5_555,
0,
-192.55555,
'Hello, world!',
77.9,
Node(10 ),
None,
None,
12.20,
]
SCREAMING_SNAKE_CASE_ = LinkedList()
for i in test_input:
linked_list.insert_tail(_SCREAMING_SNAKE_CASE )
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(_SCREAMING_SNAKE_CASE ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->"
"-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the head
SCREAMING_SNAKE_CASE_ = linked_list.delete_head()
assert result == -9
assert (
str(_SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->"
"Hello, world!->77.9->Node(10)->None->None->12.2"
)
# Delete the tail
SCREAMING_SNAKE_CASE_ = linked_list.delete_tail()
assert result == 12.2
assert (
str(_SCREAMING_SNAKE_CASE ) == "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
SCREAMING_SNAKE_CASE_ = linked_list.delete_nth(10 )
assert result is None
assert (
str(_SCREAMING_SNAKE_CASE ) == "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(_SCREAMING_SNAKE_CASE )
== "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(_SCREAMING_SNAKE_CASE )
assert (
str(_SCREAMING_SNAKE_CASE )
== "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(_SCREAMING_SNAKE_CASE )
== "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->"
"7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)"
)
def _UpperCAmelCase ( ):
"""simple docstring"""
from doctest import testmod
testmod()
SCREAMING_SNAKE_CASE_ = 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(_SCREAMING_SNAKE_CASE )
print('\nReading/changing Node data using indexing:' )
print(f"""Element at Position 1: {linked_list[1]}""" )
SCREAMING_SNAKE_CASE_ = input('Enter New Value: ' ).strip()
print('New list:' )
print(_SCREAMING_SNAKE_CASE )
print(f"""length of linked_list is : {len(_SCREAMING_SNAKE_CASE )}""" )
if __name__ == "__main__":
main()
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Optional[int] = {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
),
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Optional[int] = 'dpr'
def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1E-12 , _A=0 , _A="absolute" , _A = 0 , **_A , ):
super().__init__(pad_token_id=_A , **_A)
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = projection_dim
SCREAMING_SNAKE_CASE_ = position_embedding_type
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list ):
"""simple docstring"""
if len(_SCREAMING_SNAKE_CASE ) <= 1:
return [tuple(_SCREAMING_SNAKE_CASE )]
SCREAMING_SNAKE_CASE_ = []
def generate(_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list ):
SCREAMING_SNAKE_CASE_ = [0] * n
res.append(tuple(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = 0
while i < n:
if c[i] < i:
if i % 2 == 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = arr[i], arr[0]
else:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = arr[i], arr[c[i]]
res.append(tuple(_SCREAMING_SNAKE_CASE ) )
c[i] += 1
SCREAMING_SNAKE_CASE_ = 0
else:
SCREAMING_SNAKE_CASE_ = 0
i += 1
generate(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
return res
if __name__ == "__main__":
UpperCamelCase__ : str = input("Enter numbers separated by a comma:\n").strip()
UpperCamelCase__ : str = [int(item) for item in user_input.split(",")]
print(heaps(arr))
| 620 |
import pytest
import datasets
# Import fixture modules as plugins
UpperCamelCase__ : Union[str, Any] = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for item in items:
if any(marker in item.keywords for marker in ['integration', 'unit'] ):
continue
item.add_marker(pytest.mark.unit )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = tmp_path_factory.getbasetemp() / 'cache'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'datasets'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'metrics'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'modules'
monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads'
monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads' / 'extracted'
monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE , scope='session' )
def _UpperCAmelCase ( ):
"""simple docstring"""
datasets.disable_progress_bar()
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , _SCREAMING_SNAKE_CASE )
| 620 | 1 |
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.metrics import fa_score
import datasets
UpperCamelCase__ : Dict = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n"
UpperCamelCase__ : List[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n"
UpperCamelCase__ : Union[str, Any] = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n"
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
return float((preds == labels).mean() )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = float(fa_score(y_true=_SCREAMING_SNAKE_CASE , y_pred=_SCREAMING_SNAKE_CASE ) )
return {
"accuracy": acc,
"f1": fa,
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = np.array(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = np.array(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = en_sentvecs.shape[0]
# mean centering
SCREAMING_SNAKE_CASE_ = en_sentvecs - np.mean(_SCREAMING_SNAKE_CASE , axis=0 )
SCREAMING_SNAKE_CASE_ = in_sentvecs - np.mean(_SCREAMING_SNAKE_CASE , axis=0 )
SCREAMING_SNAKE_CASE_ = cdist(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'cosine' )
SCREAMING_SNAKE_CASE_ = np.array(range(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = sim.argsort(axis=1 )[:, :10]
SCREAMING_SNAKE_CASE_ = np.any(preds == actual[:, None] , axis=1 )
return float(matches.mean() )
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __snake_case ( datasets.Metric ):
def lowerCAmelCase__ ( self):
if self.config_name not in [
"wnli",
"copa",
"sna",
"csqa",
"wstp",
"inltkh",
"bbca",
"cvit-mkb-clsr",
"iitp-mr",
"iitp-pr",
"actsa-sc",
"md",
"wiki-ner",
]:
raise KeyError(
'You should supply a configuration name selected in '
'["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", '
'"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", '
'"wiki-ner"]')
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'predictions': datasets.Value('int64')
if self.config_name != 'cvit-mkb-clsr'
else datasets.Sequence(datasets.Value('float32')),
'references': datasets.Value('int64')
if self.config_name != 'cvit-mkb-clsr'
else datasets.Sequence(datasets.Value('float32')),
}) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , )
def lowerCAmelCase__ ( self , _A , _A):
if self.config_name == "cvit-mkb-clsr":
return {"precision@10": precision_at_aa(_A , _A)}
elif self.config_name in ["wiki-ner"]:
return acc_and_fa(_A , _A)
elif self.config_name in [
"wnli",
"copa",
"sna",
"csqa",
"wstp",
"inltkh",
"bbca",
"iitp-mr",
"iitp-pr",
"actsa-sc",
"md",
]:
return {"accuracy": simple_accuracy(_A , _A)}
else:
raise KeyError(
'You should supply a configuration name selected in '
'["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", '
'"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", '
'"wiki-ner"]')
| 620 |
from typing import List
import numpy as np
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {key: len(_SCREAMING_SNAKE_CASE ) for key, value in gen_kwargs.items() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
'Sharding is ambiguous for this dataset: '
+ 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
+ '\n'.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items() )
+ '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
+ 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
) )
SCREAMING_SNAKE_CASE_ = max(lists_lengths.values() , default=0 )
return max(1 , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for group_idx in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
SCREAMING_SNAKE_CASE_ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
SCREAMING_SNAKE_CASE_ = range(_SCREAMING_SNAKE_CASE , start + num_shards_to_add )
shards_indices_per_group.append(_SCREAMING_SNAKE_CASE )
return shards_indices_per_group
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = _number_of_shards_in_gen_kwargs(_SCREAMING_SNAKE_CASE )
if num_shards == 1:
return [dict(_SCREAMING_SNAKE_CASE )]
else:
SCREAMING_SNAKE_CASE_ = _distribute_shards(num_shards=_SCREAMING_SNAKE_CASE , max_num_jobs=_SCREAMING_SNAKE_CASE )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(_SCREAMING_SNAKE_CASE ) )
]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[dict] ):
"""simple docstring"""
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key] , _SCREAMING_SNAKE_CASE )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : np.random.Generator , _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {len(_SCREAMING_SNAKE_CASE ) for value in gen_kwargs.values() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
SCREAMING_SNAKE_CASE_ = {}
for size in list_sizes:
SCREAMING_SNAKE_CASE_ = list(range(_SCREAMING_SNAKE_CASE ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
SCREAMING_SNAKE_CASE_ = dict(_SCREAMING_SNAKE_CASE )
for key, value in shuffled_kwargs.items():
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = [value[i] for i in indices_per_size[len(_SCREAMING_SNAKE_CASE )]]
return shuffled_kwargs
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = word.split()
def justify(_SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ) -> str:
SCREAMING_SNAKE_CASE_ = max_width - width
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE )
if len(_SCREAMING_SNAKE_CASE ) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * overall_spaces_count
else:
SCREAMING_SNAKE_CASE_ = words_count - 1
# num_spaces_between_words_list[i] : tells you to insert
# num_spaces_between_words_list[i] spaces
# after word on line[i]
SCREAMING_SNAKE_CASE_ = spaces_to_insert_between_words * [
overall_spaces_count // spaces_to_insert_between_words
]
SCREAMING_SNAKE_CASE_ = (
overall_spaces_count % spaces_to_insert_between_words
)
# distribute spaces via round robin to the left words
for i in range(_SCREAMING_SNAKE_CASE ):
num_spaces_between_words_list[i] += 1
SCREAMING_SNAKE_CASE_ = []
for i in range(_SCREAMING_SNAKE_CASE ):
# add the word
aligned_words_list.append(line[i] )
# add the spaces to insert
aligned_words_list.append(num_spaces_between_words_list[i] * ' ' )
# just add the last word to the sentence
aligned_words_list.append(line[-1] )
# join the aligned words list to form a justified line
return "".join(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for word in words:
if width + len(_SCREAMING_SNAKE_CASE ) + len(_SCREAMING_SNAKE_CASE ) <= max_width:
# keep adding words until we can fill out max_width
# width = sum of length of all words (without overall_spaces_count)
# len(word) = length of current word
# len(line) = number of overall_spaces_count to insert between words
line.append(_SCREAMING_SNAKE_CASE )
width += len(_SCREAMING_SNAKE_CASE )
else:
# justify the line and add it to result
answer.append(justify(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
# reset new line and new width
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = [word], len(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = max_width - width - len(_SCREAMING_SNAKE_CASE )
answer.append(' '.join(_SCREAMING_SNAKE_CASE ) + (remaining_spaces + 1) * ' ' )
return answer
if __name__ == "__main__":
from doctest import testmod
testmod()
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
UpperCamelCase__ : List[str] = {
"microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json",
# See all BioGPT models at https://huggingface.co/models?filter=biogpt
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Any = 'biogpt'
def __init__( self , _A=42384 , _A=1024 , _A=24 , _A=16 , _A=4096 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1024 , _A=0.0_2 , _A=1E-12 , _A=True , _A=True , _A=0.0 , _A=0.0 , _A=1 , _A=0 , _A=2 , **_A , ):
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = scale_embedding
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = layerdrop
SCREAMING_SNAKE_CASE_ = activation_dropout
super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A)
| 620 | 1 |
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
import diffusers
from diffusers import (
AutoencoderKL,
EulerDiscreteScheduler,
StableDiffusionLatentUpscalePipeline,
StableDiffusionPipeline,
UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [tensor.shape for tensor in tensor_list]
return all(shape == shapes[0] for shape in shapes[1:] )
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : List[Any] = StableDiffusionLatentUpscalePipeline
__lowerCAmelCase : int = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
'height',
'width',
'cross_attention_kwargs',
'negative_prompt_embeds',
'prompt_embeds',
}
__lowerCAmelCase : Any = PipelineTesterMixin.required_optional_params - {'num_images_per_prompt'}
__lowerCAmelCase : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
__lowerCAmelCase : Any = frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
__lowerCAmelCase : Tuple = frozenset([] )
__lowerCAmelCase : Tuple = True
@property
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 4
SCREAMING_SNAKE_CASE_ = (16, 16)
SCREAMING_SNAKE_CASE_ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0)).to(_A)
return image
def lowerCAmelCase__ ( self):
torch.manual_seed(0)
SCREAMING_SNAKE_CASE_ = UNetaDConditionModel(
act_fn='gelu' , attention_head_dim=8 , norm_num_groups=_A , block_out_channels=[32, 32, 64, 64] , time_cond_proj_dim=160 , conv_in_kernel=1 , conv_out_kernel=1 , cross_attention_dim=32 , down_block_types=(
'KDownBlock2D',
'KCrossAttnDownBlock2D',
'KCrossAttnDownBlock2D',
'KCrossAttnDownBlock2D',
) , in_channels=8 , mid_block_type=_A , only_cross_attention=_A , out_channels=5 , resnet_time_scale_shift='scale_shift' , time_embedding_type='fourier' , timestep_post_act='gelu' , up_block_types=('KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KCrossAttnUpBlock2D', 'KUpBlock2D') , )
SCREAMING_SNAKE_CASE_ = AutoencoderKL(
block_out_channels=[32, 32, 64, 64] , in_channels=3 , out_channels=3 , down_block_types=[
'DownEncoderBlock2D',
'DownEncoderBlock2D',
'DownEncoderBlock2D',
'DownEncoderBlock2D',
] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , )
SCREAMING_SNAKE_CASE_ = EulerDiscreteScheduler(prediction_type='sample')
SCREAMING_SNAKE_CASE_ = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='quick_gelu' , projection_dim=512 , )
SCREAMING_SNAKE_CASE_ = CLIPTextModel(_A)
SCREAMING_SNAKE_CASE_ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')
SCREAMING_SNAKE_CASE_ = {
'unet': model.eval(),
'vae': vae.eval(),
'scheduler': scheduler,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
}
return components
def lowerCAmelCase__ ( self , _A , _A=0):
if str(_A).startswith('mps'):
SCREAMING_SNAKE_CASE_ = torch.manual_seed(_A)
else:
SCREAMING_SNAKE_CASE_ = torch.Generator(device=_A).manual_seed(_A)
SCREAMING_SNAKE_CASE_ = {
'prompt': 'A painting of a squirrel eating a burger',
'image': self.dummy_image.cpu(),
'generator': generator,
'num_inference_steps': 2,
'output_type': 'numpy',
}
return inputs
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 'cpu'
SCREAMING_SNAKE_CASE_ = self.get_dummy_components()
SCREAMING_SNAKE_CASE_ = self.pipeline_class(**_A)
pipe.to(_A)
pipe.set_progress_bar_config(disable=_A)
SCREAMING_SNAKE_CASE_ = self.get_dummy_inputs(_A)
SCREAMING_SNAKE_CASE_ = pipe(**_A).images
SCREAMING_SNAKE_CASE_ = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 256, 256, 3))
SCREAMING_SNAKE_CASE_ = np.array(
[0.4_7_2_2_2_4_1_2, 0.4_1_9_2_1_6_3_3, 0.4_4_7_1_7_4_3_4, 0.4_6_8_7_4_1_9_2, 0.4_2_5_8_8_2_5_8, 0.4_6_1_5_0_7_2_6, 0.4_6_7_7_5_3_4, 0.4_5_5_8_3_8_3_2, 0.4_8_5_7_9_0_5_5])
SCREAMING_SNAKE_CASE_ = np.abs(image_slice.flatten() - expected_slice).max()
self.assertLessEqual(_A , 1E-3)
def lowerCAmelCase__ ( self):
super().test_attention_slicing_forward_pass(expected_max_diff=7E-3)
def lowerCAmelCase__ ( self):
super().test_cpu_offload_forward_pass(expected_max_diff=3E-3)
def lowerCAmelCase__ ( self):
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3)
def lowerCAmelCase__ ( self):
super().test_inference_batch_single_identical(expected_max_diff=7E-3)
def lowerCAmelCase__ ( self):
super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3E-3)
def lowerCAmelCase__ ( self):
super().test_save_load_local(expected_max_difference=3E-3)
def lowerCAmelCase__ ( self):
super().test_save_load_optional_components(expected_max_difference=3E-3)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = [
'DDIMScheduler',
'DDPMScheduler',
'PNDMScheduler',
'HeunDiscreteScheduler',
'EulerAncestralDiscreteScheduler',
'KDPM2DiscreteScheduler',
'KDPM2AncestralDiscreteScheduler',
'DPMSolverSDEScheduler',
]
SCREAMING_SNAKE_CASE_ = self.get_dummy_components()
SCREAMING_SNAKE_CASE_ = self.pipeline_class(**_A)
# make sure that PNDM does not need warm-up
pipe.scheduler.register_to_config(skip_prk_steps=_A)
pipe.to(_A)
pipe.set_progress_bar_config(disable=_A)
SCREAMING_SNAKE_CASE_ = self.get_dummy_inputs(_A)
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = []
for scheduler_enum in KarrasDiffusionSchedulers:
if scheduler_enum.name in skip_schedulers:
# no sigma schedulers are not supported
# no schedulers
continue
SCREAMING_SNAKE_CASE_ = getattr(_A , scheduler_enum.name)
SCREAMING_SNAKE_CASE_ = scheduler_cls.from_config(pipe.scheduler.config)
SCREAMING_SNAKE_CASE_ = pipe(**_A)[0]
outputs.append(_A)
assert check_same_shape(_A)
@require_torch_gpu
@slow
class __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = torch.manual_seed(33)
SCREAMING_SNAKE_CASE_ = StableDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' , torch_dtype=torch.floataa)
pipe.to('cuda')
SCREAMING_SNAKE_CASE_ = StableDiffusionLatentUpscalePipeline.from_pretrained(
'stabilityai/sd-x2-latent-upscaler' , torch_dtype=torch.floataa)
upscaler.to('cuda')
SCREAMING_SNAKE_CASE_ = 'a photo of an astronaut high resolution, unreal engine, ultra realistic'
SCREAMING_SNAKE_CASE_ = pipe(_A , generator=_A , output_type='latent').images
SCREAMING_SNAKE_CASE_ = upscaler(
prompt=_A , image=_A , num_inference_steps=20 , guidance_scale=0 , generator=_A , output_type='np' , ).images[0]
SCREAMING_SNAKE_CASE_ = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy')
assert np.abs((expected_image - image).mean()) < 5E-2
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = torch.manual_seed(33)
SCREAMING_SNAKE_CASE_ = StableDiffusionLatentUpscalePipeline.from_pretrained(
'stabilityai/sd-x2-latent-upscaler' , torch_dtype=torch.floataa)
upscaler.to('cuda')
SCREAMING_SNAKE_CASE_ = 'the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas'
SCREAMING_SNAKE_CASE_ = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png')
SCREAMING_SNAKE_CASE_ = upscaler(
prompt=_A , image=_A , num_inference_steps=20 , guidance_scale=0 , generator=_A , output_type='np' , ).images[0]
SCREAMING_SNAKE_CASE_ = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy')
assert np.abs((expected_image - image).max()) < 5E-2
| 620 |
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A , _A , _A = None , ):
super().__init__()
self.register_modules(transformer=_A , vae=_A , scheduler=_A)
# create a imagenet -> id dictionary for easier use
SCREAMING_SNAKE_CASE_ = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(','):
SCREAMING_SNAKE_CASE_ = int(_A)
SCREAMING_SNAKE_CASE_ = dict(sorted(self.labels.items()))
def lowerCAmelCase__ ( self , _A):
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = list(_A)
for l in label:
if l not in self.labels:
raise ValueError(
f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""")
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self , _A , _A = 4.0 , _A = None , _A = 50 , _A = "pil" , _A = True , ):
SCREAMING_SNAKE_CASE_ = len(_A)
SCREAMING_SNAKE_CASE_ = self.transformer.config.sample_size
SCREAMING_SNAKE_CASE_ = self.transformer.config.in_channels
SCREAMING_SNAKE_CASE_ = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=_A , device=self.device , dtype=self.transformer.dtype , )
SCREAMING_SNAKE_CASE_ = torch.cat([latents] * 2) if guidance_scale > 1 else latents
SCREAMING_SNAKE_CASE_ = torch.tensor(_A , device=self.device).reshape(-1)
SCREAMING_SNAKE_CASE_ = torch.tensor([1000] * batch_size , device=self.device)
SCREAMING_SNAKE_CASE_ = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(_A)
for t in self.progress_bar(self.scheduler.timesteps):
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ = latent_model_input[: len(_A) // 2]
SCREAMING_SNAKE_CASE_ = torch.cat([half, half] , dim=0)
SCREAMING_SNAKE_CASE_ = self.scheduler.scale_model_input(_A , _A)
SCREAMING_SNAKE_CASE_ = t
if not torch.is_tensor(_A):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
SCREAMING_SNAKE_CASE_ = latent_model_input.device.type == 'mps'
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = torch.floataa if is_mps else torch.floataa
else:
SCREAMING_SNAKE_CASE_ = torch.intaa if is_mps else torch.intaa
SCREAMING_SNAKE_CASE_ = torch.tensor([timesteps] , dtype=_A , device=latent_model_input.device)
elif len(timesteps.shape) == 0:
SCREAMING_SNAKE_CASE_ = timesteps[None].to(latent_model_input.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
SCREAMING_SNAKE_CASE_ = timesteps.expand(latent_model_input.shape[0])
# predict noise model_output
SCREAMING_SNAKE_CASE_ = self.transformer(
_A , timestep=_A , class_labels=_A).sample
# perform guidance
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , len(_A) // 2 , dim=0)
SCREAMING_SNAKE_CASE_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
SCREAMING_SNAKE_CASE_ = torch.cat([half_eps, half_eps] , dim=0)
SCREAMING_SNAKE_CASE_ = torch.cat([eps, rest] , dim=1)
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , _A , dim=1)
else:
SCREAMING_SNAKE_CASE_ = noise_pred
# compute previous image: x_t -> x_t-1
SCREAMING_SNAKE_CASE_ = self.scheduler.step(_A , _A , _A).prev_sample
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = latent_model_input.chunk(2 , dim=0)
else:
SCREAMING_SNAKE_CASE_ = latent_model_input
SCREAMING_SNAKE_CASE_ = 1 / self.vae.config.scaling_factor * latents
SCREAMING_SNAKE_CASE_ = self.vae.decode(_A).sample
SCREAMING_SNAKE_CASE_ = (samples / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
SCREAMING_SNAKE_CASE_ = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_A)
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=_A)
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [0 for i in range(r + 1 )]
# nc0 = 1
SCREAMING_SNAKE_CASE_ = 1
for i in range(1 , n + 1 ):
# to compute current row from previous row.
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r]
print(binomial_coefficient(n=10, r=5))
| 620 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class __snake_case :
def __init__( self , _A , _A , _A , _A , _A , _A=0.2 , _A=0.2):
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = conva_get[:2]
SCREAMING_SNAKE_CASE_ = conva_get[2]
SCREAMING_SNAKE_CASE_ = size_pa
SCREAMING_SNAKE_CASE_ = rate_w
SCREAMING_SNAKE_CASE_ = rate_t
SCREAMING_SNAKE_CASE_ = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5)
for i in range(self.conva[1])
]
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.conva[1]) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
def lowerCAmelCase__ ( self , _A):
# save model dict with pickle
SCREAMING_SNAKE_CASE_ = {
'num_bp1': self.num_bpa,
'num_bp2': self.num_bpa,
'num_bp3': self.num_bpa,
'conv1': self.conva,
'step_conv1': self.step_conva,
'size_pooling1': self.size_poolinga,
'rate_weight': self.rate_weight,
'rate_thre': self.rate_thre,
'w_conv1': self.w_conva,
'wkj': self.wkj,
'vji': self.vji,
'thre_conv1': self.thre_conva,
'thre_bp2': self.thre_bpa,
'thre_bp3': self.thre_bpa,
}
with open(_A , 'wb') as f:
pickle.dump(_A , _A)
print(f"""Model saved: {save_path}""")
@classmethod
def lowerCAmelCase__ ( cls , _A):
# read saved model
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = pickle.load(_A) # noqa: S301
SCREAMING_SNAKE_CASE_ = model_dic.get('conv1')
conv_get.append(model_dic.get('step_conv1'))
SCREAMING_SNAKE_CASE_ = model_dic.get('size_pooling1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp3')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_weight')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_thre')
# create model instance
SCREAMING_SNAKE_CASE_ = CNN(_A , _A , _A , _A , _A , _A , _A)
# modify model parameter
SCREAMING_SNAKE_CASE_ = model_dic.get('w_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('wkj')
SCREAMING_SNAKE_CASE_ = model_dic.get('vji')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp3')
return conv_ins
def lowerCAmelCase__ ( self , _A):
return 1 / (1 + np.exp(-1 * x))
def lowerCAmelCase__ ( self , _A):
return round(_A , 3)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
# convolution process
SCREAMING_SNAKE_CASE_ = convs[0]
SCREAMING_SNAKE_CASE_ = convs[1]
SCREAMING_SNAKE_CASE_ = np.shape(_A)[0]
# get the data slice of original image data, data_focus
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , size_data - size_conv + 1 , _A):
for j_focus in range(0 , size_data - size_conv + 1 , _A):
SCREAMING_SNAKE_CASE_ = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(_A)
# calculate the feature map of every single kernel, and saved as list of matrix
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = int((size_data - size_conv) / conv_step + 1)
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(len(_A)):
SCREAMING_SNAKE_CASE_ = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map]))
- thre_convs[i_map]
)
featuremap.append(self.sig(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(
_A , _A)
data_featuremap.append(_A)
# expanding the data slice to One dimenssion
SCREAMING_SNAKE_CASE_ = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(_A))
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return focus_list, data_featuremap
def lowerCAmelCase__ ( self , _A , _A , _A="average_pool"):
# pooling process
SCREAMING_SNAKE_CASE_ = len(featuremaps[0])
SCREAMING_SNAKE_CASE_ = int(size_map / size_pooling)
SCREAMING_SNAKE_CASE_ = []
for i_map in range(len(_A)):
SCREAMING_SNAKE_CASE_ = featuremaps[i_map]
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , _A , _A):
for j_focus in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(_A))
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(_A , _A)
featuremap_pooled.append(_A)
return featuremap_pooled
def lowerCAmelCase__ ( self , _A):
# expanding three dimension data to one dimension list
SCREAMING_SNAKE_CASE_ = []
for i in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.shape(data[i])
SCREAMING_SNAKE_CASE_ = data[i].reshape(1 , shapes[0] * shapes[1])
SCREAMING_SNAKE_CASE_ = data_listed.getA().tolist()[0]
data_expanded.extend(_A)
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return data_expanded
def lowerCAmelCase__ ( self , _A):
# expanding matrix to one dimension list
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = data_mat.reshape(1 , shapes[0] * shapes[1])
return data_expanded
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = np.ones((size_map, size_map))
for i in range(0 , _A , _A):
for j in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = pd_pool[
i_pool
]
SCREAMING_SNAKE_CASE_ = i_pool + 1
SCREAMING_SNAKE_CASE_ = np.multiply(
_A , np.multiply(out_map[i_map] , (1 - out_map[i_map])))
pd_all.append(_A)
return pd_all
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , _A=bool):
# model traning
print('----------------------Start Training-------------------------')
print((' - - Shape: Train_Data ', np.shape(_A)))
print((' - - Shape: Teach_Data ', np.shape(_A)))
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 10000
while rp < n_repeat and mse >= error_accuracy:
SCREAMING_SNAKE_CASE_ = 0
print(f"""-------------Learning Time {rp}--------------""")
for p in range(len(_A)):
# print('------------Learning Image: %d--------------'%p)
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_train[p])
SCREAMING_SNAKE_CASE_ = np.asarray(datas_teach[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.wkj.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
SCREAMING_SNAKE_CASE_ = np.multiply(
(data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.multiply(
np.dot(_A , self.wkj) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji)
SCREAMING_SNAKE_CASE_ = pd_i_all / (self.size_poolinga * self.size_poolinga)
SCREAMING_SNAKE_CASE_ = pd_conva_pooled.T.getA().tolist()
SCREAMING_SNAKE_CASE_ = self._calculate_gradient_from_pool(
_A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1]):
SCREAMING_SNAKE_CASE_ = self._expand_mat(pd_conva_all[k_conv])
SCREAMING_SNAKE_CASE_ = self.rate_weight * np.dot(_A , _A)
SCREAMING_SNAKE_CASE_ = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]))
SCREAMING_SNAKE_CASE_ = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv]) * self.rate_thre
)
# all connected layer
SCREAMING_SNAKE_CASE_ = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.vji + pd_j_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_k_all * self.rate_thre
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
SCREAMING_SNAKE_CASE_ = np.sum(abs(data_teach - bp_outa))
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
SCREAMING_SNAKE_CASE_ = rp + 1
SCREAMING_SNAKE_CASE_ = error_count / patterns
all_mse.append(_A)
def draw_error():
SCREAMING_SNAKE_CASE_ = [error_accuracy for i in range(int(n_repeat * 1.2))]
plt.plot(_A , '+-')
plt.plot(_A , 'r--')
plt.xlabel('Learning Times')
plt.ylabel('All_mse')
plt.grid(_A , alpha=0.5)
plt.show()
print('------------------Training Complished---------------------')
print((' - - Training epoch: ', rp, f""" - - Mse: {mse:.6f}"""))
if draw_e:
draw_error()
return mse
def lowerCAmelCase__ ( self , _A):
# model predict
SCREAMING_SNAKE_CASE_ = []
print('-------------------Start Testing-------------------------')
print((' - - Shape: Test_Data ', np.shape(_A)))
for p in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_test[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = bp_outa * self.vji.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = bp_outa * self.wkj.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
produce_out.extend(bp_outa.getA().tolist())
SCREAMING_SNAKE_CASE_ = [list(map(self.do_round , _A)) for each in produce_out]
return np.asarray(_A)
def lowerCAmelCase__ ( self , _A):
# return the data of image after convoluting process so we can check it out
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 620 | 1 |
import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Tuple = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase__ : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
@dataclass
class __snake_case :
__lowerCAmelCase : str = field(
default=lowerCAmelCase__ , metadata={'help': 'Model type selected in the list: ' + ', '.join(lowerCAmelCase__ )} )
__lowerCAmelCase : str = field(
default=lowerCAmelCase__ , metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
__lowerCAmelCase : int = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
__lowerCAmelCase : int = field(
default=128 , metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'} , )
__lowerCAmelCase : int = field(
default=64 , metadata={
'help': (
'The maximum number of tokens for the question. Questions longer than this will '
'be truncated to this length.'
)
} , )
__lowerCAmelCase : int = field(
default=30 , metadata={
'help': (
'The maximum length of an answer that can be generated. This is needed because the start '
'and end predictions are not conditioned on one another.'
)
} , )
__lowerCAmelCase : bool = field(
default=lowerCAmelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
__lowerCAmelCase : bool = field(
default=lowerCAmelCase__ , metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
__lowerCAmelCase : float = field(
default=0.0 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
__lowerCAmelCase : int = field(
default=20 , metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
__lowerCAmelCase : int = field(
default=0 , metadata={
'help': (
'language id of input for language-specific xlm models (see'
' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
)
} , )
__lowerCAmelCase : int = field(default=1 , metadata={'help': 'multiple threads for converting example to features'} )
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Optional[int] = 'train'
__lowerCAmelCase : Tuple = 'dev'
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : SquadDataTrainingArguments
__lowerCAmelCase : List[SquadFeatures]
__lowerCAmelCase : Split
__lowerCAmelCase : bool
def __init__( self , _A , _A , _A = None , _A = Split.train , _A = False , _A = None , _A = "pt" , ):
SCREAMING_SNAKE_CASE_ = args
SCREAMING_SNAKE_CASE_ = is_language_sensitive
SCREAMING_SNAKE_CASE_ = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
if isinstance(_A , _A):
try:
SCREAMING_SNAKE_CASE_ = Split[mode]
except KeyError:
raise KeyError('mode is not a valid split name')
SCREAMING_SNAKE_CASE_ = mode
# Load data features from cache or dataset file
SCREAMING_SNAKE_CASE_ = 'v2' if args.version_2_with_negative else 'v1'
SCREAMING_SNAKE_CASE_ = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
SCREAMING_SNAKE_CASE_ = cached_features_file + '.lock'
with FileLock(_A):
if os.path.exists(_A) and not args.overwrite_cache:
SCREAMING_SNAKE_CASE_ = time.time()
SCREAMING_SNAKE_CASE_ = torch.load(_A)
# Legacy cache files have only features, while new cache files
# will have dataset and examples also.
SCREAMING_SNAKE_CASE_ = self.old_features['features']
SCREAMING_SNAKE_CASE_ = self.old_features.get('dataset' , _A)
SCREAMING_SNAKE_CASE_ = self.old_features.get('examples' , _A)
logger.info(
f"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start)
if self.dataset is None or self.examples is None:
logger.warning(
f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
' future run')
else:
if mode == Split.dev:
SCREAMING_SNAKE_CASE_ = self.processor.get_dev_examples(args.data_dir)
else:
SCREAMING_SNAKE_CASE_ = self.processor.get_train_examples(args.data_dir)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = squad_convert_examples_to_features(
examples=self.examples , tokenizer=_A , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=_A , )
SCREAMING_SNAKE_CASE_ = time.time()
torch.save(
{'features': self.features, 'dataset': self.dataset, 'examples': self.examples} , _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):
return len(self.features)
def __getitem__( self , _A):
# Convert to Tensors and build dataset
SCREAMING_SNAKE_CASE_ = self.features[i]
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.input_ids , dtype=torch.long)
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.attention_mask , dtype=torch.long)
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.token_type_ids , dtype=torch.long)
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.cls_index , dtype=torch.long)
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.p_mask , dtype=torch.float)
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.is_impossible , dtype=torch.float)
SCREAMING_SNAKE_CASE_ = {
'input_ids': input_ids,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids,
}
if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
del inputs["token_type_ids"]
if self.args.model_type in ["xlnet", "xlm"]:
inputs.update({'cls_index': cls_index, 'p_mask': p_mask})
if self.args.version_2_with_negative:
inputs.update({'is_impossible': is_impossible})
if self.is_language_sensitive:
inputs.update({'langs': (torch.ones(input_ids.shape , dtype=torch.intaa) * self.args.lang_id)})
if self.mode == Split.train:
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.start_position , dtype=torch.long)
SCREAMING_SNAKE_CASE_ = torch.tensor(feature.end_position , dtype=torch.long)
inputs.update({'start_positions': start_positions, 'end_positions': end_positions})
return inputs
| 620 |
import os
import zipfile
import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int=7 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = None
if token is not None:
SCREAMING_SNAKE_CASE_ = {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}
# The id of a workflow (not of a workflow run)
SCREAMING_SNAKE_CASE_ = '636036'
SCREAMING_SNAKE_CASE_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""
SCREAMING_SNAKE_CASE_ = requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).json()
return result["workflow_runs"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_daily_ci_runs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = None
for workflow_run in workflow_runs:
if workflow_run["status"] == "completed":
SCREAMING_SNAKE_CASE_ = workflow_run['id']
break
return workflow_run_id
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE )
if workflow_run_id is not None:
SCREAMING_SNAKE_CASE_ = get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
for artifact_name in artifact_names:
if artifact_name in artifacts_links:
SCREAMING_SNAKE_CASE_ = artifacts_links[artifact_name]
download_artifact(
artifact_name=_SCREAMING_SNAKE_CASE , artifact_url=_SCREAMING_SNAKE_CASE , output_dir=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
for artifact_name in artifact_names:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{artifact_name}.zip""" )
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = {}
with zipfile.ZipFile(_SCREAMING_SNAKE_CASE ) as z:
for filename in z.namelist():
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
# read the file
with z.open(_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ = f.read().decode('UTF-8' )
return results
| 620 | 1 |
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
UpperCamelCase__ : str = "sshleifer/bart-tiny-random"
UpperCamelCase__ : Optional[int] = "patrickvonplaten/t5-tiny-random"
@require_torch
class __snake_case ( unittest.TestCase ):
@cached_property
def lowerCAmelCase__ ( self):
return AutoConfig.from_pretrained(_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ = create_student_by_copying_alternating_layers(_A , tempfile.mkdtemp() , e=1 , d=1)
self.assertEqual(student.config.num_hidden_layers , 1)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ = create_student_by_copying_alternating_layers(_A , tempfile.mkdtemp() , e=1 , d=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ = 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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ = 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 lowerCAmelCase__ ( self):
with self.assertRaises(_A):
create_student_by_copying_alternating_layers(_A , tempfile.mkdtemp() , e=_A , d=_A)
| 620 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase__ : Any = {
"configuration_mvp": ["MVP_PRETRAINED_CONFIG_ARCHIVE_MAP", "MvpConfig", "MvpOnnxConfig"],
"tokenization_mvp": ["MvpTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[int] = ["MvpTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"MVP_PRETRAINED_MODEL_ARCHIVE_LIST",
"MvpForCausalLM",
"MvpForConditionalGeneration",
"MvpForQuestionAnswering",
"MvpForSequenceClassification",
"MvpModel",
"MvpPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
UpperCamelCase__ : Optional[int] = 9.8_06_65
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float = g ):
"""simple docstring"""
if fluid_density <= 0:
raise ValueError('Impossible fluid density' )
if volume < 0:
raise ValueError('Impossible Object volume' )
if gravity <= 0:
raise ValueError('Impossible Gravity' )
return fluid_density * gravity * volume
if __name__ == "__main__":
import doctest
# run doctest
doctest.testmod()
| 620 |
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Dict = inspect.getfile(accelerate.test_utils )
__lowerCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
__lowerCAmelCase : Tuple = ['accelerate', 'launch']
__lowerCAmelCase : Union[str, Any] = Path.home() / '.cache/huggingface/accelerate'
__lowerCAmelCase : List[str] = 'default_config.yaml'
__lowerCAmelCase : List[Any] = config_folder / config_file
__lowerCAmelCase : str = config_folder / '_default_config.yaml'
__lowerCAmelCase : Optional[int] = Path('tests/test_configs' )
@classmethod
def lowerCAmelCase__ ( cls):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path)
@classmethod
def lowerCAmelCase__ ( cls):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
for config in sorted(self.test_config_path.glob('**/*.yaml')):
with self.subTest(config_file=_A):
execute_subprocess_async(
self.base_cmd + ['--config_file', str(_A), self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy())
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[Any] = 'test-tpu'
__lowerCAmelCase : str = 'us-central1-a'
__lowerCAmelCase : Union[str, Any] = 'ls'
__lowerCAmelCase : Union[str, Any] = ['accelerate', 'tpu-config']
__lowerCAmelCase : Union[str, Any] = 'cd /usr/share'
__lowerCAmelCase : List[Any] = 'tests/test_samples/test_command_file.sh'
__lowerCAmelCase : Dict = 'Running gcloud compute tpus tpu-vm ssh'
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command',
self.command,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A)
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--command',
self.command,
'--command',
'echo "Hello World"',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command_file',
self.command_file,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--install_accelerate',
'--accelerate_version',
'12.0.0',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
| 620 | 1 |
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
flip_channel_order,
get_resize_output_image_size,
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_torch_available, is_torch_tensor, is_vision_available, logging
if is_vision_available():
import PIL
if is_torch_available():
import torch
UpperCamelCase__ : List[str] = logging.get_logger(__name__)
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Union[str, Any] = ['pixel_values']
def __init__( self , _A = True , _A = None , _A = PILImageResampling.BILINEAR , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = True , **_A , ):
super().__init__(**_A)
SCREAMING_SNAKE_CASE_ = size if size is not None else {'shortest_edge': 224}
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A)
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 256, 'width': 256}
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , param_name='crop_size')
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = resample
SCREAMING_SNAKE_CASE_ = do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_flip_channel_order
def lowerCAmelCase__ ( self , _A , _A , _A = PIL.Image.BILINEAR , _A = None , **_A , ):
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A)
if "shortest_edge" not in size:
raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""")
SCREAMING_SNAKE_CASE_ = get_resize_output_image_size(_A , size=size['shortest_edge'] , default_to_square=_A)
return resize(_A , size=_A , resample=_A , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A , _A = None , **_A , ):
SCREAMING_SNAKE_CASE_ = get_size_dict(_A)
if "height" not in size or "width" not in size:
raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""")
return center_crop(_A , size=(size['height'], size['width']) , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A , _A = None , **_A , ):
return rescale(_A , scale=_A , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A = None):
return flip_channel_order(_A , data_format=_A)
def lowerCAmelCase__ ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ):
SCREAMING_SNAKE_CASE_ = do_resize if do_resize is not None else self.do_resize
SCREAMING_SNAKE_CASE_ = resample if resample is not None else self.resample
SCREAMING_SNAKE_CASE_ = do_rescale if do_rescale is not None else self.do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor if rescale_factor is not None else self.rescale_factor
SCREAMING_SNAKE_CASE_ = do_center_crop if do_center_crop is not None else self.do_center_crop
SCREAMING_SNAKE_CASE_ = (
do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
)
SCREAMING_SNAKE_CASE_ = size if size is not None else self.size
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A)
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else self.crop_size
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , param_name='crop_size')
SCREAMING_SNAKE_CASE_ = make_list_of_images(_A)
if not valid_images(_A):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.')
# All transformations expect numpy arrays.
SCREAMING_SNAKE_CASE_ = [to_numpy_array(_A) for image in images]
if do_resize:
SCREAMING_SNAKE_CASE_ = [self.resize(image=_A , size=_A , resample=_A) for image in images]
if do_center_crop:
SCREAMING_SNAKE_CASE_ = [self.center_crop(image=_A , size=_A) for image in images]
if do_rescale:
SCREAMING_SNAKE_CASE_ = [self.rescale(image=_A , scale=_A) for image in images]
# the pretrained checkpoints assume images are BGR, not RGB
if do_flip_channel_order:
SCREAMING_SNAKE_CASE_ = [self.flip_channel_order(image=_A) for image in images]
SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(_A , _A) for image in images]
SCREAMING_SNAKE_CASE_ = {'pixel_values': images}
return BatchFeature(data=_A , tensor_type=_A)
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = outputs.logits
# Resize logits and compute semantic segmentation maps
if target_sizes is not None:
if len(_A) != len(_A):
raise ValueError(
'Make sure that you pass in as many target sizes as the batch dimension of the logits')
if is_torch_tensor(_A):
SCREAMING_SNAKE_CASE_ = target_sizes.numpy()
SCREAMING_SNAKE_CASE_ = []
for idx in range(len(_A)):
SCREAMING_SNAKE_CASE_ = torch.nn.functional.interpolate(
logits[idx].unsqueeze(dim=0) , size=target_sizes[idx] , mode='bilinear' , align_corners=_A)
SCREAMING_SNAKE_CASE_ = resized_logits[0].argmax(dim=0)
semantic_segmentation.append(_A)
else:
SCREAMING_SNAKE_CASE_ = logits.argmax(dim=1)
SCREAMING_SNAKE_CASE_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
return semantic_segmentation
| 620 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCamelCase__ : Tuple = {
"configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
"processing_trocr": ["TrOCRProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
"TrOCRForCausalLM",
"TrOCRPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
UpperCamelCase__ : str = logging.get_logger(__name__)
if is_vision_available():
import PIL
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = ['pixel_values']
def __init__( self , _A = True , _A = None , _A = PILImageResampling.BICUBIC , _A = True , _A = None , _A = True , _A = 1 / 255 , _A = True , _A = None , _A = None , _A = True , **_A , ):
super().__init__(**_A)
SCREAMING_SNAKE_CASE_ = size if size is not None else {'shortest_edge': 224}
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A)
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 224, 'width': 224}
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A , param_name='crop_size')
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = resample
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else OPENAI_CLIP_STD
SCREAMING_SNAKE_CASE_ = do_convert_rgb
def lowerCAmelCase__ ( self , _A , _A , _A = PILImageResampling.BICUBIC , _A = None , **_A , ):
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , default_to_square=_A)
if "shortest_edge" not in size:
raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""")
SCREAMING_SNAKE_CASE_ = get_resize_output_image_size(_A , size=size['shortest_edge'] , default_to_square=_A)
return resize(_A , size=_A , resample=_A , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A , _A = None , **_A , ):
SCREAMING_SNAKE_CASE_ = get_size_dict(_A)
if "height" not in size or "width" not in size:
raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""")
return center_crop(_A , size=(size['height'], size['width']) , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A , _A = None , **_A , ):
return rescale(_A , scale=_A , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A , _A , _A = None , **_A , ):
return normalize(_A , mean=_A , std=_A , data_format=_A , **_A)
def lowerCAmelCase__ ( self , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = None , _A = ChannelDimension.FIRST , **_A , ):
SCREAMING_SNAKE_CASE_ = do_resize if do_resize is not None else self.do_resize
SCREAMING_SNAKE_CASE_ = size if size is not None else self.size
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , param_name='size' , default_to_square=_A)
SCREAMING_SNAKE_CASE_ = resample if resample is not None else self.resample
SCREAMING_SNAKE_CASE_ = do_center_crop if do_center_crop is not None else self.do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else self.crop_size
SCREAMING_SNAKE_CASE_ = get_size_dict(_A , param_name='crop_size' , default_to_square=_A)
SCREAMING_SNAKE_CASE_ = do_rescale if do_rescale is not None else self.do_rescale
SCREAMING_SNAKE_CASE_ = rescale_factor if rescale_factor is not None else self.rescale_factor
SCREAMING_SNAKE_CASE_ = do_normalize if do_normalize is not None else self.do_normalize
SCREAMING_SNAKE_CASE_ = image_mean if image_mean is not None else self.image_mean
SCREAMING_SNAKE_CASE_ = image_std if image_std is not None else self.image_std
SCREAMING_SNAKE_CASE_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
SCREAMING_SNAKE_CASE_ = make_list_of_images(_A)
if not valid_images(_A):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.')
if do_resize and size is None:
raise ValueError('Size must be specified if do_resize is True.')
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.')
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.')
# PIL RGBA images are converted to RGB
if do_convert_rgb:
SCREAMING_SNAKE_CASE_ = [convert_to_rgb(_A) for image in images]
# All transformations expect numpy arrays.
SCREAMING_SNAKE_CASE_ = [to_numpy_array(_A) for image in images]
if do_resize:
SCREAMING_SNAKE_CASE_ = [self.resize(image=_A , size=_A , resample=_A) for image in images]
if do_center_crop:
SCREAMING_SNAKE_CASE_ = [self.center_crop(image=_A , size=_A) for image in images]
if do_rescale:
SCREAMING_SNAKE_CASE_ = [self.rescale(image=_A , scale=_A) for image in images]
if do_normalize:
SCREAMING_SNAKE_CASE_ = [self.normalize(image=_A , mean=_A , std=_A) for image in images]
SCREAMING_SNAKE_CASE_ = [to_channel_dimension_format(_A , _A) for image in images]
SCREAMING_SNAKE_CASE_ = {'pixel_values': images}
return BatchFeature(data=_A , tensor_type=_A)
| 620 |
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
UpperCamelCase__ : int = Lock()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0 , 10 ):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
SCREAMING_SNAKE_CASE_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# after all swaps are performed, send the values back to main
result_pipe[1].send(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe() )
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ):
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(
len(_SCREAMING_SNAKE_CASE ) - 1,
arr[len(_SCREAMING_SNAKE_CASE ) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1],
) , ) )
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE_ = result_pipe[p][0].recv()
process_array_[p].join()
return arr
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = list(range(10 , 0 , -1 ) )
print('Initial List' )
print(*_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = odd_even_transposition(_SCREAMING_SNAKE_CASE )
print('Sorted List\n' )
print(*_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 | 1 |
# Lint as: python3
import os
import re
import urllib.parse
from pathlib import Path
from typing import Callable, List, Optional, Union
from zipfile import ZipFile
from ..utils.file_utils import cached_path, hf_github_url
from ..utils.logging import get_logger
from ..utils.version import Version
UpperCamelCase__ : Optional[Any] = get_logger(__name__)
class __snake_case :
__lowerCAmelCase : Optional[int] = 'dummy_data'
__lowerCAmelCase : int = 'datasets'
__lowerCAmelCase : str = False
def __init__( self , _A , _A , _A , _A = None , _A = False , _A = True , _A = None , ):
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = dataset_name
SCREAMING_SNAKE_CASE_ = cache_dir
SCREAMING_SNAKE_CASE_ = use_local_dummy_data
SCREAMING_SNAKE_CASE_ = config
# download_callbacks take a single url as input
SCREAMING_SNAKE_CASE_ = download_callbacks or []
# if False, it doesn't load existing files and it returns the paths of the dummy files relative
# to the dummy_data zip file root
SCREAMING_SNAKE_CASE_ = load_existing_dummy_data
# TODO(PVP, QL) might need to make this more general
SCREAMING_SNAKE_CASE_ = str(_A)
# to be downloaded
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
@property
def lowerCAmelCase__ ( self):
if self._dummy_file is None:
SCREAMING_SNAKE_CASE_ = self.download_dummy_data()
return self._dummy_file
@property
def lowerCAmelCase__ ( self):
if self.config is not None:
# structure is dummy / config_name / version_name
return os.path.join('dummy' , self.config.name , self.version_name)
# structure is dummy / version_name
return os.path.join('dummy' , self.version_name)
@property
def lowerCAmelCase__ ( self):
return os.path.join(self.dummy_data_folder , 'dummy_data.zip')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = (
self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data
)
SCREAMING_SNAKE_CASE_ = cached_path(
_A , cache_dir=self.cache_dir , extract_compressed_file=_A , force_extract=_A)
return os.path.join(_A , self.dummy_file_name)
@property
def lowerCAmelCase__ ( self):
return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file)
@property
def lowerCAmelCase__ ( self):
if self._bucket_url is None:
SCREAMING_SNAKE_CASE_ = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '/'))
return self._bucket_url
@property
def lowerCAmelCase__ ( self):
# return full path if its a dir
if os.path.isdir(self.dummy_file):
return self.dummy_file
# else cut off path to file -> example `xsum`.
return "/".join(self.dummy_file.replace(os.sep , '/').split('/')[:-1])
def lowerCAmelCase__ ( self , _A , *_A):
if self.load_existing_dummy_data:
# dummy data is downloaded and tested
SCREAMING_SNAKE_CASE_ = self.dummy_file
else:
# dummy data cannot be downloaded and only the path to dummy file is returned
SCREAMING_SNAKE_CASE_ = self.dummy_file_name
# special case when data_url is a dict
if isinstance(_A , _A):
return self.create_dummy_data_dict(_A , _A)
elif isinstance(_A , (list, tuple)):
return self.create_dummy_data_list(_A , _A)
else:
return self.create_dummy_data_single(_A , _A)
def lowerCAmelCase__ ( self , _A , *_A):
return self.download_and_extract(_A)
def lowerCAmelCase__ ( self , _A , _A):
return self.download_and_extract(_A)
def lowerCAmelCase__ ( self , _A , *_A , **_A):
return path
def lowerCAmelCase__ ( self):
return {}
def lowerCAmelCase__ ( self , _A , _A):
SCREAMING_SNAKE_CASE_ = {}
for key, single_urls in data_url.items():
for download_callback in self.download_callbacks:
if isinstance(_A , _A):
for single_url in single_urls:
download_callback(_A)
else:
SCREAMING_SNAKE_CASE_ = single_urls
download_callback(_A)
# we force the name of each key to be the last file / folder name of the url path
# if the url has arguments, we need to encode them with urllib.parse.quote_plus
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [os.path.join(_A , urllib.parse.quote_plus(Path(_A).name)) for x in single_urls]
else:
SCREAMING_SNAKE_CASE_ = single_urls
SCREAMING_SNAKE_CASE_ = os.path.join(_A , urllib.parse.quote_plus(Path(_A).name))
SCREAMING_SNAKE_CASE_ = value
# make sure that values are unique
if all(isinstance(_A , _A) for i in dummy_data_dict.values()) and len(set(dummy_data_dict.values())) < len(
dummy_data_dict.values()):
# append key to value to make its name unique
SCREAMING_SNAKE_CASE_ = {key: value + key for key, value in dummy_data_dict.items()}
return dummy_data_dict
def lowerCAmelCase__ ( self , _A , _A):
SCREAMING_SNAKE_CASE_ = []
# trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one
SCREAMING_SNAKE_CASE_ = all(bool(re.findall('[0-9]{3,}-of-[0-9]{3,}' , _A)) for url in data_url)
SCREAMING_SNAKE_CASE_ = all(
url.startswith('https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed') for url in data_url)
if data_url and (is_tf_records or is_pubmed_records):
SCREAMING_SNAKE_CASE_ = [data_url[0]] * len(_A)
for single_url in data_url:
for download_callback in self.download_callbacks:
download_callback(_A)
# we force the name of each key to be the last file / folder name of the url path
# if the url has arguments, we need to encode them with urllib.parse.quote_plus
SCREAMING_SNAKE_CASE_ = os.path.join(_A , urllib.parse.quote_plus(single_url.split('/')[-1]))
dummy_data_list.append(_A)
return dummy_data_list
def lowerCAmelCase__ ( self , _A , _A):
for download_callback in self.download_callbacks:
download_callback(_A)
# we force the name of each key to be the last file / folder name of the url path
# if the url has arguments, we need to encode them with urllib.parse.quote_plus
SCREAMING_SNAKE_CASE_ = os.path.join(_A , urllib.parse.quote_plus(data_url.split('/')[-1]))
if os.path.exists(_A) or not self.load_existing_dummy_data:
return value
else:
# Backward compatibility, maybe deprecate at one point.
# For many datasets with single url calls to dl_manager.download_and_extract,
# the dummy_data.zip file is actually the zipped downloaded file
# while now we expected the dummy_data.zip file to be a directory containing
# the downloaded file.
return path_to_dummy_data
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self , _A):
def _iter_archive_members(_A):
# this preserves the order of the members inside the ZIP archive
SCREAMING_SNAKE_CASE_ = Path(self.dummy_file).parent
SCREAMING_SNAKE_CASE_ = path.relative_to(_A)
with ZipFile(self.local_path_to_dummy_data) as zip_file:
SCREAMING_SNAKE_CASE_ = zip_file.namelist()
for member in members:
if member.startswith(relative_path.as_posix()):
yield dummy_parent_path.joinpath(_A)
SCREAMING_SNAKE_CASE_ = Path(_A)
SCREAMING_SNAKE_CASE_ = _iter_archive_members(_A) if self.use_local_dummy_data else path.rglob('*')
for file_path in file_paths:
if file_path.is_file() and not file_path.name.startswith(('.', '__')):
yield file_path.relative_to(_A).as_posix(), file_path.open('rb')
def lowerCAmelCase__ ( self , _A):
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [paths]
for path in paths:
if os.path.isfile(_A):
if os.path.basename(_A).startswith(('.', '__')):
return
yield path
else:
for dirpath, dirnames, filenames in os.walk(_A):
if os.path.basename(_A).startswith(('.', '__')):
continue
dirnames.sort()
for filename in sorted(_A):
if filename.startswith(('.', '__')):
continue
yield os.path.join(_A , _A)
| 620 |
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
UpperCamelCase__ : int = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n"
class __snake_case ( unittest.TestCase , lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering')
self.tool.setup()
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering' , remote=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
| 620 | 1 |
UpperCamelCase__ : Tuple = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []}
UpperCamelCase__ : Optional[Any] = ["a", "b", "c", "d", "e"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = start
# add current to visited
visited.append(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
SCREAMING_SNAKE_CASE_ = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# if all neighbors visited add current to sort
sort.append(_SCREAMING_SNAKE_CASE )
# if all vertices haven't been visited select a new one to visit
if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ):
for vertice in vertices:
if vertice not in visited:
SCREAMING_SNAKE_CASE_ = topological_sort(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# return sort
return sort
if __name__ == "__main__":
UpperCamelCase__ : Dict = topological_sort("a", [], [])
print(sort)
| 620 |
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import BeitImageProcessor
class __snake_case ( unittest.TestCase ):
def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=False , ):
SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 20, 'width': 20}
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 18, 'width': 18}
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = min_resolution
SCREAMING_SNAKE_CASE_ = max_resolution
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean
SCREAMING_SNAKE_CASE_ = image_std
SCREAMING_SNAKE_CASE_ = do_reduce_labels
def lowerCAmelCase__ ( self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_reduce_labels": self.do_reduce_labels,
}
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[1]['file'] )
return image, map
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[1]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[2]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[3]['file'] )
return [imagea, imagea], [mapa, mapa]
@require_torch
@require_vision
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Union[str, Any] = BeitImageProcessor if is_vision_available() else None
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BeitImageProcessingTester(self)
@property
def lowerCAmelCase__ ( self):
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(_A , 'do_resize'))
self.assertTrue(hasattr(_A , 'size'))
self.assertTrue(hasattr(_A , 'do_center_crop'))
self.assertTrue(hasattr(_A , 'center_crop'))
self.assertTrue(hasattr(_A , 'do_normalize'))
self.assertTrue(hasattr(_A , 'image_mean'))
self.assertTrue(hasattr(_A , 'image_std'))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 20, 'width': 20})
self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18})
self.assertEqual(image_processor.do_reduce_labels , _A)
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A)
self.assertEqual(image_processor.size , {'height': 42, 'width': 42})
self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84})
self.assertEqual(image_processor.do_reduce_labels , _A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A)
for image in image_inputs:
self.assertIsInstance(_A , Image.Image)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A)
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
SCREAMING_SNAKE_CASE_ = []
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
maps.append(torch.zeros(image.shape[-2:]).long())
# Test not batched input
SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , maps[0] , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test not batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_batch_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
2,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
2,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 150)
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
| 620 | 1 |
import argparse
import gc
import json
import os
import shutil
import warnings
import torch
from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
try:
from transformers import LlamaTokenizerFast
except ImportError as e:
warnings.warn(e)
warnings.warn(
"The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
)
UpperCamelCase__ : Optional[Any] = None
UpperCamelCase__ : str = {
"7B": 11_008,
"13B": 13_824,
"30B": 17_920,
"65B": 22_016,
"70B": 28_672,
}
UpperCamelCase__ : str = {
"7B": 1,
"7Bf": 1,
"13B": 2,
"13Bf": 2,
"30B": 4,
"65B": 8,
"70B": 8,
"70Bf": 8,
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any]=1 , _SCREAMING_SNAKE_CASE : Union[str, Any]=256 ):
"""simple docstring"""
return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
with open(_SCREAMING_SNAKE_CASE , 'r' ) as f:
return json.load(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
with open(_SCREAMING_SNAKE_CASE , 'w' ) as f:
json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int]=True ):
"""simple docstring"""
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , 'tmp' )
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = read_json(os.path.join(_SCREAMING_SNAKE_CASE , 'params.json' ) )
SCREAMING_SNAKE_CASE_ = NUM_SHARDS[model_size]
SCREAMING_SNAKE_CASE_ = params['n_layers']
SCREAMING_SNAKE_CASE_ = params['n_heads']
SCREAMING_SNAKE_CASE_ = n_heads // num_shards
SCREAMING_SNAKE_CASE_ = params['dim']
SCREAMING_SNAKE_CASE_ = dim // n_heads
SCREAMING_SNAKE_CASE_ = 10000.0
SCREAMING_SNAKE_CASE_ = 1.0 / (base ** (torch.arange(0 , _SCREAMING_SNAKE_CASE , 2 ).float() / dims_per_head))
if "n_kv_heads" in params:
SCREAMING_SNAKE_CASE_ = params['n_kv_heads'] # for GQA / MQA
SCREAMING_SNAKE_CASE_ = n_heads_per_shard // num_key_value_heads
SCREAMING_SNAKE_CASE_ = dim // num_key_value_heads
else: # compatibility with other checkpoints
SCREAMING_SNAKE_CASE_ = n_heads
SCREAMING_SNAKE_CASE_ = n_heads_per_shard
SCREAMING_SNAKE_CASE_ = dim
# permute for sliced rotary
def permute(_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[str]=n_heads , _SCREAMING_SNAKE_CASE : Dict=dim , _SCREAMING_SNAKE_CASE : List[Any]=dim ):
return w.view(_SCREAMING_SNAKE_CASE , dima // n_heads // 2 , 2 , _SCREAMING_SNAKE_CASE ).transpose(1 , 2 ).reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
print(f"""Fetching all parameters from the checkpoint at {input_base_path}.""" )
# Load weights
if model_size == "7B":
# Not sharded
# (The sharded implementation would also work, but this is simpler.)
SCREAMING_SNAKE_CASE_ = torch.load(os.path.join(_SCREAMING_SNAKE_CASE , 'consolidated.00.pth' ) , map_location='cpu' )
else:
# Sharded
SCREAMING_SNAKE_CASE_ = [
torch.load(os.path.join(_SCREAMING_SNAKE_CASE , f"""consolidated.{i:02d}.pth""" ) , map_location='cpu' )
for i in range(_SCREAMING_SNAKE_CASE )
]
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = {'weight_map': {}}
for layer_i in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = f"""pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"""
if model_size == "7B":
# Unsharded
SCREAMING_SNAKE_CASE_ = {
f"""model.layers.{layer_i}.self_attn.q_proj.weight""": permute(
loaded[f"""layers.{layer_i}.attention.wq.weight"""] ),
f"""model.layers.{layer_i}.self_attn.k_proj.weight""": permute(
loaded[f"""layers.{layer_i}.attention.wk.weight"""] ),
f"""model.layers.{layer_i}.self_attn.v_proj.weight""": loaded[f"""layers.{layer_i}.attention.wv.weight"""],
f"""model.layers.{layer_i}.self_attn.o_proj.weight""": loaded[f"""layers.{layer_i}.attention.wo.weight"""],
f"""model.layers.{layer_i}.mlp.gate_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w1.weight"""],
f"""model.layers.{layer_i}.mlp.down_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w2.weight"""],
f"""model.layers.{layer_i}.mlp.up_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w3.weight"""],
f"""model.layers.{layer_i}.input_layernorm.weight""": loaded[f"""layers.{layer_i}.attention_norm.weight"""],
f"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[f"""layers.{layer_i}.ffn_norm.weight"""],
}
else:
# Sharded
# Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
# the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
# redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
SCREAMING_SNAKE_CASE_ = {
f"""model.layers.{layer_i}.input_layernorm.weight""": loaded[0][
f"""layers.{layer_i}.attention_norm.weight"""
].clone(),
f"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[0][
f"""layers.{layer_i}.ffn_norm.weight"""
].clone(),
}
SCREAMING_SNAKE_CASE_ = permute(
torch.cat(
[
loaded[i][f"""layers.{layer_i}.attention.wq.weight"""].view(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
for i in range(_SCREAMING_SNAKE_CASE )
] , dim=0 , ).reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = permute(
torch.cat(
[
loaded[i][f"""layers.{layer_i}.attention.wk.weight"""].view(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
for i in range(_SCREAMING_SNAKE_CASE )
] , dim=0 , ).reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = torch.cat(
[
loaded[i][f"""layers.{layer_i}.attention.wv.weight"""].view(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
for i in range(_SCREAMING_SNAKE_CASE )
] , dim=0 , ).reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = torch.cat(
[loaded[i][f"""layers.{layer_i}.attention.wo.weight"""] for i in range(_SCREAMING_SNAKE_CASE )] , dim=1 )
SCREAMING_SNAKE_CASE_ = torch.cat(
[loaded[i][f"""layers.{layer_i}.feed_forward.w1.weight"""] for i in range(_SCREAMING_SNAKE_CASE )] , dim=0 )
SCREAMING_SNAKE_CASE_ = torch.cat(
[loaded[i][f"""layers.{layer_i}.feed_forward.w2.weight"""] for i in range(_SCREAMING_SNAKE_CASE )] , dim=1 )
SCREAMING_SNAKE_CASE_ = torch.cat(
[loaded[i][f"""layers.{layer_i}.feed_forward.w3.weight"""] for i in range(_SCREAMING_SNAKE_CASE )] , dim=0 )
SCREAMING_SNAKE_CASE_ = inv_freq
for k, v in state_dict.items():
SCREAMING_SNAKE_CASE_ = filename
param_count += v.numel()
torch.save(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = f"""pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"""
if model_size == "7B":
# Unsharded
SCREAMING_SNAKE_CASE_ = {
'model.embed_tokens.weight': loaded['tok_embeddings.weight'],
'model.norm.weight': loaded['norm.weight'],
'lm_head.weight': loaded['output.weight'],
}
else:
SCREAMING_SNAKE_CASE_ = {
'model.norm.weight': loaded[0]['norm.weight'],
'model.embed_tokens.weight': torch.cat(
[loaded[i]['tok_embeddings.weight'] for i in range(_SCREAMING_SNAKE_CASE )] , dim=1 ),
'lm_head.weight': torch.cat([loaded[i]['output.weight'] for i in range(_SCREAMING_SNAKE_CASE )] , dim=0 ),
}
for k, v in state_dict.items():
SCREAMING_SNAKE_CASE_ = filename
param_count += v.numel()
torch.save(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
# Write configs
SCREAMING_SNAKE_CASE_ = {'total_size': param_count * 2}
write_json(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , 'pytorch_model.bin.index.json' ) )
SCREAMING_SNAKE_CASE_ = params['ffn_dim_multiplier'] if 'ffn_dim_multiplier' in params else 1
SCREAMING_SNAKE_CASE_ = params['multiple_of'] if 'multiple_of' in params else 256
SCREAMING_SNAKE_CASE_ = LlamaConfig(
hidden_size=_SCREAMING_SNAKE_CASE , intermediate_size=compute_intermediate_size(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , num_attention_heads=params['n_heads'] , num_hidden_layers=params['n_layers'] , rms_norm_eps=params['norm_eps'] , num_key_value_heads=_SCREAMING_SNAKE_CASE , )
config.save_pretrained(_SCREAMING_SNAKE_CASE )
# Make space so we can load the model properly now.
del state_dict
del loaded
gc.collect()
print('Loading the checkpoint in a Llama model.' )
SCREAMING_SNAKE_CASE_ = LlamaForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , low_cpu_mem_usage=_SCREAMING_SNAKE_CASE )
# Avoid saving this as part of the config.
del model.config._name_or_path
print('Saving in the Transformers format.' )
model.save_pretrained(_SCREAMING_SNAKE_CASE , safe_serialization=_SCREAMING_SNAKE_CASE )
shutil.rmtree(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
print(f"""Saving a {tokenizer_class.__name__} to {tokenizer_path}.""" )
SCREAMING_SNAKE_CASE_ = tokenizer_class(_SCREAMING_SNAKE_CASE )
tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
parser.add_argument(
'--input_dir' , help='Location of LLaMA weights, which contains tokenizer.model and model folders' , )
parser.add_argument(
'--model_size' , choices=['7B', '7Bf', '13B', '13Bf', '30B', '65B', '70B', '70Bf', 'tokenizer_only'] , )
parser.add_argument(
'--output_dir' , help='Location to write HF model and tokenizer' , )
parser.add_argument('--safe_serialization' , type=_SCREAMING_SNAKE_CASE , help='Whether or not to save using `safetensors`.' )
SCREAMING_SNAKE_CASE_ = parser.parse_args()
if args.model_size != "tokenizer_only":
write_model(
model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , )
SCREAMING_SNAKE_CASE_ = os.path.join(args.input_dir , 'tokenizer.model' )
write_tokenizer(args.output_dir , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 200 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [1, 2, 5, 10, 20, 50, 100, 200]
SCREAMING_SNAKE_CASE_ = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(_SCREAMING_SNAKE_CASE , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73_682
| 620 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCamelCase__ : str = {
"configuration_groupvit": [
"GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"GroupViTConfig",
"GroupViTOnnxConfig",
"GroupViTTextConfig",
"GroupViTVisionConfig",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
"GroupViTModel",
"GroupViTPreTrainedModel",
"GroupViTTextModel",
"GroupViTVisionModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[Any] = [
"TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFGroupViTModel",
"TFGroupViTPreTrainedModel",
"TFGroupViTTextModel",
"TFGroupViTVisionModel",
]
if TYPE_CHECKING:
from .configuration_groupvit import (
GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
GroupViTConfig,
GroupViTOnnxConfig,
GroupViTTextConfig,
GroupViTVisionConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_groupvit import (
GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GroupViTModel,
GroupViTPreTrainedModel,
GroupViTTextModel,
GroupViTVisionModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_groupvit import (
TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFGroupViTModel,
TFGroupViTPreTrainedModel,
TFGroupViTTextModel,
TFGroupViTVisionModel,
)
else:
import sys
UpperCamelCase__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if index == number_of_items:
return 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 )
if weights[index] <= max_weight:
SCREAMING_SNAKE_CASE_ = values[index] + knapsack(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 )
return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 | 1 |
import gc
import unittest
from transformers import CTRLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
)
class __snake_case :
def __init__( self , _A , _A=14 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = seq_length
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_token_type_ids
SCREAMING_SNAKE_CASE_ = use_input_mask
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = use_mc_token_ids
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = type_sequence_label_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = num_labels
SCREAMING_SNAKE_CASE_ = num_choices
SCREAMING_SNAKE_CASE_ = scope
SCREAMING_SNAKE_CASE_ = self.vocab_size - 1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE_ = random_attention_mask([self.batch_size, self.seq_length])
SCREAMING_SNAKE_CASE_ = None
if self.use_token_type_ids:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_mc_token_ids:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.num_choices] , self.seq_length)
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.type_sequence_label_size)
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.num_choices)
SCREAMING_SNAKE_CASE_ = self.get_config()
SCREAMING_SNAKE_CASE_ = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2)
return (
config,
input_ids,
input_mask,
head_mask,
token_type_ids,
mc_token_ids,
sequence_labels,
token_labels,
choice_labels,
)
def lowerCAmelCase__ ( self):
return CTRLConfig(
vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , )
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , *_A):
SCREAMING_SNAKE_CASE_ = CTRLModel(config=_A)
model.to(_A)
model.eval()
model(_A , token_type_ids=_A , head_mask=_A)
model(_A , token_type_ids=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(len(result.past_key_values) , config.n_layer)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , *_A):
SCREAMING_SNAKE_CASE_ = CTRLLMHeadModel(_A)
model.to(_A)
model.eval()
SCREAMING_SNAKE_CASE_ = model(_A , token_type_ids=_A , labels=_A)
self.parent.assertEqual(result.loss.shape , ())
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask}
return config, inputs_dict
def lowerCAmelCase__ ( self , _A , _A , _A , _A , *_A):
SCREAMING_SNAKE_CASE_ = self.num_labels
SCREAMING_SNAKE_CASE_ = CTRLForSequenceClassification(_A)
model.to(_A)
model.eval()
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.type_sequence_label_size)
SCREAMING_SNAKE_CASE_ = model(_A , token_type_ids=_A , labels=_A)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
@require_torch
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Dict = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
__lowerCAmelCase : Dict = (CTRLLMHeadModel,) if is_torch_available() else ()
__lowerCAmelCase : Any = (
{
'feature-extraction': CTRLModel,
'text-classification': CTRLForSequenceClassification,
'text-generation': CTRLLMHeadModel,
'zero-shot': CTRLForSequenceClassification,
}
if is_torch_available()
else {}
)
__lowerCAmelCase : Tuple = True
__lowerCAmelCase : Dict = False
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
# config could not be created.
return True
return False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = CTRLModelTester(self)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A , n_embd=37)
def lowerCAmelCase__ ( self):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_ctrl_model(*_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_lm_head_model(*_A)
@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
def lowerCAmelCase__ ( self):
pass
@slow
def lowerCAmelCase__ ( self):
for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE_ = CTRLModel.from_pretrained(_A)
self.assertIsNotNone(_A)
@unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :)
def lowerCAmelCase__ ( self):
pass
@require_torch
class __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
super().tearDown()
# clean-up as much as possible GPU memory occupied by PyTorch
gc.collect()
torch.cuda.empty_cache()
@slow
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = CTRLLMHeadModel.from_pretrained('ctrl')
model.to(_A)
SCREAMING_SNAKE_CASE_ = torch.tensor(
[[11859, 0, 1611, 8]] , dtype=torch.long , device=_A) # Legal the president is
SCREAMING_SNAKE_CASE_ = [
11859,
0,
1611,
8,
5,
150,
26449,
2,
19,
348,
469,
3,
2595,
48,
20740,
246533,
246533,
19,
30,
5,
] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a
SCREAMING_SNAKE_CASE_ = model.generate(_A , do_sample=_A)
self.assertListEqual(output_ids[0].tolist() , _A)
| 620 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase__ : List[Any] = torch.device("cpu")
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = dct.pop(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = val
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for k in state_dict.keys():
SCREAMING_SNAKE_CASE_ = k
if ".pwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.pwconv' , '.point_wise_conv' )
if ".dwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.dwconv' , '.depth_wise_conv' )
if ".Proj." in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.Proj.' , '.proj.' )
if "patch_embed" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' )
if "network" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.split('.' )
if ls[2].isdigit():
SCREAMING_SNAKE_CASE_ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] )
else:
SCREAMING_SNAKE_CASE_ = k_new.replace('network' , 'swiftformer.encoder.network' )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
SCREAMING_SNAKE_CASE_ = 1_000
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json'
SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
SCREAMING_SNAKE_CASE_ = [3, 3, 6, 4]
SCREAMING_SNAKE_CASE_ = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
SCREAMING_SNAKE_CASE_ = [3, 3, 9, 6]
SCREAMING_SNAKE_CASE_ = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
SCREAMING_SNAKE_CASE_ = [4, 3, 10, 5]
SCREAMING_SNAKE_CASE_ = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
SCREAMING_SNAKE_CASE_ = [4, 4, 12, 6]
SCREAMING_SNAKE_CASE_ = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith('https' ):
SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
SCREAMING_SNAKE_CASE_ = checkpoint
SCREAMING_SNAKE_CASE_ = create_rename_keys(_SCREAMING_SNAKE_CASE )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
SCREAMING_SNAKE_CASE_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval()
hf_model.load_state_dict(_SCREAMING_SNAKE_CASE )
# prepare test inputs
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = ViTImageProcessor.from_pretrained('preprocessor_config' )
SCREAMING_SNAKE_CASE_ = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
# compare outputs from both models
SCREAMING_SNAKE_CASE_ = get_expected_output(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = hf_model(inputs['pixel_values'] ).logits
assert hf_logits.shape == torch.Size([1, 1_000] )
assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1E-3 )
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--swiftformer_name",
default="swiftformer_xs",
choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"],
type=str,
help="Name of the SwiftFormer model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="./converted_outputs/",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.")
UpperCamelCase__ : Union[str, Any] = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 620 | 1 |
import unittest
from dataclasses import dataclass
import pytest
from accelerate.commands.config.config_args import SageMakerConfig
from accelerate.utils import ComputeEnvironment
from accelerate.utils.launch import _convert_nargs_to_dict
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Tuple = ComputeEnvironment.AMAZON_SAGEMAKER
__lowerCAmelCase : Optional[Any] = True
__lowerCAmelCase : Union[str, Any] = 'ml.p3.2xlarge'
__lowerCAmelCase : Any = 'accelerate_sagemaker_execution_role'
__lowerCAmelCase : Union[str, Any] = 'hf-sm'
__lowerCAmelCase : List[str] = 'us-east-1'
__lowerCAmelCase : List[str] = 1
__lowerCAmelCase : int = 'accelerate-sagemaker-1'
__lowerCAmelCase : Union[str, Any] = '1.6'
__lowerCAmelCase : int = '4.4'
__lowerCAmelCase : Tuple = 'train.py'
__lowerCAmelCase : Tuple = [
'--model_name_or_path',
'bert',
'--do_train',
'False',
'--epochs',
'3',
'--learning_rate',
'5e-5',
'--max_steps',
'50.5',
]
__lowerCAmelCase : Dict = [
'--model_name_or_path',
'bert',
'--do_train',
'--do_test',
'False',
'--do_predict',
'--epochs',
'3',
'--learning_rate',
'5e-5',
'--max_steps',
'50.5',
]
class __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
# If no defaults are changed, `to_kwargs` returns an empty dict.
SCREAMING_SNAKE_CASE_ = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args)
assert isinstance(converted_args['model_name_or_path'] , _A)
assert isinstance(converted_args['do_train'] , _A)
assert isinstance(converted_args['epochs'] , _A)
assert isinstance(converted_args['learning_rate'] , _A)
assert isinstance(converted_args['max_steps'] , _A)
with pytest.raises(_A):
_convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args)
| 620 |
def _UpperCAmelCase ( ):
"""simple docstring"""
for n in range(1 , 1_000_000 ):
yield n * (n + 1) // 2
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 2
while i * i <= n:
SCREAMING_SNAKE_CASE_ = 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 _UpperCAmelCase ( ):
"""simple docstring"""
return next(i for i in triangle_number_generator() if count_divisors(_SCREAMING_SNAKE_CASE ) > 500 )
if __name__ == "__main__":
print(solution())
| 620 | 1 |
from __future__ import annotations
import random
import unittest
from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLModel,
)
class __snake_case :
def __init__( self , _A , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = 13
SCREAMING_SNAKE_CASE_ = 7
SCREAMING_SNAKE_CASE_ = 30
SCREAMING_SNAKE_CASE_ = self.seq_length + self.mem_len
SCREAMING_SNAKE_CASE_ = 15
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = 99
SCREAMING_SNAKE_CASE_ = [10, 50, 80]
SCREAMING_SNAKE_CASE_ = 32
SCREAMING_SNAKE_CASE_ = 32
SCREAMING_SNAKE_CASE_ = 4
SCREAMING_SNAKE_CASE_ = 8
SCREAMING_SNAKE_CASE_ = 128
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 3
SCREAMING_SNAKE_CASE_ = self.vocab_size - 1
SCREAMING_SNAKE_CASE_ = 0.0_1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = TransfoXLConfig(
vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , )
return (config, input_ids_a, input_ids_a, lm_labels)
def lowerCAmelCase__ ( self):
random.seed(self.seed)
tf.random.set_seed(self.seed)
def lowerCAmelCase__ ( self , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = TFTransfoXLModel(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model(_A).to_tuple()
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids_a, 'mems': mems_a}
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model(_A).to_tuple()
self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
def lowerCAmelCase__ ( self , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = TFTransfoXLLMHeadModel(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model(_A).to_tuple()
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids_a, 'labels': lm_labels}
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model(_A).to_tuple()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model([input_ids_a, mems_a]).to_tuple()
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels}
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model(_A).to_tuple()
self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
def lowerCAmelCase__ ( self , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = TFTransfoXLForSequenceClassification(_A)
SCREAMING_SNAKE_CASE_ = model(_A)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids_a}
return config, inputs_dict
@require_tf
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : List[str] = (
(TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
)
__lowerCAmelCase : List[str] = () if is_tf_available() else ()
__lowerCAmelCase : List[Any] = (
{
'feature-extraction': TFTransfoXLModel,
'text-classification': TFTransfoXLForSequenceClassification,
'text-generation': TFTransfoXLLMHeadModel,
'zero-shot': TFTransfoXLForSequenceClassification,
}
if is_tf_available()
else {}
)
# TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
__lowerCAmelCase : List[Any] = False
__lowerCAmelCase : List[str] = False
__lowerCAmelCase : Optional[int] = False
__lowerCAmelCase : Dict = False
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
if pipeline_test_casse_name == "TextGenerationPipelineTests":
# Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
# `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
# tokenizer.
return True
return False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TFTransfoXLModelTester(self)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A , d_embed=37)
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
self.model_tester.set_seed()
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_model(*_A)
def lowerCAmelCase__ ( self):
self.model_tester.set_seed()
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_lm_head(*_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE_ = [TFTransfoXLForSequenceClassification]
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE_ = model_class(_A)
assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer)
if model_class in list_other_models_with_output_ebd:
SCREAMING_SNAKE_CASE_ = model.get_output_embeddings()
assert isinstance(_A , tf.keras.layers.Layer)
SCREAMING_SNAKE_CASE_ = model.get_bias()
assert name is None
else:
SCREAMING_SNAKE_CASE_ = model.get_output_embeddings()
assert x is None
SCREAMING_SNAKE_CASE_ = model.get_bias()
assert name is None
def lowerCAmelCase__ ( self):
# TODO JP: Make TransfoXL XLA compliant
pass
@slow
def lowerCAmelCase__ ( self):
for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE_ = TFTransfoXLModel.from_pretrained(_A)
self.assertIsNotNone(_A)
@unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.')
def lowerCAmelCase__ ( self):
pass
@require_tf
class __snake_case ( unittest.TestCase ):
@unittest.skip('Skip test until #12651 is resolved.')
@slow
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103')
# fmt: off
SCREAMING_SNAKE_CASE_ = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,11739,4762,358,5,25,245,22,1706,17,20098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,6224,831,16002,2,8,603,78967,29546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,29546,54,8,3609,5,57211,49,4,1,277,18,8,1755,15691,3,341,25,416,693,42573,71,17,401,94,31,17919,2,29546,7873,18,1,435,23,11011,755,5,5167,3,7983,98,84,2,29546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,29546,824,1400,1868,2,19,160,2,311,8,5496,2,20920,17,25,15097,3,24,24,0]] , dtype=tf.intaa) # noqa: E231
# fmt: on
# In 1991 , the remains of Russian Tsar Nicholas II and his family
# ( except for Alexei and Maria ) are discovered .
# The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
# remainder of the story . 1883 Western Siberia ,
# a young Grigori Rasputin is asked by his father and a group of men to perform magic .
# Rasputin has a vision and denounces one of the men as a horse thief . Although his
# father initially slaps him for making such an accusation , Rasputin watches as the
# man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
# the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
# with people , even a bishop , begging for his blessing . <eod> </s> <eos>
# fmt: off
SCREAMING_SNAKE_CASE_ = [33,1297,2,1,1009,4,1109,11739,4762,358,5,25,245,22,1706,17,20098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,6224,831,16002,2,8,603,78967,29546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,29546,54,8,3609,5,57211,49,4,1,277,18,8,1755,15691,3,341,25,416,693,42573,71,17,401,94,31,17919,2,29546,7873,18,1,435,23,11011,755,5,5167,3,7983,98,84,2,29546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,29546,824,1400,1868,2,19,160,2,311,8,5496,2,20920,17,25,15097,3,24,24,0,33,1,1857,2,1,1009,4,1109,11739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,0] # noqa: E231
# fmt: on
# In 1991, the remains of Russian Tsar Nicholas II and his family (
# except for Alexei and Maria ) are discovered. The voice of young son,
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
# 1883 Western Siberia, a young Grigori Rasputin is asked by his father
# and a group of men to perform magic. Rasputin has a vision and
# denounces one of the men as a horse thief. Although his father initially
# slaps him for making such an accusation, Rasputin watches as the man
# is chased outside and beaten. Twenty years later, Rasputin sees a vision
# of the Virgin Mary, prompting him to become a priest.
# Rasputin quickly becomes famous, with people, even a bishop, begging for
# his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
# Nicholas II and his family were discovered. The voice of <unk> young son,
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>
SCREAMING_SNAKE_CASE_ = model.generate(_A , max_length=200 , do_sample=_A)
self.assertListEqual(output_ids[0].numpy().tolist() , _A)
| 620 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
UpperCamelCase__ : Optional[int] = datasets.utils.logging.get_logger(__name__)
@dataclass
class __snake_case ( datasets.BuilderConfig ):
__lowerCAmelCase : Optional[datasets.Features] = None
__lowerCAmelCase : str = "utf-8"
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : bool = True # deprecated
__lowerCAmelCase : Optional[int] = None # deprecated
__lowerCAmelCase : int = 10 << 20 # 10MB
__lowerCAmelCase : Optional[bool] = None
class __snake_case ( datasets.ArrowBasedBuilder ):
__lowerCAmelCase : int = JsonConfig
def lowerCAmelCase__ ( self):
if self.config.block_size is not None:
logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead')
SCREAMING_SNAKE_CASE_ = self.config.block_size
if self.config.use_threads is not True:
logger.warning(
'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.')
if self.config.newlines_in_values is not None:
raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported')
return datasets.DatasetInfo(features=self.config.features)
def lowerCAmelCase__ ( self , _A):
if not self.config.data_files:
raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
SCREAMING_SNAKE_CASE_ = dl_manager.download_and_extract(self.config.data_files)
if isinstance(_A , (str, list, tuple)):
SCREAMING_SNAKE_CASE_ = data_files
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files})]
SCREAMING_SNAKE_CASE_ = []
for split_name, files in data_files.items():
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'files': files}))
return splits
def lowerCAmelCase__ ( self , _A):
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features) - set(pa_table.column_names):
SCREAMING_SNAKE_CASE_ = self.config.features.arrow_schema.field(_A).type
SCREAMING_SNAKE_CASE_ = pa_table.append_column(_A , pa.array([None] * len(_A) , type=_A))
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
SCREAMING_SNAKE_CASE_ = table_cast(_A , self.config.features.arrow_schema)
return pa_table
def lowerCAmelCase__ ( self , _A):
for file_idx, file in enumerate(itertools.chain.from_iterable(_A)):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
# We keep only the field we are interested in
SCREAMING_SNAKE_CASE_ = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(_A , (list, tuple)):
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
else:
SCREAMING_SNAKE_CASE_ = dataset
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
yield file_idx, self._cast_table(_A)
# If the file has one json object per line
else:
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = 0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
SCREAMING_SNAKE_CASE_ = max(self.config.chunksize // 32 , 16 << 10)
SCREAMING_SNAKE_CASE_ = (
self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
)
while True:
SCREAMING_SNAKE_CASE_ = f.read(self.config.chunksize)
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(_A)
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
SCREAMING_SNAKE_CASE_ = batch.decode(self.config.encoding , errors=_A).encode('utf-8')
try:
while True:
try:
SCREAMING_SNAKE_CASE_ = paj.read_json(
io.BytesIO(_A) , read_options=paj.ReadOptions(block_size=_A))
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(_A , pa.ArrowInvalid)
and "straddling" not in str(_A)
or block_size > len(_A)
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
f"""Batch of {len(_A)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""")
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
except json.JSONDecodeError:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(_A , _A): # list is the only sequence type supported in JSON
try:
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(f"""Not able to read records in the JSON file at {file}.""") from None
yield file_idx, self._cast_table(_A)
break
else:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(
f"""Not able to read records in the JSON file at {file}. """
f"""You should probably indicate the field of the JSON file containing your records. """
f"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """
f"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_A)
batch_idx += 1
| 620 | 1 |
import re
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = re.compile(r'^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$' )
if match := re.search(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
return match.string == phone
return False
if __name__ == "__main__":
print(indian_phone_validator("+918827897895"))
| 620 |
import unittest
from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM
@require_torch
class __snake_case :
def __init__( self , _A , _A=99 , _A=13 , _A=16 , _A=7 , _A=True , _A=True , _A=True , _A=False , _A=True , _A=2 , _A=32 , _A=4 , _A=4 , _A=30 , _A=0 , _A=1 , _A=2 , _A=None , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE_ = self.decoder_seq_length
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_attention_mask
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_ffn_dim
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = eos_token_id
SCREAMING_SNAKE_CASE_ = bos_token_id
SCREAMING_SNAKE_CASE_ = pad_token_id
SCREAMING_SNAKE_CASE_ = decoder_start_token_id
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = decoder_seq_length
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_attention_mask:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2)
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = TrOCRConfig(
vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , )
return (config, input_ids, attention_mask, lm_labels)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , ):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = TrOCRDecoder(config=_A).to(_A).eval()
SCREAMING_SNAKE_CASE_ = input_ids[:2]
input_ids[input_ids == 0] += 1
# first forward pass
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
self.parent.assertTrue(len(_A) == len(_A))
self.parent.assertTrue(len(_A) == len(_A) + 1)
SCREAMING_SNAKE_CASE_ = outputs['past_key_values']
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE_ = ids_tensor((2, 1) , config.vocab_size - 1) + 1
# append to next input_ids and
SCREAMING_SNAKE_CASE_ = torch.cat([input_ids, next_tokens] , dim=-1)
SCREAMING_SNAKE_CASE_ = model(_A)['last_hidden_state']
SCREAMING_SNAKE_CASE_ = model(_A , past_key_values=_A)['last_hidden_state']
# select random slice
SCREAMING_SNAKE_CASE_ = ids_tensor((1,) , output_from_past.shape[-1]).item()
SCREAMING_SNAKE_CASE_ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE_ = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(_A , _A , atol=1E-3)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
@require_torch
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Tuple = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
__lowerCAmelCase : Union[str, Any] = (TrOCRForCausalLM,) if is_torch_available() else ()
__lowerCAmelCase : str = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
__lowerCAmelCase : Any = True
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TrOCRStandaloneDecoderModelTester(self , is_training=_A)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*_A)
def lowerCAmelCase__ ( self):
return
@unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :)
def lowerCAmelCase__ ( self):
pass
| 620 | 1 |
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast
@require_vision
class __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE_ = BlipImageProcessor()
SCREAMING_SNAKE_CASE_ = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model')
SCREAMING_SNAKE_CASE_ = BlipaProcessor(_A , _A)
processor.save_pretrained(self.tmpdirname)
def lowerCAmelCase__ ( self , **_A):
return AutoProcessor.from_pretrained(self.tmpdirname , **_A).tokenizer
def lowerCAmelCase__ ( self , **_A):
return AutoProcessor.from_pretrained(self.tmpdirname , **_A).image_processor
def lowerCAmelCase__ ( self):
shutil.rmtree(self.tmpdirname)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta)]
SCREAMING_SNAKE_CASE_ = [Image.fromarray(np.moveaxis(_A , 0 , -1)) for x in image_inputs]
return image_inputs
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor())
processor.save_pretrained(self.tmpdirname)
SCREAMING_SNAKE_CASE_ = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)')
SCREAMING_SNAKE_CASE_ = self.get_image_processor(do_normalize=_A , padding_value=1.0)
SCREAMING_SNAKE_CASE_ = BlipaProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A , padding_value=1.0)
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab())
self.assertIsInstance(processor.tokenizer , _A)
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string())
self.assertIsInstance(processor.image_processor , _A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_image_processor()
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = BlipaProcessor(tokenizer=_A , image_processor=_A)
SCREAMING_SNAKE_CASE_ = self.prepare_image_inputs()
SCREAMING_SNAKE_CASE_ = image_processor(_A , return_tensors='np')
SCREAMING_SNAKE_CASE_ = processor(images=_A , return_tensors='np')
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_image_processor()
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = BlipaProcessor(tokenizer=_A , image_processor=_A)
SCREAMING_SNAKE_CASE_ = 'lower newer'
SCREAMING_SNAKE_CASE_ = processor(text=_A)
SCREAMING_SNAKE_CASE_ = tokenizer(_A , return_token_type_ids=_A)
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_image_processor()
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = BlipaProcessor(tokenizer=_A , image_processor=_A)
SCREAMING_SNAKE_CASE_ = 'lower newer'
SCREAMING_SNAKE_CASE_ = self.prepare_image_inputs()
SCREAMING_SNAKE_CASE_ = processor(text=_A , images=_A)
self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'input_ids', 'attention_mask'])
# test if it raises when no input is passed
with pytest.raises(_A):
processor()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_image_processor()
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = BlipaProcessor(tokenizer=_A , image_processor=_A)
SCREAMING_SNAKE_CASE_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
SCREAMING_SNAKE_CASE_ = processor.batch_decode(_A)
SCREAMING_SNAKE_CASE_ = tokenizer.batch_decode(_A)
self.assertListEqual(_A , _A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_image_processor()
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = BlipaProcessor(tokenizer=_A , image_processor=_A)
SCREAMING_SNAKE_CASE_ = 'lower newer'
SCREAMING_SNAKE_CASE_ = self.prepare_image_inputs()
SCREAMING_SNAKE_CASE_ = processor(text=_A , images=_A)
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'input_ids', 'attention_mask'])
| 620 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : torch.FloatTensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ):
super().__init__()
# pass init params to Encoder
SCREAMING_SNAKE_CASE_ = Encoder(
in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , )
SCREAMING_SNAKE_CASE_ = vq_embed_dim if vq_embed_dim is not None else latent_channels
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
SCREAMING_SNAKE_CASE_ = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A)
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
# pass init params to Decoder
SCREAMING_SNAKE_CASE_ = Decoder(
in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , )
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = self.encoder(_A)
SCREAMING_SNAKE_CASE_ = self.quant_conv(_A)
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_A)
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = False , _A = True):
# also go through quantization layer
if not force_not_quantize:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.quantize(_A)
else:
SCREAMING_SNAKE_CASE_ = h
SCREAMING_SNAKE_CASE_ = self.post_quant_conv(_A)
SCREAMING_SNAKE_CASE_ = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None)
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = sample
SCREAMING_SNAKE_CASE_ = self.encode(_A).latents
SCREAMING_SNAKE_CASE_ = self.decode(_A).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
| 620 | 1 |
import time
from contextlib import contextmanager
from pathlib import Path
import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder
UpperCamelCase__ : str = "__DUMMY_TRANSFORMERS_USER__"
UpperCamelCase__ : int = "Dummy User"
UpperCamelCase__ : Optional[int] = "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"
UpperCamelCase__ : Dict = "https://hub-ci.huggingface.co"
UpperCamelCase__ : str = CI_HUB_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}"
UpperCamelCase__ : Optional[Any] = CI_HUB_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
UpperCamelCase__ : List[Any] = Path("~/.huggingface/hub_ci_token").expanduser()
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
monkeypatch.setattr(
'huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
monkeypatch.setattr('datasets.config.HF_ENDPOINT' , _SCREAMING_SNAKE_CASE )
monkeypatch.setattr('datasets.config.HUB_DATASETS_URL' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
monkeypatch.setattr('huggingface_hub.hf_api.HfFolder.path_token' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
HfFolder.save_token(_SCREAMING_SNAKE_CASE )
yield
HfFolder.delete_token()
@pytest.fixture(scope='session' )
def _UpperCAmelCase ( ):
"""simple docstring"""
return HfApi(endpoint=_SCREAMING_SNAKE_CASE )
@pytest.fixture(scope='session' )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : HfApi ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = HfFolder.get_token()
HfFolder.save_token(_SCREAMING_SNAKE_CASE )
yield CI_HUB_USER_TOKEN
if previous_token is not None:
HfFolder.save_token(_SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
def _cleanup_repo(_SCREAMING_SNAKE_CASE : int ):
hf_api.delete_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' )
return _cleanup_repo
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
@contextmanager
def _temporary_repo(_SCREAMING_SNAKE_CASE : Tuple ):
try:
yield repo_id
finally:
cleanup_repo(_SCREAMING_SNAKE_CASE )
return _temporary_repo
@pytest.fixture(scope='session' )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : HfApi , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = f"""repo_txt_data-{int(time.time() * 1_0E3 )}"""
SCREAMING_SNAKE_CASE_ = f"""{CI_HUB_USER}/{repo_name}"""
hf_api.create_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' , private=_SCREAMING_SNAKE_CASE )
hf_api.upload_file(
token=_SCREAMING_SNAKE_CASE , path_or_fileobj=str(_SCREAMING_SNAKE_CASE ) , path_in_repo='data/text_data.txt' , repo_id=_SCREAMING_SNAKE_CASE , repo_type='dataset' , )
yield repo_id
try:
hf_api.delete_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
return hf_private_dataset_repo_txt_data_
@pytest.fixture(scope='session' )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : HfApi , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = f"""repo_zipped_txt_data-{int(time.time() * 1_0E3 )}"""
SCREAMING_SNAKE_CASE_ = f"""{CI_HUB_USER}/{repo_name}"""
hf_api.create_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' , private=_SCREAMING_SNAKE_CASE )
hf_api.upload_file(
token=_SCREAMING_SNAKE_CASE , path_or_fileobj=str(_SCREAMING_SNAKE_CASE ) , path_in_repo='data.zip' , repo_id=_SCREAMING_SNAKE_CASE , repo_type='dataset' , )
yield repo_id
try:
hf_api.delete_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
return hf_private_dataset_repo_zipped_txt_data_
@pytest.fixture(scope='session' )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : HfApi , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = f"""repo_zipped_img_data-{int(time.time() * 1_0E3 )}"""
SCREAMING_SNAKE_CASE_ = f"""{CI_HUB_USER}/{repo_name}"""
hf_api.create_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' , private=_SCREAMING_SNAKE_CASE )
hf_api.upload_file(
token=_SCREAMING_SNAKE_CASE , path_or_fileobj=str(_SCREAMING_SNAKE_CASE ) , path_in_repo='data.zip' , repo_id=_SCREAMING_SNAKE_CASE , repo_type='dataset' , )
yield repo_id
try:
hf_api.delete_repo(_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE , repo_type='dataset' )
except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error
pass
@pytest.fixture()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
return hf_private_dataset_repo_zipped_img_data_
| 620 |
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
UpperCamelCase__ : Optional[int] = logging.getLogger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : torch.nn.Module , _SCREAMING_SNAKE_CASE : BnbQuantizationConfig , _SCREAMING_SNAKE_CASE : Union[str, os.PathLike] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[str, Union[int, str, torch.device]]] = None , _SCREAMING_SNAKE_CASE : Optional[List[str]] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[Union[int, str], Union[int, str]]] = None , _SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , _SCREAMING_SNAKE_CASE : bool = False , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.load_in_abit
SCREAMING_SNAKE_CASE_ = 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.' )
SCREAMING_SNAKE_CASE_ = []
# custom device map
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1:
SCREAMING_SNAKE_CASE_ = [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:
SCREAMING_SNAKE_CASE_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE )
# compatibility with peft
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = get_parameter_device(_SCREAMING_SNAKE_CASE )
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.' )
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
# convert param to the right dtype
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = name.replace('.weight' , '' ).replace('.bias' , '' )
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ):
param.to(_SCREAMING_SNAKE_CASE )
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():
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = get_quantized_model_device_map(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] )
load_checkpoint_in_model(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
SCREAMING_SNAKE_CASE_ = {'': 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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
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\'.' )
SCREAMING_SNAKE_CASE_ = {}
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 )
} )
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = special_dtypes
SCREAMING_SNAKE_CASE_ = no_split_module_classes
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
SCREAMING_SNAKE_CASE_ = get_balanced_memory(
_SCREAMING_SNAKE_CASE , low_zero=(device_map == 'balanced_low_0') , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = max_memory
SCREAMING_SNAKE_CASE_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
# check if don't have any quantized module on the cpu
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
SCREAMING_SNAKE_CASE_ = {
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if modules_to_not_convert is None:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : str=None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = False
for name, module in model.named_children():
if current_key_name is None:
SCREAMING_SNAKE_CASE_ = []
current_key_name.append(_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
SCREAMING_SNAKE_CASE_ = '.'.join(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = 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' )
SCREAMING_SNAKE_CASE_ = module.weight.data
if module.bias is not None:
SCREAMING_SNAKE_CASE_ = module.bias.data
bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE )
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = True
if len(list(module.children() ) ) > 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
with init_empty_weights():
SCREAMING_SNAKE_CASE_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
SCREAMING_SNAKE_CASE_ = find_tied_parameters(_SCREAMING_SNAKE_CASE )
# For compatibility with Accelerate < 0.18
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
SCREAMING_SNAKE_CASE_ = sum(_SCREAMING_SNAKE_CASE , [] )
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE ) > 0
# Check if it is a base model
SCREAMING_SNAKE_CASE_ = False
if hasattr(_SCREAMING_SNAKE_CASE , 'base_model_prefix' ):
SCREAMING_SNAKE_CASE_ = not hasattr(_SCREAMING_SNAKE_CASE , 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
SCREAMING_SNAKE_CASE_ = list(model.named_children() )
SCREAMING_SNAKE_CASE_ = [list_modules[-1][0]]
# add last module together with tied weights
SCREAMING_SNAKE_CASE_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE )
# remove ".weight" from the keys
SCREAMING_SNAKE_CASE_ = ['.weight', '.bias']
SCREAMING_SNAKE_CASE_ = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
SCREAMING_SNAKE_CASE_ = name.replace(_SCREAMING_SNAKE_CASE , '' )
filtered_module_names.append(_SCREAMING_SNAKE_CASE )
return filtered_module_names
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for m in model.modules():
if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ):
return True
return False
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : nn.Module ):
"""simple docstring"""
return next(parameter.parameters() ).device
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = param_name
SCREAMING_SNAKE_CASE_ = model
if "." in tensor_name:
SCREAMING_SNAKE_CASE_ = tensor_name.split('.' )
for split in splits[:-1]:
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
SCREAMING_SNAKE_CASE_ = new_module
SCREAMING_SNAKE_CASE_ = splits[-1]
# offload weights
SCREAMING_SNAKE_CASE_ = False
offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
if hasattr(module._parameters[tensor_name] , 'SCB' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , )
else:
offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'meta' , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
| 620 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
UpperCamelCase__ : Tuple = {"configuration_swin": ["SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwinConfig", "SwinOnnxConfig"]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : List[Any] = [
"SWIN_PRETRAINED_MODEL_ARCHIVE_LIST",
"SwinForImageClassification",
"SwinForMaskedImageModeling",
"SwinModel",
"SwinPreTrainedModel",
"SwinBackbone",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : List[Any] = [
"TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFSwinForImageClassification",
"TFSwinForMaskedImageModeling",
"TFSwinModel",
"TFSwinPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swin import (
SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinBackbone,
SwinForImageClassification,
SwinForMaskedImageModeling,
SwinModel,
SwinPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_swin import (
TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSwinForImageClassification,
TFSwinForMaskedImageModeling,
TFSwinModel,
TFSwinPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 |
import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
UpperCamelCase__ : Optional[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
# See all BART models at https://huggingface.co/models?filter=bart
UpperCamelCase__ : List[str] = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
}
UpperCamelCase__ : str = {
"facebook/bart-base": 1_024,
"facebook/bart-large": 1_024,
"facebook/bart-large-mnli": 1_024,
"facebook/bart-large-cnn": 1_024,
"facebook/bart-large-xsum": 1_024,
"yjernite/bart_eli5": 1_024,
}
@lru_cache()
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (
list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) )
)
SCREAMING_SNAKE_CASE_ = bs[:]
SCREAMING_SNAKE_CASE_ = 0
for b in range(2**8 ):
if b not in bs:
bs.append(_SCREAMING_SNAKE_CASE )
cs.append(2**8 + n )
n += 1
SCREAMING_SNAKE_CASE_ = [chr(_SCREAMING_SNAKE_CASE ) for n in cs]
return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = set()
SCREAMING_SNAKE_CASE_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
SCREAMING_SNAKE_CASE_ = char
return pairs
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = VOCAB_FILES_NAMES
__lowerCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP
__lowerCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask']
def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ):
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else bos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else eos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else sep_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else cls_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else unk_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token
super().__init__(
errors=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , **_A , )
with open(_A , encoding='utf-8') as vocab_handle:
SCREAMING_SNAKE_CASE_ = json.load(_A)
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()}
SCREAMING_SNAKE_CASE_ = errors # how to handle errors in decoding
SCREAMING_SNAKE_CASE_ = bytes_to_unicode()
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.byte_encoder.items()}
with open(_A , encoding='utf-8') as merges_handle:
SCREAMING_SNAKE_CASE_ = merges_handle.read().split('\n')[1:-1]
SCREAMING_SNAKE_CASE_ = [tuple(merge.split()) for merge in bpe_merges]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
SCREAMING_SNAKE_CASE_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+')
@property
def lowerCAmelCase__ ( self):
return len(self.encoder)
def lowerCAmelCase__ ( self):
return dict(self.encoder , **self.added_tokens_encoder)
def lowerCAmelCase__ ( self , _A):
if token in self.cache:
return self.cache[token]
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
if not pairs:
return token
while True:
SCREAMING_SNAKE_CASE_ = min(_A , key=lambda _A: self.bpe_ranks.get(_A , float('inf')))
if bigram not in self.bpe_ranks:
break
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
while i < len(_A):
try:
SCREAMING_SNAKE_CASE_ = word.index(_A , _A)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
SCREAMING_SNAKE_CASE_ = j
if word[i] == first and i < len(_A) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = new_word
if len(_A) == 1:
break
else:
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
SCREAMING_SNAKE_CASE_ = ' '.join(_A)
SCREAMING_SNAKE_CASE_ = word
return word
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = []
for token in re.findall(self.pat , _A):
SCREAMING_SNAKE_CASE_ = ''.join(
self.byte_encoder[b] for b in token.encode('utf-8')) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A).split(' '))
return bpe_tokens
def lowerCAmelCase__ ( self , _A):
return self.encoder.get(_A , self.encoder.get(self.unk_token))
def lowerCAmelCase__ ( self , _A):
return self.decoder.get(_A)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = ''.join(_A)
SCREAMING_SNAKE_CASE_ = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8' , errors=self.errors)
return text
def lowerCAmelCase__ ( self , _A , _A = None):
if not os.path.isdir(_A):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""")
return
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'])
with open(_A , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A) + '\n')
SCREAMING_SNAKE_CASE_ = 0
with open(_A , 'w' , encoding='utf-8') as writer:
writer.write('#version: 0.2\n')
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A: kv[1]):
if index != token_index:
logger.warning(
f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
' Please check that the tokenizer is not corrupted!')
SCREAMING_SNAKE_CASE_ = token_index
writer.write(' '.join(_A) + '\n')
index += 1
return vocab_file, merge_file
def lowerCAmelCase__ ( self , _A , _A = None):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowerCAmelCase__ ( self , _A , _A = None , _A = False):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A)
if token_ids_a is None:
return [1] + ([0] * len(_A)) + [1]
return [1] + ([0] * len(_A)) + [1, 1] + ([0] * len(_A)) + [1]
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
def lowerCAmelCase__ ( self , _A , _A=False , **_A):
SCREAMING_SNAKE_CASE_ = kwargs.pop('add_prefix_space' , self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(_A) > 0 and not text[0].isspace()):
SCREAMING_SNAKE_CASE_ = ' ' + text
return (text, kwargs)
| 620 | 1 |
from __future__ import annotations
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list[float] ):
"""simple docstring"""
if len(_SCREAMING_SNAKE_CASE ) < 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' )
SCREAMING_SNAKE_CASE_ = nums.copy()
copy_nums.sort()
return copy_nums[-1] < sum(copy_nums[:-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Optional[int] = {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
),
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Optional[int] = 'dpr'
def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1E-12 , _A=0 , _A="absolute" , _A = 0 , **_A , ):
super().__init__(pad_token_id=_A , **_A)
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = projection_dim
SCREAMING_SNAKE_CASE_ = position_embedding_type
| 620 | 1 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : torch.FloatTensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ):
super().__init__()
# pass init params to Encoder
SCREAMING_SNAKE_CASE_ = Encoder(
in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , )
SCREAMING_SNAKE_CASE_ = vq_embed_dim if vq_embed_dim is not None else latent_channels
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
SCREAMING_SNAKE_CASE_ = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A)
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
# pass init params to Decoder
SCREAMING_SNAKE_CASE_ = Decoder(
in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , )
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = self.encoder(_A)
SCREAMING_SNAKE_CASE_ = self.quant_conv(_A)
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_A)
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = False , _A = True):
# also go through quantization layer
if not force_not_quantize:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.quantize(_A)
else:
SCREAMING_SNAKE_CASE_ = h
SCREAMING_SNAKE_CASE_ = self.post_quant_conv(_A)
SCREAMING_SNAKE_CASE_ = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None)
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = sample
SCREAMING_SNAKE_CASE_ = self.encode(_A).latents
SCREAMING_SNAKE_CASE_ = self.decode(_A).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
| 620 |
import pytest
import datasets
# Import fixture modules as plugins
UpperCamelCase__ : Union[str, Any] = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for item in items:
if any(marker in item.keywords for marker in ['integration', 'unit'] ):
continue
item.add_marker(pytest.mark.unit )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = tmp_path_factory.getbasetemp() / 'cache'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'datasets'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'metrics'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'modules'
monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads'
monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads' / 'extracted'
monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE , scope='session' )
def _UpperCAmelCase ( ):
"""simple docstring"""
datasets.disable_progress_bar()
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , _SCREAMING_SNAKE_CASE )
| 620 | 1 |
import json
import os
import unittest
from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : int = BioGptTokenizer
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
SCREAMING_SNAKE_CASE_ = [
'l',
'o',
'w',
'e',
'r',
's',
't',
'i',
'd',
'n',
'w</w>',
'r</w>',
't</w>',
'lo',
'low',
'er</w>',
'low</w>',
'lowest</w>',
'newer</w>',
'wider</w>',
'<unk>',
]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = ['l o 123', 'lo w 1456', 'e r</w> 1789', '']
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'])
with open(self.vocab_file , 'w') as fp:
fp.write(json.dumps(_A))
with open(self.merges_file , 'w') as fp:
fp.write('\n'.join(_A))
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = 'lower newer'
SCREAMING_SNAKE_CASE_ = 'lower newer'
return input_text, output_text
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BioGptTokenizer(self.vocab_file , self.merges_file)
SCREAMING_SNAKE_CASE_ = 'lower'
SCREAMING_SNAKE_CASE_ = ['low', 'er</w>']
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(_A)
self.assertListEqual(_A , _A)
SCREAMING_SNAKE_CASE_ = tokens + ['<unk>']
SCREAMING_SNAKE_CASE_ = [14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_A) , _A)
@slow
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BioGptTokenizer.from_pretrained('microsoft/biogpt')
SCREAMING_SNAKE_CASE_ = tokenizer.encode('sequence builders' , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer.encode('multi-sequence build' , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer.build_inputs_with_special_tokens(_A)
SCREAMING_SNAKE_CASE_ = tokenizer.build_inputs_with_special_tokens(_A , _A)
self.assertTrue(encoded_sentence == [2] + text)
self.assertTrue(encoded_pair == [2] + text + [2] + text_a)
| 620 |
from typing import List
import numpy as np
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {key: len(_SCREAMING_SNAKE_CASE ) for key, value in gen_kwargs.items() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
'Sharding is ambiguous for this dataset: '
+ 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
+ '\n'.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items() )
+ '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
+ 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
) )
SCREAMING_SNAKE_CASE_ = max(lists_lengths.values() , default=0 )
return max(1 , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for group_idx in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
SCREAMING_SNAKE_CASE_ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
SCREAMING_SNAKE_CASE_ = range(_SCREAMING_SNAKE_CASE , start + num_shards_to_add )
shards_indices_per_group.append(_SCREAMING_SNAKE_CASE )
return shards_indices_per_group
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = _number_of_shards_in_gen_kwargs(_SCREAMING_SNAKE_CASE )
if num_shards == 1:
return [dict(_SCREAMING_SNAKE_CASE )]
else:
SCREAMING_SNAKE_CASE_ = _distribute_shards(num_shards=_SCREAMING_SNAKE_CASE , max_num_jobs=_SCREAMING_SNAKE_CASE )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(_SCREAMING_SNAKE_CASE ) )
]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[dict] ):
"""simple docstring"""
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key] , _SCREAMING_SNAKE_CASE )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : np.random.Generator , _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {len(_SCREAMING_SNAKE_CASE ) for value in gen_kwargs.values() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
SCREAMING_SNAKE_CASE_ = {}
for size in list_sizes:
SCREAMING_SNAKE_CASE_ = list(range(_SCREAMING_SNAKE_CASE ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
SCREAMING_SNAKE_CASE_ = dict(_SCREAMING_SNAKE_CASE )
for key, value in shuffled_kwargs.items():
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = [value[i] for i in indices_per_size[len(_SCREAMING_SNAKE_CASE )]]
return shuffled_kwargs
| 620 | 1 |
from __future__ import annotations
import math
UpperCamelCase__ : Optional[int] = "2020.9.26"
UpperCamelCase__ : str = "xcodz-dot, cclaus, dhruvmanila"
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float ):
"""simple docstring"""
if not all(isinstance(_SCREAMING_SNAKE_CASE , (float, int) ) for val in locals().values() ):
SCREAMING_SNAKE_CASE_ = f"""Input values must either be float or int: {list(locals().values() )}"""
raise TypeError(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = ((x * distance) / (z + distance)) * scale
SCREAMING_SNAKE_CASE_ = ((y * distance) / (z + distance)) * scale
return projected_x, projected_y
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : float ):
"""simple docstring"""
if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise TypeError('Axis must be a str' )
SCREAMING_SNAKE_CASE_ = locals()
del input_variables["axis"]
if not all(isinstance(_SCREAMING_SNAKE_CASE , (float, int) ) for val in input_variables.values() ):
SCREAMING_SNAKE_CASE_ = (
'Input values except axis must either be float or int: '
f"""{list(input_variables.values() )}"""
)
raise TypeError(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = (angle % 360) / 450 * 180 / math.pi
if axis == "z":
SCREAMING_SNAKE_CASE_ = x * math.cos(_SCREAMING_SNAKE_CASE ) - y * math.sin(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = y * math.cos(_SCREAMING_SNAKE_CASE ) + x * math.sin(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = z
elif axis == "x":
SCREAMING_SNAKE_CASE_ = y * math.cos(_SCREAMING_SNAKE_CASE ) - z * math.sin(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = z * math.cos(_SCREAMING_SNAKE_CASE ) + y * math.sin(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = x
elif axis == "y":
SCREAMING_SNAKE_CASE_ = x * math.cos(_SCREAMING_SNAKE_CASE ) - z * math.sin(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = z * math.cos(_SCREAMING_SNAKE_CASE ) + x * math.sin(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = y
else:
raise ValueError('not a valid axis, choose one of \'x\', \'y\', \'z\'' )
return new_x, new_y, new_z
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F'{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }')
print(F'{rotate(1.0, 2.0, 3.0, "y", 90.0) = }')
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
UpperCamelCase__ : List[str] = {
"microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json",
# See all BioGPT models at https://huggingface.co/models?filter=biogpt
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Any = 'biogpt'
def __init__( self , _A=42384 , _A=1024 , _A=24 , _A=16 , _A=4096 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1024 , _A=0.0_2 , _A=1E-12 , _A=True , _A=True , _A=0.0 , _A=0.0 , _A=1 , _A=0 , _A=2 , **_A , ):
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = scale_embedding
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = layerdrop
SCREAMING_SNAKE_CASE_ = activation_dropout
super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A)
| 620 | 1 |
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 __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Tuple = ['image_processor', 'tokenizer']
__lowerCAmelCase : Dict = 'Pix2StructImageProcessor'
__lowerCAmelCase : List[Any] = ('T5Tokenizer', 'T5TokenizerFast')
def __init__( self , _A , _A):
SCREAMING_SNAKE_CASE_ = False
super().__init__(_A , _A)
def __call__( self , _A=None , _A = None , _A = True , _A = False , _A = None , _A = None , _A = 2048 , _A = 0 , _A = None , _A = None , _A = False , _A = False , _A = False , _A = False , _A = False , _A = True , _A = None , **_A , ):
if images is None and text is None:
raise ValueError('You have to specify either images or text.')
# Get only text
if images is None and not self.image_processor.is_vqa:
SCREAMING_SNAKE_CASE_ = self.tokenizer
SCREAMING_SNAKE_CASE_ = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
return text_encoding
if not self.image_processor.is_vqa:
# add pixel_values
SCREAMING_SNAKE_CASE_ = self.image_processor(
_A , return_tensors=_A , max_patches=_A , **_A)
else:
# add pixel_values and bbox
SCREAMING_SNAKE_CASE_ = self.image_processor(
_A , return_tensors=_A , max_patches=_A , header_text=_A , **_A)
if text is not None and not self.image_processor.is_vqa:
SCREAMING_SNAKE_CASE_ = self.tokenizer(
text=_A , add_special_tokens=_A , padding=_A , truncation=_A , max_length=_A , stride=_A , pad_to_multiple_of=_A , return_attention_mask=_A , return_overflowing_tokens=_A , return_special_tokens_mask=_A , return_offsets_mapping=_A , return_token_type_ids=_A , return_length=_A , verbose=_A , return_tensors=_A , **_A , )
if "attention_mask" in text_encoding:
SCREAMING_SNAKE_CASE_ = text_encoding.pop('attention_mask')
if "input_ids" in text_encoding:
SCREAMING_SNAKE_CASE_ = text_encoding.pop('input_ids')
else:
SCREAMING_SNAKE_CASE_ = None
if text_encoding is not None:
encoding_image_processor.update(_A)
return encoding_image_processor
def lowerCAmelCase__ ( self , *_A , **_A):
return self.tokenizer.batch_decode(*_A , **_A)
def lowerCAmelCase__ ( self , *_A , **_A):
return self.tokenizer.decode(*_A , **_A)
@property
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tokenizer.model_input_names
SCREAMING_SNAKE_CASE_ = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
| 620 |
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A , _A , _A = None , ):
super().__init__()
self.register_modules(transformer=_A , vae=_A , scheduler=_A)
# create a imagenet -> id dictionary for easier use
SCREAMING_SNAKE_CASE_ = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(','):
SCREAMING_SNAKE_CASE_ = int(_A)
SCREAMING_SNAKE_CASE_ = dict(sorted(self.labels.items()))
def lowerCAmelCase__ ( self , _A):
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = list(_A)
for l in label:
if l not in self.labels:
raise ValueError(
f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""")
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self , _A , _A = 4.0 , _A = None , _A = 50 , _A = "pil" , _A = True , ):
SCREAMING_SNAKE_CASE_ = len(_A)
SCREAMING_SNAKE_CASE_ = self.transformer.config.sample_size
SCREAMING_SNAKE_CASE_ = self.transformer.config.in_channels
SCREAMING_SNAKE_CASE_ = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=_A , device=self.device , dtype=self.transformer.dtype , )
SCREAMING_SNAKE_CASE_ = torch.cat([latents] * 2) if guidance_scale > 1 else latents
SCREAMING_SNAKE_CASE_ = torch.tensor(_A , device=self.device).reshape(-1)
SCREAMING_SNAKE_CASE_ = torch.tensor([1000] * batch_size , device=self.device)
SCREAMING_SNAKE_CASE_ = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(_A)
for t in self.progress_bar(self.scheduler.timesteps):
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ = latent_model_input[: len(_A) // 2]
SCREAMING_SNAKE_CASE_ = torch.cat([half, half] , dim=0)
SCREAMING_SNAKE_CASE_ = self.scheduler.scale_model_input(_A , _A)
SCREAMING_SNAKE_CASE_ = t
if not torch.is_tensor(_A):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
SCREAMING_SNAKE_CASE_ = latent_model_input.device.type == 'mps'
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = torch.floataa if is_mps else torch.floataa
else:
SCREAMING_SNAKE_CASE_ = torch.intaa if is_mps else torch.intaa
SCREAMING_SNAKE_CASE_ = torch.tensor([timesteps] , dtype=_A , device=latent_model_input.device)
elif len(timesteps.shape) == 0:
SCREAMING_SNAKE_CASE_ = timesteps[None].to(latent_model_input.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
SCREAMING_SNAKE_CASE_ = timesteps.expand(latent_model_input.shape[0])
# predict noise model_output
SCREAMING_SNAKE_CASE_ = self.transformer(
_A , timestep=_A , class_labels=_A).sample
# perform guidance
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , len(_A) // 2 , dim=0)
SCREAMING_SNAKE_CASE_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
SCREAMING_SNAKE_CASE_ = torch.cat([half_eps, half_eps] , dim=0)
SCREAMING_SNAKE_CASE_ = torch.cat([eps, rest] , dim=1)
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , _A , dim=1)
else:
SCREAMING_SNAKE_CASE_ = noise_pred
# compute previous image: x_t -> x_t-1
SCREAMING_SNAKE_CASE_ = self.scheduler.step(_A , _A , _A).prev_sample
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = latent_model_input.chunk(2 , dim=0)
else:
SCREAMING_SNAKE_CASE_ = latent_model_input
SCREAMING_SNAKE_CASE_ = 1 / self.vae.config.scaling_factor * latents
SCREAMING_SNAKE_CASE_ = self.vae.decode(_A).sample
SCREAMING_SNAKE_CASE_ = (samples / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
SCREAMING_SNAKE_CASE_ = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_A)
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=_A)
| 620 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available
UpperCamelCase__ : int = {"tokenization_herbert": ["HerbertTokenizer"]}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[Any] = ["HerbertTokenizerFast"]
if TYPE_CHECKING:
from .tokenization_herbert import HerbertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_herbert_fast import HerbertTokenizerFast
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class __snake_case :
def __init__( self , _A , _A , _A , _A , _A , _A=0.2 , _A=0.2):
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = conva_get[:2]
SCREAMING_SNAKE_CASE_ = conva_get[2]
SCREAMING_SNAKE_CASE_ = size_pa
SCREAMING_SNAKE_CASE_ = rate_w
SCREAMING_SNAKE_CASE_ = rate_t
SCREAMING_SNAKE_CASE_ = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5)
for i in range(self.conva[1])
]
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.conva[1]) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
def lowerCAmelCase__ ( self , _A):
# save model dict with pickle
SCREAMING_SNAKE_CASE_ = {
'num_bp1': self.num_bpa,
'num_bp2': self.num_bpa,
'num_bp3': self.num_bpa,
'conv1': self.conva,
'step_conv1': self.step_conva,
'size_pooling1': self.size_poolinga,
'rate_weight': self.rate_weight,
'rate_thre': self.rate_thre,
'w_conv1': self.w_conva,
'wkj': self.wkj,
'vji': self.vji,
'thre_conv1': self.thre_conva,
'thre_bp2': self.thre_bpa,
'thre_bp3': self.thre_bpa,
}
with open(_A , 'wb') as f:
pickle.dump(_A , _A)
print(f"""Model saved: {save_path}""")
@classmethod
def lowerCAmelCase__ ( cls , _A):
# read saved model
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = pickle.load(_A) # noqa: S301
SCREAMING_SNAKE_CASE_ = model_dic.get('conv1')
conv_get.append(model_dic.get('step_conv1'))
SCREAMING_SNAKE_CASE_ = model_dic.get('size_pooling1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp3')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_weight')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_thre')
# create model instance
SCREAMING_SNAKE_CASE_ = CNN(_A , _A , _A , _A , _A , _A , _A)
# modify model parameter
SCREAMING_SNAKE_CASE_ = model_dic.get('w_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('wkj')
SCREAMING_SNAKE_CASE_ = model_dic.get('vji')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp3')
return conv_ins
def lowerCAmelCase__ ( self , _A):
return 1 / (1 + np.exp(-1 * x))
def lowerCAmelCase__ ( self , _A):
return round(_A , 3)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
# convolution process
SCREAMING_SNAKE_CASE_ = convs[0]
SCREAMING_SNAKE_CASE_ = convs[1]
SCREAMING_SNAKE_CASE_ = np.shape(_A)[0]
# get the data slice of original image data, data_focus
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , size_data - size_conv + 1 , _A):
for j_focus in range(0 , size_data - size_conv + 1 , _A):
SCREAMING_SNAKE_CASE_ = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(_A)
# calculate the feature map of every single kernel, and saved as list of matrix
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = int((size_data - size_conv) / conv_step + 1)
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(len(_A)):
SCREAMING_SNAKE_CASE_ = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map]))
- thre_convs[i_map]
)
featuremap.append(self.sig(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(
_A , _A)
data_featuremap.append(_A)
# expanding the data slice to One dimenssion
SCREAMING_SNAKE_CASE_ = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(_A))
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return focus_list, data_featuremap
def lowerCAmelCase__ ( self , _A , _A , _A="average_pool"):
# pooling process
SCREAMING_SNAKE_CASE_ = len(featuremaps[0])
SCREAMING_SNAKE_CASE_ = int(size_map / size_pooling)
SCREAMING_SNAKE_CASE_ = []
for i_map in range(len(_A)):
SCREAMING_SNAKE_CASE_ = featuremaps[i_map]
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , _A , _A):
for j_focus in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(_A))
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(_A , _A)
featuremap_pooled.append(_A)
return featuremap_pooled
def lowerCAmelCase__ ( self , _A):
# expanding three dimension data to one dimension list
SCREAMING_SNAKE_CASE_ = []
for i in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.shape(data[i])
SCREAMING_SNAKE_CASE_ = data[i].reshape(1 , shapes[0] * shapes[1])
SCREAMING_SNAKE_CASE_ = data_listed.getA().tolist()[0]
data_expanded.extend(_A)
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return data_expanded
def lowerCAmelCase__ ( self , _A):
# expanding matrix to one dimension list
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = data_mat.reshape(1 , shapes[0] * shapes[1])
return data_expanded
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = np.ones((size_map, size_map))
for i in range(0 , _A , _A):
for j in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = pd_pool[
i_pool
]
SCREAMING_SNAKE_CASE_ = i_pool + 1
SCREAMING_SNAKE_CASE_ = np.multiply(
_A , np.multiply(out_map[i_map] , (1 - out_map[i_map])))
pd_all.append(_A)
return pd_all
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , _A=bool):
# model traning
print('----------------------Start Training-------------------------')
print((' - - Shape: Train_Data ', np.shape(_A)))
print((' - - Shape: Teach_Data ', np.shape(_A)))
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 10000
while rp < n_repeat and mse >= error_accuracy:
SCREAMING_SNAKE_CASE_ = 0
print(f"""-------------Learning Time {rp}--------------""")
for p in range(len(_A)):
# print('------------Learning Image: %d--------------'%p)
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_train[p])
SCREAMING_SNAKE_CASE_ = np.asarray(datas_teach[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.wkj.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
SCREAMING_SNAKE_CASE_ = np.multiply(
(data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.multiply(
np.dot(_A , self.wkj) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji)
SCREAMING_SNAKE_CASE_ = pd_i_all / (self.size_poolinga * self.size_poolinga)
SCREAMING_SNAKE_CASE_ = pd_conva_pooled.T.getA().tolist()
SCREAMING_SNAKE_CASE_ = self._calculate_gradient_from_pool(
_A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1]):
SCREAMING_SNAKE_CASE_ = self._expand_mat(pd_conva_all[k_conv])
SCREAMING_SNAKE_CASE_ = self.rate_weight * np.dot(_A , _A)
SCREAMING_SNAKE_CASE_ = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]))
SCREAMING_SNAKE_CASE_ = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv]) * self.rate_thre
)
# all connected layer
SCREAMING_SNAKE_CASE_ = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.vji + pd_j_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_k_all * self.rate_thre
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
SCREAMING_SNAKE_CASE_ = np.sum(abs(data_teach - bp_outa))
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
SCREAMING_SNAKE_CASE_ = rp + 1
SCREAMING_SNAKE_CASE_ = error_count / patterns
all_mse.append(_A)
def draw_error():
SCREAMING_SNAKE_CASE_ = [error_accuracy for i in range(int(n_repeat * 1.2))]
plt.plot(_A , '+-')
plt.plot(_A , 'r--')
plt.xlabel('Learning Times')
plt.ylabel('All_mse')
plt.grid(_A , alpha=0.5)
plt.show()
print('------------------Training Complished---------------------')
print((' - - Training epoch: ', rp, f""" - - Mse: {mse:.6f}"""))
if draw_e:
draw_error()
return mse
def lowerCAmelCase__ ( self , _A):
# model predict
SCREAMING_SNAKE_CASE_ = []
print('-------------------Start Testing-------------------------')
print((' - - Shape: Test_Data ', np.shape(_A)))
for p in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_test[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = bp_outa * self.vji.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = bp_outa * self.wkj.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
produce_out.extend(bp_outa.getA().tolist())
SCREAMING_SNAKE_CASE_ = [list(map(self.do_round , _A)) for each in produce_out]
return np.asarray(_A)
def lowerCAmelCase__ ( self , _A):
# return the data of image after convoluting process so we can check it out
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 620 | 1 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 1 , _SCREAMING_SNAKE_CASE : int = 1_000 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 0
for divide_by_number in range(_SCREAMING_SNAKE_CASE , digit + 1 ):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = numerator
for _ in range(1 , digit + 1 ):
if now_divide in has_been_divided:
if longest_list_length < len(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = divide_by_number
else:
has_been_divided.append(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = now_divide * 10 % divide_by_number
return the_digit
# Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
import os
import zipfile
import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int=7 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = None
if token is not None:
SCREAMING_SNAKE_CASE_ = {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}
# The id of a workflow (not of a workflow run)
SCREAMING_SNAKE_CASE_ = '636036'
SCREAMING_SNAKE_CASE_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""
SCREAMING_SNAKE_CASE_ = requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).json()
return result["workflow_runs"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_daily_ci_runs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = None
for workflow_run in workflow_runs:
if workflow_run["status"] == "completed":
SCREAMING_SNAKE_CASE_ = workflow_run['id']
break
return workflow_run_id
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE )
if workflow_run_id is not None:
SCREAMING_SNAKE_CASE_ = get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
for artifact_name in artifact_names:
if artifact_name in artifacts_links:
SCREAMING_SNAKE_CASE_ = artifacts_links[artifact_name]
download_artifact(
artifact_name=_SCREAMING_SNAKE_CASE , artifact_url=_SCREAMING_SNAKE_CASE , output_dir=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
for artifact_name in artifact_names:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{artifact_name}.zip""" )
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = {}
with zipfile.ZipFile(_SCREAMING_SNAKE_CASE ) as z:
for filename in z.namelist():
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
# read the file
with z.open(_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ = f.read().decode('UTF-8' )
return results
| 620 | 1 |
import colorsys
from PIL import Image # type: ignore
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : float , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = x
SCREAMING_SNAKE_CASE_ = y
for step in range(_SCREAMING_SNAKE_CASE ): # noqa: B007
SCREAMING_SNAKE_CASE_ = a * a - b * b + x
SCREAMING_SNAKE_CASE_ = 2 * a * b + y
SCREAMING_SNAKE_CASE_ = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : float ):
"""simple docstring"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : float ):
"""simple docstring"""
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(_SCREAMING_SNAKE_CASE , 1 , 1 ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 800 , _SCREAMING_SNAKE_CASE : int = 600 , _SCREAMING_SNAKE_CASE : float = -0.6 , _SCREAMING_SNAKE_CASE : float = 0 , _SCREAMING_SNAKE_CASE : float = 3.2 , _SCREAMING_SNAKE_CASE : int = 50 , _SCREAMING_SNAKE_CASE : bool = True , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = Image.new('RGB' , (image_width, image_height) )
SCREAMING_SNAKE_CASE_ = img.load()
# loop through the image-coordinates
for image_x in range(_SCREAMING_SNAKE_CASE ):
for image_y in range(_SCREAMING_SNAKE_CASE ):
# determine the figure-coordinates based on the image-coordinates
SCREAMING_SNAKE_CASE_ = figure_width / image_width * image_height
SCREAMING_SNAKE_CASE_ = figure_center_x + (image_x / image_width - 0.5) * figure_width
SCREAMING_SNAKE_CASE_ = figure_center_y + (image_y / image_height - 0.5) * figure_height
SCREAMING_SNAKE_CASE_ = get_distance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
SCREAMING_SNAKE_CASE_ = get_color_coded_rgb(_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = get_black_and_white_rgb(_SCREAMING_SNAKE_CASE )
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
UpperCamelCase__ : List[str] = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| 620 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase__ : Any = {
"configuration_mvp": ["MVP_PRETRAINED_CONFIG_ARCHIVE_MAP", "MvpConfig", "MvpOnnxConfig"],
"tokenization_mvp": ["MvpTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[int] = ["MvpTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"MVP_PRETRAINED_MODEL_ARCHIVE_LIST",
"MvpForCausalLM",
"MvpForConditionalGeneration",
"MvpForQuestionAnswering",
"MvpForSequenceClassification",
"MvpModel",
"MvpPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
import warnings
from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401
warnings.warn(
"The `inpainting.py` script is outdated. Please use directly `from diffusers import"
" StableDiffusionInpaintPipeline` instead."
)
| 620 |
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Dict = inspect.getfile(accelerate.test_utils )
__lowerCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
__lowerCAmelCase : Tuple = ['accelerate', 'launch']
__lowerCAmelCase : Union[str, Any] = Path.home() / '.cache/huggingface/accelerate'
__lowerCAmelCase : List[str] = 'default_config.yaml'
__lowerCAmelCase : List[Any] = config_folder / config_file
__lowerCAmelCase : str = config_folder / '_default_config.yaml'
__lowerCAmelCase : Optional[int] = Path('tests/test_configs' )
@classmethod
def lowerCAmelCase__ ( cls):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path)
@classmethod
def lowerCAmelCase__ ( cls):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
for config in sorted(self.test_config_path.glob('**/*.yaml')):
with self.subTest(config_file=_A):
execute_subprocess_async(
self.base_cmd + ['--config_file', str(_A), self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy())
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[Any] = 'test-tpu'
__lowerCAmelCase : str = 'us-central1-a'
__lowerCAmelCase : Union[str, Any] = 'ls'
__lowerCAmelCase : Union[str, Any] = ['accelerate', 'tpu-config']
__lowerCAmelCase : Union[str, Any] = 'cd /usr/share'
__lowerCAmelCase : List[Any] = 'tests/test_samples/test_command_file.sh'
__lowerCAmelCase : Dict = 'Running gcloud compute tpus tpu-vm ssh'
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command',
self.command,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A)
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--command',
self.command,
'--command',
'echo "Hello World"',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command_file',
self.command_file,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--install_accelerate',
'--accelerate_version',
'12.0.0',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
| 620 | 1 |
import argparse
import os
# New Code #
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils import find_executable_batch_size
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to ensure out-of-memory errors never
# interrupt training, and builds off the `nlp_example.py` script.
#
# 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)
#
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# 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__ : Tuple = 16
UpperCamelCase__ : List[str] = 32
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Accelerator , _SCREAMING_SNAKE_CASE : int = 16 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained('bert-base-cased' )
SCREAMING_SNAKE_CASE_ = load_dataset('glue' , 'mrpc' )
def tokenize_function(_SCREAMING_SNAKE_CASE : Dict ):
# max_length=None => use the model max length (it's actually the default)
SCREAMING_SNAKE_CASE_ = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE )
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():
SCREAMING_SNAKE_CASE_ = datasets.map(
_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , 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
SCREAMING_SNAKE_CASE_ = tokenized_datasets.rename_column('label' , 'labels' )
def collate_fn(_SCREAMING_SNAKE_CASE : str ):
# On TPU it's best to pad everything to the same length or training will be very slow.
SCREAMING_SNAKE_CASE_ = 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":
SCREAMING_SNAKE_CASE_ = 16
elif accelerator.mixed_precision != "no":
SCREAMING_SNAKE_CASE_ = 8
else:
SCREAMING_SNAKE_CASE_ = None
return tokenizer.pad(
_SCREAMING_SNAKE_CASE , padding='longest' , max_length=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_tensors='pt' , )
# Instantiate dataloaders.
SCREAMING_SNAKE_CASE_ = DataLoader(
tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = DataLoader(
tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE )
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__ : Tuple = mocked_dataloaders # noqa: F811
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
if os.environ.get('TESTING_MOCKED_DATALOADERS' , _SCREAMING_SNAKE_CASE ) == "1":
SCREAMING_SNAKE_CASE_ = 2
# Initialize accelerator
SCREAMING_SNAKE_CASE_ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
SCREAMING_SNAKE_CASE_ = config['lr']
SCREAMING_SNAKE_CASE_ = int(config['num_epochs'] )
SCREAMING_SNAKE_CASE_ = int(config['seed'] )
SCREAMING_SNAKE_CASE_ = int(config['batch_size'] )
SCREAMING_SNAKE_CASE_ = evaluate.load('glue' , 'mrpc' )
# New Code #
# We now can define an inner training loop function. It should take a batch size as the only parameter,
# and build the dataloaders in there.
# It also gets our decorator
@find_executable_batch_size(starting_batch_size=_SCREAMING_SNAKE_CASE )
def inner_training_loop(_SCREAMING_SNAKE_CASE : Any ):
# And now just move everything below under this function
# We need to bring in the Accelerator object from earlier
nonlocal accelerator
# And reset all of its attributes that could hold onto any memory:
accelerator.free_memory()
# Then we can declare the model, optimizer, and everything else:
set_seed(_SCREAMING_SNAKE_CASE )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
SCREAMING_SNAKE_CASE_ = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_SCREAMING_SNAKE_CASE )
# 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).
SCREAMING_SNAKE_CASE_ = model.to(accelerator.device )
# Instantiate optimizer
SCREAMING_SNAKE_CASE_ = AdamW(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# Instantiate scheduler
SCREAMING_SNAKE_CASE_ = get_linear_schedule_with_warmup(
optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(_SCREAMING_SNAKE_CASE ) * 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.
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = accelerator.prepare(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# Now we train the model
for epoch in range(_SCREAMING_SNAKE_CASE ):
model.train()
for step, batch in enumerate(_SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
SCREAMING_SNAKE_CASE_ = model(**_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = outputs.loss
accelerator.backward(_SCREAMING_SNAKE_CASE )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(_SCREAMING_SNAKE_CASE ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
SCREAMING_SNAKE_CASE_ = model(**_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = outputs.logits.argmax(dim=-1 )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = accelerator.gather_for_metrics((predictions, batch['labels']) )
metric.add_batch(
predictions=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(f"""epoch {epoch}:""" , _SCREAMING_SNAKE_CASE )
# New Code #
# And call it at the end with no arguments
# Note: You could also refactor this outside of your training loop function
inner_training_loop()
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser(description='Simple example of training script.' )
parser.add_argument(
'--mixed_precision' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , 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.' )
SCREAMING_SNAKE_CASE_ = parser.parse_args()
SCREAMING_SNAKE_CASE_ = {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCamelCase__ : Tuple = {
"configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
"processing_trocr": ["TrOCRProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
"TrOCRForCausalLM",
"TrOCRPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
UpperCamelCase__ : Optional[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
# See all BART models at https://huggingface.co/models?filter=bart
UpperCamelCase__ : List[str] = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
}
UpperCamelCase__ : str = {
"facebook/bart-base": 1_024,
"facebook/bart-large": 1_024,
"facebook/bart-large-mnli": 1_024,
"facebook/bart-large-cnn": 1_024,
"facebook/bart-large-xsum": 1_024,
"yjernite/bart_eli5": 1_024,
}
@lru_cache()
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (
list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) )
)
SCREAMING_SNAKE_CASE_ = bs[:]
SCREAMING_SNAKE_CASE_ = 0
for b in range(2**8 ):
if b not in bs:
bs.append(_SCREAMING_SNAKE_CASE )
cs.append(2**8 + n )
n += 1
SCREAMING_SNAKE_CASE_ = [chr(_SCREAMING_SNAKE_CASE ) for n in cs]
return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = set()
SCREAMING_SNAKE_CASE_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
SCREAMING_SNAKE_CASE_ = char
return pairs
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = VOCAB_FILES_NAMES
__lowerCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP
__lowerCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask']
def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ):
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else bos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else eos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else sep_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else cls_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else unk_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token
super().__init__(
errors=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , **_A , )
with open(_A , encoding='utf-8') as vocab_handle:
SCREAMING_SNAKE_CASE_ = json.load(_A)
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()}
SCREAMING_SNAKE_CASE_ = errors # how to handle errors in decoding
SCREAMING_SNAKE_CASE_ = bytes_to_unicode()
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.byte_encoder.items()}
with open(_A , encoding='utf-8') as merges_handle:
SCREAMING_SNAKE_CASE_ = merges_handle.read().split('\n')[1:-1]
SCREAMING_SNAKE_CASE_ = [tuple(merge.split()) for merge in bpe_merges]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
SCREAMING_SNAKE_CASE_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+')
@property
def lowerCAmelCase__ ( self):
return len(self.encoder)
def lowerCAmelCase__ ( self):
return dict(self.encoder , **self.added_tokens_encoder)
def lowerCAmelCase__ ( self , _A):
if token in self.cache:
return self.cache[token]
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
if not pairs:
return token
while True:
SCREAMING_SNAKE_CASE_ = min(_A , key=lambda _A: self.bpe_ranks.get(_A , float('inf')))
if bigram not in self.bpe_ranks:
break
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
while i < len(_A):
try:
SCREAMING_SNAKE_CASE_ = word.index(_A , _A)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
SCREAMING_SNAKE_CASE_ = j
if word[i] == first and i < len(_A) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = new_word
if len(_A) == 1:
break
else:
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
SCREAMING_SNAKE_CASE_ = ' '.join(_A)
SCREAMING_SNAKE_CASE_ = word
return word
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = []
for token in re.findall(self.pat , _A):
SCREAMING_SNAKE_CASE_ = ''.join(
self.byte_encoder[b] for b in token.encode('utf-8')) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A).split(' '))
return bpe_tokens
def lowerCAmelCase__ ( self , _A):
return self.encoder.get(_A , self.encoder.get(self.unk_token))
def lowerCAmelCase__ ( self , _A):
return self.decoder.get(_A)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = ''.join(_A)
SCREAMING_SNAKE_CASE_ = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8' , errors=self.errors)
return text
def lowerCAmelCase__ ( self , _A , _A = None):
if not os.path.isdir(_A):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""")
return
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'])
with open(_A , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A) + '\n')
SCREAMING_SNAKE_CASE_ = 0
with open(_A , 'w' , encoding='utf-8') as writer:
writer.write('#version: 0.2\n')
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A: kv[1]):
if index != token_index:
logger.warning(
f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
' Please check that the tokenizer is not corrupted!')
SCREAMING_SNAKE_CASE_ = token_index
writer.write(' '.join(_A) + '\n')
index += 1
return vocab_file, merge_file
def lowerCAmelCase__ ( self , _A , _A = None):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowerCAmelCase__ ( self , _A , _A = None , _A = False):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A)
if token_ids_a is None:
return [1] + ([0] * len(_A)) + [1]
return [1] + ([0] * len(_A)) + [1, 1] + ([0] * len(_A)) + [1]
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
def lowerCAmelCase__ ( self , _A , _A=False , **_A):
SCREAMING_SNAKE_CASE_ = kwargs.pop('add_prefix_space' , self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(_A) > 0 and not text[0].isspace()):
SCREAMING_SNAKE_CASE_ = ' ' + text
return (text, kwargs)
| 620 |
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
UpperCamelCase__ : int = Lock()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0 , 10 ):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
SCREAMING_SNAKE_CASE_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# after all swaps are performed, send the values back to main
result_pipe[1].send(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe() )
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ):
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(
len(_SCREAMING_SNAKE_CASE ) - 1,
arr[len(_SCREAMING_SNAKE_CASE ) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1],
) , ) )
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE_ = result_pipe[p][0].recv()
process_array_[p].join()
return arr
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = list(range(10 , 0 , -1 ) )
print('Initial List' )
print(*_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = odd_even_transposition(_SCREAMING_SNAKE_CASE )
print('Sorted List\n' )
print(*_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 | 1 |
from transformers import BertTokenizerFast
from .custom_tokenization import CustomTokenizer
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : List[Any] = CustomTokenizer
pass
| 620 |
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
UpperCamelCase__ : int = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n"
class __snake_case ( unittest.TestCase , lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering')
self.tool.setup()
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering' , remote=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
| 620 | 1 |
from typing import Tuple, Union
from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig
if is_timm_available():
import timm
if is_torch_available():
from torch import Tensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
__lowerCAmelCase : List[str] = 'pixel_values'
__lowerCAmelCase : List[str] = False
__lowerCAmelCase : int = TimmBackboneConfig
def __init__( self , _A , **_A):
requires_backends(self , 'timm')
super().__init__(_A)
SCREAMING_SNAKE_CASE_ = config
if config.backbone is None:
raise ValueError('backbone is not set in the config. Please set it to a timm model name.')
if config.backbone not in timm.list_models():
raise ValueError(f"""backbone {config.backbone} is not supported by timm.""")
if hasattr(_A , 'out_features') and config.out_features is not None:
raise ValueError('out_features is not supported by TimmBackbone. Please use out_indices instead.')
SCREAMING_SNAKE_CASE_ = getattr(_A , 'use_pretrained_backbone' , _A)
if pretrained is None:
raise ValueError('use_pretrained_backbone is not set in the config. Please set it to True or False.')
# We just take the final layer by default. This matches the default for the transformers models.
SCREAMING_SNAKE_CASE_ = config.out_indices if getattr(_A , 'out_indices' , _A) is not None else (-1,)
SCREAMING_SNAKE_CASE_ = timm.create_model(
config.backbone , pretrained=_A , features_only=config.features_only , in_chans=config.num_channels , out_indices=_A , **_A , )
# These are used to control the output of the model when called. If output_hidden_states is True, then
# return_layers is modified to include all layers.
SCREAMING_SNAKE_CASE_ = self._backbone.return_layers
SCREAMING_SNAKE_CASE_ = {layer['module']: str(_A) for i, layer in enumerate(self._backbone.feature_info.info)}
super()._init_backbone(_A)
@classmethod
def lowerCAmelCase__ ( cls , _A , *_A , **_A):
requires_backends(cls , ['vision', 'timm'])
from ...models.timm_backbone import TimmBackboneConfig
SCREAMING_SNAKE_CASE_ = kwargs.pop('config' , TimmBackboneConfig())
SCREAMING_SNAKE_CASE_ = kwargs.pop('use_timm_backbone' , _A)
if not use_timm:
raise ValueError('use_timm_backbone must be True for timm backbones')
SCREAMING_SNAKE_CASE_ = kwargs.pop('num_channels' , config.num_channels)
SCREAMING_SNAKE_CASE_ = kwargs.pop('features_only' , config.features_only)
SCREAMING_SNAKE_CASE_ = kwargs.pop('use_pretrained_backbone' , config.use_pretrained_backbone)
SCREAMING_SNAKE_CASE_ = kwargs.pop('out_indices' , config.out_indices)
SCREAMING_SNAKE_CASE_ = TimmBackboneConfig(
backbone=_A , num_channels=_A , features_only=_A , use_pretrained_backbone=_A , out_indices=_A , )
return super()._from_config(_A , **_A)
def lowerCAmelCase__ ( self , _A):
pass
def lowerCAmelCase__ ( self , _A , _A=None , _A=None , _A=None , **_A):
SCREAMING_SNAKE_CASE_ = return_dict if return_dict is not None else self.config.use_return_dict
SCREAMING_SNAKE_CASE_ = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
SCREAMING_SNAKE_CASE_ = output_attentions if output_attentions is not None else self.config.output_attentions
if output_attentions:
raise ValueError('Cannot output attentions for timm backbones at the moment')
if output_hidden_states:
# We modify the return layers to include all the stages of the backbone
SCREAMING_SNAKE_CASE_ = self._all_layers
SCREAMING_SNAKE_CASE_ = self._backbone(_A , **_A)
SCREAMING_SNAKE_CASE_ = self._return_layers
SCREAMING_SNAKE_CASE_ = tuple(hidden_states[i] for i in self.out_indices)
else:
SCREAMING_SNAKE_CASE_ = self._backbone(_A , **_A)
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = tuple(_A) if hidden_states is not None else None
if not return_dict:
SCREAMING_SNAKE_CASE_ = (feature_maps,)
if output_hidden_states:
SCREAMING_SNAKE_CASE_ = output + (hidden_states,)
return output
return BackboneOutput(feature_maps=_A , hidden_states=_A , attentions=_A)
| 620 |
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import BeitImageProcessor
class __snake_case ( unittest.TestCase ):
def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=False , ):
SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 20, 'width': 20}
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 18, 'width': 18}
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = min_resolution
SCREAMING_SNAKE_CASE_ = max_resolution
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean
SCREAMING_SNAKE_CASE_ = image_std
SCREAMING_SNAKE_CASE_ = do_reduce_labels
def lowerCAmelCase__ ( self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_reduce_labels": self.do_reduce_labels,
}
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[1]['file'] )
return image, map
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[1]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[2]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[3]['file'] )
return [imagea, imagea], [mapa, mapa]
@require_torch
@require_vision
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Union[str, Any] = BeitImageProcessor if is_vision_available() else None
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BeitImageProcessingTester(self)
@property
def lowerCAmelCase__ ( self):
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(_A , 'do_resize'))
self.assertTrue(hasattr(_A , 'size'))
self.assertTrue(hasattr(_A , 'do_center_crop'))
self.assertTrue(hasattr(_A , 'center_crop'))
self.assertTrue(hasattr(_A , 'do_normalize'))
self.assertTrue(hasattr(_A , 'image_mean'))
self.assertTrue(hasattr(_A , 'image_std'))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 20, 'width': 20})
self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18})
self.assertEqual(image_processor.do_reduce_labels , _A)
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A)
self.assertEqual(image_processor.size , {'height': 42, 'width': 42})
self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84})
self.assertEqual(image_processor.do_reduce_labels , _A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A)
for image in image_inputs:
self.assertIsInstance(_A , Image.Image)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A)
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
SCREAMING_SNAKE_CASE_ = []
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
maps.append(torch.zeros(image.shape[-2:]).long())
# Test not batched input
SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , maps[0] , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test not batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_batch_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
2,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
2,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 150)
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
| 620 | 1 |
import warnings
from ...utils import logging
from .image_processing_poolformer import PoolFormerImageProcessor
UpperCamelCase__ : Tuple = logging.get_logger(__name__)
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , *_A , **_A):
warnings.warn(
'The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
' Please use PoolFormerImageProcessor instead.' , _A , )
super().__init__(*_A , **_A)
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 200 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [1, 2, 5, 10, 20, 50, 100, 200]
SCREAMING_SNAKE_CASE_ = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(_SCREAMING_SNAKE_CASE , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73_682
| 620 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase__ : Union[str, Any] = {
"configuration_nllb_moe": [
"NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP",
"NllbMoeConfig",
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST",
"NllbMoeForConditionalGeneration",
"NllbMoeModel",
"NllbMoePreTrainedModel",
"NllbMoeTop2Router",
"NllbMoeSparseMLP",
]
if TYPE_CHECKING:
from .configuration_nllb_moe import (
NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP,
NllbMoeConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_nllb_moe import (
NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST,
NllbMoeForConditionalGeneration,
NllbMoeModel,
NllbMoePreTrainedModel,
NllbMoeSparseMLP,
NllbMoeTopaRouter,
)
else:
import sys
UpperCamelCase__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if index == number_of_items:
return 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 )
if weights[index] <= max_weight:
SCREAMING_SNAKE_CASE_ = values[index] + knapsack(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 )
return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 | 1 |
from __future__ import annotations
import collections
import pprint
from pathlib import Path
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
return "".join(sorted(_SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
return word_by_signature[signature(_SCREAMING_SNAKE_CASE )]
UpperCamelCase__ : str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8")
UpperCamelCase__ : Union[str, Any] = sorted({word.strip().lower() for word in data.splitlines()})
UpperCamelCase__ : str = collections.defaultdict(list)
for word in word_list:
word_by_signature[signature(word)].append(word)
if __name__ == "__main__":
UpperCamelCase__ : Optional[int] = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n ")
file.write(pprint.pformat(all_anagrams))
| 620 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase__ : List[Any] = torch.device("cpu")
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = dct.pop(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = val
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for k in state_dict.keys():
SCREAMING_SNAKE_CASE_ = k
if ".pwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.pwconv' , '.point_wise_conv' )
if ".dwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.dwconv' , '.depth_wise_conv' )
if ".Proj." in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.Proj.' , '.proj.' )
if "patch_embed" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' )
if "network" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.split('.' )
if ls[2].isdigit():
SCREAMING_SNAKE_CASE_ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] )
else:
SCREAMING_SNAKE_CASE_ = k_new.replace('network' , 'swiftformer.encoder.network' )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
SCREAMING_SNAKE_CASE_ = 1_000
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json'
SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
SCREAMING_SNAKE_CASE_ = [3, 3, 6, 4]
SCREAMING_SNAKE_CASE_ = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
SCREAMING_SNAKE_CASE_ = [3, 3, 9, 6]
SCREAMING_SNAKE_CASE_ = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
SCREAMING_SNAKE_CASE_ = [4, 3, 10, 5]
SCREAMING_SNAKE_CASE_ = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
SCREAMING_SNAKE_CASE_ = [4, 4, 12, 6]
SCREAMING_SNAKE_CASE_ = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith('https' ):
SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
SCREAMING_SNAKE_CASE_ = checkpoint
SCREAMING_SNAKE_CASE_ = create_rename_keys(_SCREAMING_SNAKE_CASE )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
SCREAMING_SNAKE_CASE_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval()
hf_model.load_state_dict(_SCREAMING_SNAKE_CASE )
# prepare test inputs
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = ViTImageProcessor.from_pretrained('preprocessor_config' )
SCREAMING_SNAKE_CASE_ = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
# compare outputs from both models
SCREAMING_SNAKE_CASE_ = get_expected_output(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = hf_model(inputs['pixel_values'] ).logits
assert hf_logits.shape == torch.Size([1, 1_000] )
assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1E-3 )
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--swiftformer_name",
default="swiftformer_xs",
choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"],
type=str,
help="Name of the SwiftFormer model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="./converted_outputs/",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.")
UpperCamelCase__ : Union[str, Any] = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 620 | 1 |
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
UpperCamelCase__ : Tuple = logging.get_logger(__name__)
UpperCamelCase__ : Union[str, Any] = {
"SenseTime/deformable-detr": "https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json",
# See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Dict = 'deformable_detr'
__lowerCAmelCase : List[str] = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=1024 , _A=6 , _A=1024 , _A=8 , _A=6 , _A=1024 , _A=8 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=True , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=4 , _A=4 , _A=4 , _A=False , _A=300 , _A=False , _A=1 , _A=5 , _A=2 , _A=1 , _A=1 , _A=5 , _A=2 , _A=0.1 , _A=0.2_5 , _A=False , **_A , ):
if backbone_config is not None and use_timm_backbone:
raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.')
if not use_timm_backbone:
if backbone_config is None:
logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.')
SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING['resnet'](out_features=['stage4'])
elif isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = backbone_config.get('model_type')
SCREAMING_SNAKE_CASE_ = CONFIG_MAPPING[backbone_model_type]
SCREAMING_SNAKE_CASE_ = config_class.from_dict(_A)
SCREAMING_SNAKE_CASE_ = use_timm_backbone
SCREAMING_SNAKE_CASE_ = backbone_config
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = num_queries
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = encoder_ffn_dim
SCREAMING_SNAKE_CASE_ = encoder_layers
SCREAMING_SNAKE_CASE_ = encoder_attention_heads
SCREAMING_SNAKE_CASE_ = decoder_ffn_dim
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = dropout
SCREAMING_SNAKE_CASE_ = attention_dropout
SCREAMING_SNAKE_CASE_ = activation_dropout
SCREAMING_SNAKE_CASE_ = activation_function
SCREAMING_SNAKE_CASE_ = init_std
SCREAMING_SNAKE_CASE_ = init_xavier_std
SCREAMING_SNAKE_CASE_ = encoder_layerdrop
SCREAMING_SNAKE_CASE_ = auxiliary_loss
SCREAMING_SNAKE_CASE_ = position_embedding_type
SCREAMING_SNAKE_CASE_ = backbone
SCREAMING_SNAKE_CASE_ = use_pretrained_backbone
SCREAMING_SNAKE_CASE_ = dilation
# deformable attributes
SCREAMING_SNAKE_CASE_ = num_feature_levels
SCREAMING_SNAKE_CASE_ = encoder_n_points
SCREAMING_SNAKE_CASE_ = decoder_n_points
SCREAMING_SNAKE_CASE_ = two_stage
SCREAMING_SNAKE_CASE_ = two_stage_num_proposals
SCREAMING_SNAKE_CASE_ = with_box_refine
if two_stage is True and with_box_refine is False:
raise ValueError('If two_stage is True, with_box_refine must be True.')
# Hungarian matcher
SCREAMING_SNAKE_CASE_ = class_cost
SCREAMING_SNAKE_CASE_ = bbox_cost
SCREAMING_SNAKE_CASE_ = giou_cost
# Loss coefficients
SCREAMING_SNAKE_CASE_ = mask_loss_coefficient
SCREAMING_SNAKE_CASE_ = dice_loss_coefficient
SCREAMING_SNAKE_CASE_ = bbox_loss_coefficient
SCREAMING_SNAKE_CASE_ = giou_loss_coefficient
SCREAMING_SNAKE_CASE_ = eos_coefficient
SCREAMING_SNAKE_CASE_ = focal_alpha
SCREAMING_SNAKE_CASE_ = disable_custom_kernels
super().__init__(is_encoder_decoder=_A , **_A)
@property
def lowerCAmelCase__ ( self):
return self.encoder_attention_heads
@property
def lowerCAmelCase__ ( self):
return self.d_model
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = copy.deepcopy(self.__dict__)
if self.backbone_config is not None:
SCREAMING_SNAKE_CASE_ = self.backbone_config.to_dict()
SCREAMING_SNAKE_CASE_ = self.__class__.model_type
return output
| 620 |
def _UpperCAmelCase ( ):
"""simple docstring"""
for n in range(1 , 1_000_000 ):
yield n * (n + 1) // 2
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 2
while i * i <= n:
SCREAMING_SNAKE_CASE_ = 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 _UpperCAmelCase ( ):
"""simple docstring"""
return next(i for i in triangle_number_generator() if count_divisors(_SCREAMING_SNAKE_CASE ) > 500 )
if __name__ == "__main__":
print(solution())
| 620 | 1 |
import qiskit
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = qiskit.Aer.get_backend('aer_simulator' )
SCREAMING_SNAKE_CASE_ = qiskit.QuantumCircuit(4 , 2 )
# encode inputs in qubits 0 and 1
if bita == 1:
qc_ha.x(0 )
if bita == 1:
qc_ha.x(1 )
qc_ha.barrier()
# use cnots to write XOR of the inputs on qubit2
qc_ha.cx(0 , 2 )
qc_ha.cx(1 , 2 )
# use ccx / toffoli gate to write AND of the inputs on qubit3
qc_ha.ccx(0 , 1 , 3 )
qc_ha.barrier()
# extract outputs
qc_ha.measure(2 , 0 ) # extract XOR value
qc_ha.measure(3 , 1 ) # extract AND value
# Execute the circuit on the qasm simulator
SCREAMING_SNAKE_CASE_ = qiskit.execute(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , shots=1_000 )
# Return the histogram data of the results of the experiment
return job.result().get_counts(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : str = half_adder(1, 1)
print(F'Half Adder Output Qubit Counts: {counts}')
| 620 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
UpperCamelCase__ : Optional[int] = datasets.utils.logging.get_logger(__name__)
@dataclass
class __snake_case ( datasets.BuilderConfig ):
__lowerCAmelCase : Optional[datasets.Features] = None
__lowerCAmelCase : str = "utf-8"
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : bool = True # deprecated
__lowerCAmelCase : Optional[int] = None # deprecated
__lowerCAmelCase : int = 10 << 20 # 10MB
__lowerCAmelCase : Optional[bool] = None
class __snake_case ( datasets.ArrowBasedBuilder ):
__lowerCAmelCase : int = JsonConfig
def lowerCAmelCase__ ( self):
if self.config.block_size is not None:
logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead')
SCREAMING_SNAKE_CASE_ = self.config.block_size
if self.config.use_threads is not True:
logger.warning(
'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.')
if self.config.newlines_in_values is not None:
raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported')
return datasets.DatasetInfo(features=self.config.features)
def lowerCAmelCase__ ( self , _A):
if not self.config.data_files:
raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
SCREAMING_SNAKE_CASE_ = dl_manager.download_and_extract(self.config.data_files)
if isinstance(_A , (str, list, tuple)):
SCREAMING_SNAKE_CASE_ = data_files
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files})]
SCREAMING_SNAKE_CASE_ = []
for split_name, files in data_files.items():
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'files': files}))
return splits
def lowerCAmelCase__ ( self , _A):
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features) - set(pa_table.column_names):
SCREAMING_SNAKE_CASE_ = self.config.features.arrow_schema.field(_A).type
SCREAMING_SNAKE_CASE_ = pa_table.append_column(_A , pa.array([None] * len(_A) , type=_A))
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
SCREAMING_SNAKE_CASE_ = table_cast(_A , self.config.features.arrow_schema)
return pa_table
def lowerCAmelCase__ ( self , _A):
for file_idx, file in enumerate(itertools.chain.from_iterable(_A)):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
# We keep only the field we are interested in
SCREAMING_SNAKE_CASE_ = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(_A , (list, tuple)):
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
else:
SCREAMING_SNAKE_CASE_ = dataset
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
yield file_idx, self._cast_table(_A)
# If the file has one json object per line
else:
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = 0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
SCREAMING_SNAKE_CASE_ = max(self.config.chunksize // 32 , 16 << 10)
SCREAMING_SNAKE_CASE_ = (
self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
)
while True:
SCREAMING_SNAKE_CASE_ = f.read(self.config.chunksize)
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(_A)
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
SCREAMING_SNAKE_CASE_ = batch.decode(self.config.encoding , errors=_A).encode('utf-8')
try:
while True:
try:
SCREAMING_SNAKE_CASE_ = paj.read_json(
io.BytesIO(_A) , read_options=paj.ReadOptions(block_size=_A))
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(_A , pa.ArrowInvalid)
and "straddling" not in str(_A)
or block_size > len(_A)
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
f"""Batch of {len(_A)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""")
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
except json.JSONDecodeError:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(_A , _A): # list is the only sequence type supported in JSON
try:
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(f"""Not able to read records in the JSON file at {file}.""") from None
yield file_idx, self._cast_table(_A)
break
else:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(
f"""Not able to read records in the JSON file at {file}. """
f"""You should probably indicate the field of the JSON file containing your records. """
f"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """
f"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_A)
batch_idx += 1
| 620 | 1 |
import os
from typing import BinaryIO, Optional, Union
import numpy as np
import pyarrow.parquet as pq
from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Features ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = np.inf
def set_batch_size(_SCREAMING_SNAKE_CASE : FeatureType ) -> None:
nonlocal batch_size
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS )
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS )
elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and feature.dtype == "binary":
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS )
_visit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
return None if batch_size is np.inf else batch_size
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A = None , _A = None , _A = None , _A = False , _A = False , _A = None , **_A , ):
super().__init__(
_A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , )
SCREAMING_SNAKE_CASE_ = path_or_paths if isinstance(_A , _A) else {self.split: path_or_paths}
SCREAMING_SNAKE_CASE_ = _PACKAGED_DATASETS_MODULES['parquet'][1]
SCREAMING_SNAKE_CASE_ = Parquet(
cache_dir=_A , data_files=_A , features=_A , hash=_A , **_A , )
def lowerCAmelCase__ ( self):
# Build iterable dataset
if self.streaming:
SCREAMING_SNAKE_CASE_ = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
self.builder.download_and_prepare(
download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , )
SCREAMING_SNAKE_CASE_ = self.builder.as_dataset(
split=self.split , verification_mode=_A , in_memory=self.keep_in_memory)
return dataset
class __snake_case :
def __init__( self , _A , _A , _A = None , **_A , ):
SCREAMING_SNAKE_CASE_ = dataset
SCREAMING_SNAKE_CASE_ = path_or_buf
SCREAMING_SNAKE_CASE_ = batch_size or get_writer_batch_size(dataset.features)
SCREAMING_SNAKE_CASE_ = parquet_writer_kwargs
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE
if isinstance(self.path_or_buf , (str, bytes, os.PathLike)):
with open(self.path_or_buf , 'wb+') as buffer:
SCREAMING_SNAKE_CASE_ = self._write(file_obj=_A , batch_size=_A , **self.parquet_writer_kwargs)
else:
SCREAMING_SNAKE_CASE_ = self._write(file_obj=self.path_or_buf , batch_size=_A , **self.parquet_writer_kwargs)
return written
def lowerCAmelCase__ ( self , _A , _A , **_A):
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = parquet_writer_kwargs.pop('path_or_buf' , _A)
SCREAMING_SNAKE_CASE_ = self.dataset.features.arrow_schema
SCREAMING_SNAKE_CASE_ = pq.ParquetWriter(_A , schema=_A , **_A)
for offset in logging.tqdm(
range(0 , len(self.dataset) , _A) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating parquet from Arrow format' , ):
SCREAMING_SNAKE_CASE_ = query_table(
table=self.dataset._data , key=slice(_A , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , )
writer.write_table(_A)
written += batch.nbytes
writer.close()
return written
| 620 |
import unittest
from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM
@require_torch
class __snake_case :
def __init__( self , _A , _A=99 , _A=13 , _A=16 , _A=7 , _A=True , _A=True , _A=True , _A=False , _A=True , _A=2 , _A=32 , _A=4 , _A=4 , _A=30 , _A=0 , _A=1 , _A=2 , _A=None , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE_ = self.decoder_seq_length
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_attention_mask
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_ffn_dim
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = eos_token_id
SCREAMING_SNAKE_CASE_ = bos_token_id
SCREAMING_SNAKE_CASE_ = pad_token_id
SCREAMING_SNAKE_CASE_ = decoder_start_token_id
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = decoder_seq_length
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_attention_mask:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2)
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = TrOCRConfig(
vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , )
return (config, input_ids, attention_mask, lm_labels)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , ):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = TrOCRDecoder(config=_A).to(_A).eval()
SCREAMING_SNAKE_CASE_ = input_ids[:2]
input_ids[input_ids == 0] += 1
# first forward pass
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
self.parent.assertTrue(len(_A) == len(_A))
self.parent.assertTrue(len(_A) == len(_A) + 1)
SCREAMING_SNAKE_CASE_ = outputs['past_key_values']
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE_ = ids_tensor((2, 1) , config.vocab_size - 1) + 1
# append to next input_ids and
SCREAMING_SNAKE_CASE_ = torch.cat([input_ids, next_tokens] , dim=-1)
SCREAMING_SNAKE_CASE_ = model(_A)['last_hidden_state']
SCREAMING_SNAKE_CASE_ = model(_A , past_key_values=_A)['last_hidden_state']
# select random slice
SCREAMING_SNAKE_CASE_ = ids_tensor((1,) , output_from_past.shape[-1]).item()
SCREAMING_SNAKE_CASE_ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE_ = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(_A , _A , atol=1E-3)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
@require_torch
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Tuple = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
__lowerCAmelCase : Union[str, Any] = (TrOCRForCausalLM,) if is_torch_available() else ()
__lowerCAmelCase : str = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
__lowerCAmelCase : Any = True
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TrOCRStandaloneDecoderModelTester(self , is_training=_A)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*_A)
def lowerCAmelCase__ ( self):
return
@unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :)
def lowerCAmelCase__ ( self):
pass
| 620 | 1 |
import argparse
import json
import re
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
MobileNetVaConfig,
MobileNetVaForImageClassification,
MobileNetVaImageProcessor,
load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = MobileNetVaConfig(layer_norm_eps=0.001 )
if "_quant" in model_name:
raise ValueError('Quantized models are not supported.' )
SCREAMING_SNAKE_CASE_ = re.match(r'^mobilenet_v1_([^_]*)_([^_]*)$' , _SCREAMING_SNAKE_CASE )
if matches:
SCREAMING_SNAKE_CASE_ = float(matches[1] )
SCREAMING_SNAKE_CASE_ = int(matches[2] )
# The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
# the usual 1000. The first class (index 0) is "background".
SCREAMING_SNAKE_CASE_ = 1_001
SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json'
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ) + 1: v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = 'background'
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
return config
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[str]=False ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_mobilenet_va_config(_SCREAMING_SNAKE_CASE )
# Load 🤗 model
SCREAMING_SNAKE_CASE_ = MobileNetVaForImageClassification(_SCREAMING_SNAKE_CASE ).eval()
# Load weights from TensorFlow checkpoint
load_tf_weights_in_mobilenet_va(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# Check outputs on an image, prepared by MobileNetV1ImageProcessor
SCREAMING_SNAKE_CASE_ = MobileNetVaImageProcessor(
crop_size={'width': config.image_size, 'height': config.image_size} , size={'shortest_edge': config.image_size + 32} , )
SCREAMING_SNAKE_CASE_ = image_processor(images=prepare_img() , return_tensors='pt' )
SCREAMING_SNAKE_CASE_ = model(**_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = outputs.logits
assert logits.shape == (1, 1_001)
if model_name == "mobilenet_v1_1.0_224":
SCREAMING_SNAKE_CASE_ = torch.tensor([-4.1739, -1.1233, 3.1205] )
elif model_name == "mobilenet_v1_0.75_192":
SCREAMING_SNAKE_CASE_ = torch.tensor([-3.9440, -2.3141, -0.3333] )
else:
SCREAMING_SNAKE_CASE_ = None
if expected_logits is not None:
assert torch.allclose(logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 )
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
print(f"""Saving image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(_SCREAMING_SNAKE_CASE )
if push_to_hub:
print('Pushing to the hub...' )
SCREAMING_SNAKE_CASE_ = 'google/' + model_name
image_processor.push_to_hub(_SCREAMING_SNAKE_CASE )
model.push_to_hub(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--model_name",
default="mobilenet_v1_1.0_224",
type=str,
help="Name of the MobileNetV1 model you'd like to convert. Should in the form 'mobilenet_v1_<depth>_<size>'.",
)
parser.add_argument(
"--checkpoint_path", required=True, type=str, help="Path to the original TensorFlow checkpoint (.ckpt file)."
)
parser.add_argument(
"--pytorch_dump_folder_path", required=True, type=str, help="Path to the output PyTorch model directory."
)
parser.add_argument(
"--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
)
UpperCamelCase__ : str = parser.parse_args()
convert_movilevit_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 620 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : torch.FloatTensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ):
super().__init__()
# pass init params to Encoder
SCREAMING_SNAKE_CASE_ = Encoder(
in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , )
SCREAMING_SNAKE_CASE_ = vq_embed_dim if vq_embed_dim is not None else latent_channels
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
SCREAMING_SNAKE_CASE_ = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A)
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
# pass init params to Decoder
SCREAMING_SNAKE_CASE_ = Decoder(
in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , )
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = self.encoder(_A)
SCREAMING_SNAKE_CASE_ = self.quant_conv(_A)
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_A)
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = False , _A = True):
# also go through quantization layer
if not force_not_quantize:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.quantize(_A)
else:
SCREAMING_SNAKE_CASE_ = h
SCREAMING_SNAKE_CASE_ = self.post_quant_conv(_A)
SCREAMING_SNAKE_CASE_ = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None)
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = sample
SCREAMING_SNAKE_CASE_ = self.encode(_A).latents
SCREAMING_SNAKE_CASE_ = self.decode(_A).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
| 620 | 1 |
import argparse
import torch
from transformers import YosoConfig, YosoForMaskedLM
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
if "model" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('model.' , '' )
if "norm1" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('norm1' , 'attention.output.LayerNorm' )
if "norm2" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('norm2' , 'output.LayerNorm' )
if "norm" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('norm' , 'LayerNorm' )
if "transformer" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.split('.' )[0].split('_' )[-1]
SCREAMING_SNAKE_CASE_ = orig_key.replace(f"""transformer_{layer_num}""" , f"""encoder.layer.{layer_num}""" )
if "mha.attn" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('mha.attn' , 'attention.self' )
if "mha" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('mha' , 'attention' )
if "W_q" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('W_q' , 'self.query' )
if "W_k" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('W_k' , 'self.key' )
if "W_v" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('W_v' , 'self.value' )
if "ff1" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('ff1' , 'intermediate.dense' )
if "ff2" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('ff2' , 'output.dense' )
if "ff" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('ff' , 'output.dense' )
if "mlm_class" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('mlm.mlm_class' , 'cls.predictions.decoder' )
if "mlm" in orig_key:
SCREAMING_SNAKE_CASE_ = orig_key.replace('mlm' , 'cls.predictions.transform' )
if "cls" not in orig_key:
SCREAMING_SNAKE_CASE_ = 'yoso.' + orig_key
return orig_key
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
for key in orig_state_dict.copy().keys():
SCREAMING_SNAKE_CASE_ = orig_state_dict.pop(_SCREAMING_SNAKE_CASE )
if ("pooler" in key) or ("sen_class" in key):
continue
else:
SCREAMING_SNAKE_CASE_ = val
SCREAMING_SNAKE_CASE_ = orig_state_dict['cls.predictions.decoder.bias']
SCREAMING_SNAKE_CASE_ = torch.arange(_SCREAMING_SNAKE_CASE ).expand((1, -1) ) + 2
return orig_state_dict
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )['model_state_dict']
SCREAMING_SNAKE_CASE_ = YosoConfig.from_json_file(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = YosoForMaskedLM(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = convert_checkpoint_helper(config.max_position_embeddings , _SCREAMING_SNAKE_CASE )
print(model.load_state_dict(_SCREAMING_SNAKE_CASE ) )
model.eval()
model.save_pretrained(_SCREAMING_SNAKE_CASE )
print(f"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" )
if __name__ == "__main__":
UpperCamelCase__ : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--pytorch_model_path", default=None, type=str, required=True, help="Path to YOSO pytorch checkpoint."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The json file for YOSO model config.",
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
UpperCamelCase__ : str = parser.parse_args()
convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
| 620 |
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
UpperCamelCase__ : Optional[int] = logging.getLogger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : torch.nn.Module , _SCREAMING_SNAKE_CASE : BnbQuantizationConfig , _SCREAMING_SNAKE_CASE : Union[str, os.PathLike] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[str, Union[int, str, torch.device]]] = None , _SCREAMING_SNAKE_CASE : Optional[List[str]] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[Union[int, str], Union[int, str]]] = None , _SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , _SCREAMING_SNAKE_CASE : bool = False , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.load_in_abit
SCREAMING_SNAKE_CASE_ = 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.' )
SCREAMING_SNAKE_CASE_ = []
# custom device map
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1:
SCREAMING_SNAKE_CASE_ = [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:
SCREAMING_SNAKE_CASE_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE )
# compatibility with peft
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = get_parameter_device(_SCREAMING_SNAKE_CASE )
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.' )
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
# convert param to the right dtype
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = name.replace('.weight' , '' ).replace('.bias' , '' )
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ):
param.to(_SCREAMING_SNAKE_CASE )
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():
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = get_quantized_model_device_map(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] )
load_checkpoint_in_model(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
SCREAMING_SNAKE_CASE_ = {'': 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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
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\'.' )
SCREAMING_SNAKE_CASE_ = {}
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 )
} )
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = special_dtypes
SCREAMING_SNAKE_CASE_ = no_split_module_classes
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
SCREAMING_SNAKE_CASE_ = get_balanced_memory(
_SCREAMING_SNAKE_CASE , low_zero=(device_map == 'balanced_low_0') , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = max_memory
SCREAMING_SNAKE_CASE_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
# check if don't have any quantized module on the cpu
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
SCREAMING_SNAKE_CASE_ = {
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if modules_to_not_convert is None:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : str=None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = False
for name, module in model.named_children():
if current_key_name is None:
SCREAMING_SNAKE_CASE_ = []
current_key_name.append(_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
SCREAMING_SNAKE_CASE_ = '.'.join(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = 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' )
SCREAMING_SNAKE_CASE_ = module.weight.data
if module.bias is not None:
SCREAMING_SNAKE_CASE_ = module.bias.data
bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE )
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = True
if len(list(module.children() ) ) > 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
with init_empty_weights():
SCREAMING_SNAKE_CASE_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
SCREAMING_SNAKE_CASE_ = find_tied_parameters(_SCREAMING_SNAKE_CASE )
# For compatibility with Accelerate < 0.18
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
SCREAMING_SNAKE_CASE_ = sum(_SCREAMING_SNAKE_CASE , [] )
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE ) > 0
# Check if it is a base model
SCREAMING_SNAKE_CASE_ = False
if hasattr(_SCREAMING_SNAKE_CASE , 'base_model_prefix' ):
SCREAMING_SNAKE_CASE_ = not hasattr(_SCREAMING_SNAKE_CASE , 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
SCREAMING_SNAKE_CASE_ = list(model.named_children() )
SCREAMING_SNAKE_CASE_ = [list_modules[-1][0]]
# add last module together with tied weights
SCREAMING_SNAKE_CASE_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE )
# remove ".weight" from the keys
SCREAMING_SNAKE_CASE_ = ['.weight', '.bias']
SCREAMING_SNAKE_CASE_ = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
SCREAMING_SNAKE_CASE_ = name.replace(_SCREAMING_SNAKE_CASE , '' )
filtered_module_names.append(_SCREAMING_SNAKE_CASE )
return filtered_module_names
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for m in model.modules():
if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ):
return True
return False
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : nn.Module ):
"""simple docstring"""
return next(parameter.parameters() ).device
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = param_name
SCREAMING_SNAKE_CASE_ = model
if "." in tensor_name:
SCREAMING_SNAKE_CASE_ = tensor_name.split('.' )
for split in splits[:-1]:
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
SCREAMING_SNAKE_CASE_ = new_module
SCREAMING_SNAKE_CASE_ = splits[-1]
# offload weights
SCREAMING_SNAKE_CASE_ = False
offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
if hasattr(module._parameters[tensor_name] , 'SCB' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , )
else:
offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'meta' , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
| 620 | 1 |
from math import factorial
UpperCamelCase__ : List[str] = {str(d): factorial(d) for d in range(10)}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
return sum(DIGIT_FACTORIAL[d] for d in str(_SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 7 * factorial(9 ) + 1
return sum(i for i in range(3 , _SCREAMING_SNAKE_CASE ) if sum_of_digit_factorial(_SCREAMING_SNAKE_CASE ) == i )
if __name__ == "__main__":
print(F'{solution() = }')
| 620 |
import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
UpperCamelCase__ : Optional[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
# See all BART models at https://huggingface.co/models?filter=bart
UpperCamelCase__ : List[str] = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
}
UpperCamelCase__ : str = {
"facebook/bart-base": 1_024,
"facebook/bart-large": 1_024,
"facebook/bart-large-mnli": 1_024,
"facebook/bart-large-cnn": 1_024,
"facebook/bart-large-xsum": 1_024,
"yjernite/bart_eli5": 1_024,
}
@lru_cache()
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (
list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) )
)
SCREAMING_SNAKE_CASE_ = bs[:]
SCREAMING_SNAKE_CASE_ = 0
for b in range(2**8 ):
if b not in bs:
bs.append(_SCREAMING_SNAKE_CASE )
cs.append(2**8 + n )
n += 1
SCREAMING_SNAKE_CASE_ = [chr(_SCREAMING_SNAKE_CASE ) for n in cs]
return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = set()
SCREAMING_SNAKE_CASE_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
SCREAMING_SNAKE_CASE_ = char
return pairs
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = VOCAB_FILES_NAMES
__lowerCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP
__lowerCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask']
def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ):
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else bos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else eos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else sep_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else cls_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else unk_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token
super().__init__(
errors=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , **_A , )
with open(_A , encoding='utf-8') as vocab_handle:
SCREAMING_SNAKE_CASE_ = json.load(_A)
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()}
SCREAMING_SNAKE_CASE_ = errors # how to handle errors in decoding
SCREAMING_SNAKE_CASE_ = bytes_to_unicode()
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.byte_encoder.items()}
with open(_A , encoding='utf-8') as merges_handle:
SCREAMING_SNAKE_CASE_ = merges_handle.read().split('\n')[1:-1]
SCREAMING_SNAKE_CASE_ = [tuple(merge.split()) for merge in bpe_merges]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
SCREAMING_SNAKE_CASE_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+')
@property
def lowerCAmelCase__ ( self):
return len(self.encoder)
def lowerCAmelCase__ ( self):
return dict(self.encoder , **self.added_tokens_encoder)
def lowerCAmelCase__ ( self , _A):
if token in self.cache:
return self.cache[token]
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
if not pairs:
return token
while True:
SCREAMING_SNAKE_CASE_ = min(_A , key=lambda _A: self.bpe_ranks.get(_A , float('inf')))
if bigram not in self.bpe_ranks:
break
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
while i < len(_A):
try:
SCREAMING_SNAKE_CASE_ = word.index(_A , _A)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
SCREAMING_SNAKE_CASE_ = j
if word[i] == first and i < len(_A) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = new_word
if len(_A) == 1:
break
else:
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
SCREAMING_SNAKE_CASE_ = ' '.join(_A)
SCREAMING_SNAKE_CASE_ = word
return word
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = []
for token in re.findall(self.pat , _A):
SCREAMING_SNAKE_CASE_ = ''.join(
self.byte_encoder[b] for b in token.encode('utf-8')) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A).split(' '))
return bpe_tokens
def lowerCAmelCase__ ( self , _A):
return self.encoder.get(_A , self.encoder.get(self.unk_token))
def lowerCAmelCase__ ( self , _A):
return self.decoder.get(_A)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = ''.join(_A)
SCREAMING_SNAKE_CASE_ = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8' , errors=self.errors)
return text
def lowerCAmelCase__ ( self , _A , _A = None):
if not os.path.isdir(_A):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""")
return
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'])
with open(_A , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A) + '\n')
SCREAMING_SNAKE_CASE_ = 0
with open(_A , 'w' , encoding='utf-8') as writer:
writer.write('#version: 0.2\n')
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A: kv[1]):
if index != token_index:
logger.warning(
f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
' Please check that the tokenizer is not corrupted!')
SCREAMING_SNAKE_CASE_ = token_index
writer.write(' '.join(_A) + '\n')
index += 1
return vocab_file, merge_file
def lowerCAmelCase__ ( self , _A , _A = None):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowerCAmelCase__ ( self , _A , _A = None , _A = False):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A)
if token_ids_a is None:
return [1] + ([0] * len(_A)) + [1]
return [1] + ([0] * len(_A)) + [1, 1] + ([0] * len(_A)) + [1]
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
def lowerCAmelCase__ ( self , _A , _A=False , **_A):
SCREAMING_SNAKE_CASE_ = kwargs.pop('add_prefix_space' , self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(_A) > 0 and not text[0].isspace()):
SCREAMING_SNAKE_CASE_ = ' ' + text
return (text, kwargs)
| 620 | 1 |
import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch
import numpy as np
from datasets import Dataset
from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch
if is_faiss_available():
import faiss
@require_faiss
class __snake_case ( lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE_ = 8
# DPR tok
SCREAMING_SNAKE_CASE_ = [
'[UNK]',
'[CLS]',
'[SEP]',
'[PAD]',
'[MASK]',
'want',
'##want',
'##ed',
'wa',
'un',
'runn',
'##ing',
',',
'low',
'lowest',
]
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , 'dpr_tokenizer')
os.makedirs(_A , exist_ok=_A)
SCREAMING_SNAKE_CASE_ = os.path.join(_A , DPR_VOCAB_FILES_NAMES['vocab_file'])
with open(self.vocab_file , 'w' , encoding='utf-8') as vocab_writer:
vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]))
# BART tok
SCREAMING_SNAKE_CASE_ = [
'l',
'o',
'w',
'e',
'r',
's',
't',
'i',
'd',
'n',
'\u0120',
'\u0120l',
'\u0120n',
'\u0120lo',
'\u0120low',
'er',
'\u0120lowest',
'\u0120newer',
'\u0120wider',
'<unk>',
]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
SCREAMING_SNAKE_CASE_ = {'unk_token': '<unk>'}
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , 'bart_tokenizer')
os.makedirs(_A , exist_ok=_A)
SCREAMING_SNAKE_CASE_ = os.path.join(_A , BART_VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(_A , BART_VOCAB_FILES_NAMES['merges_file'])
with open(self.vocab_file , 'w' , encoding='utf-8') as fp:
fp.write(json.dumps(_A) + '\n')
with open(self.merges_file , 'w' , encoding='utf-8') as fp:
fp.write('\n'.join(_A))
def lowerCAmelCase__ ( self):
return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer'))
def lowerCAmelCase__ ( self):
return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer'))
def lowerCAmelCase__ ( self):
return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer'))
def lowerCAmelCase__ ( self):
shutil.rmtree(self.tmpdirname)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = Dataset.from_dict(
{
'id': ['0', '1'],
'text': ['foo', 'bar'],
'title': ['Foo', 'Bar'],
'embeddings': [np.ones(self.retrieval_vector_size), 2 * np.ones(self.retrieval_vector_size)],
})
dataset.add_faiss_index('embeddings' , string_factory='Flat' , metric_type=faiss.METRIC_INNER_PRODUCT)
return dataset
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset()
SCREAMING_SNAKE_CASE_ = RagConfig(
retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , )
with patch('transformers.models.rag.retrieval_rag.load_dataset') as mock_load_dataset:
SCREAMING_SNAKE_CASE_ = dataset
SCREAMING_SNAKE_CASE_ = RagRetriever(
_A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , )
return retriever
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset()
SCREAMING_SNAKE_CASE_ = RagConfig(
retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='custom' , )
if from_disk:
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , 'dataset')
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , 'index.faiss')
dataset.get_index('embeddings').save(os.path.join(self.tmpdirname , 'index.faiss'))
dataset.drop_index('embeddings')
dataset.save_to_disk(os.path.join(self.tmpdirname , 'dataset'))
del dataset
SCREAMING_SNAKE_CASE_ = RagRetriever(
_A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , )
else:
SCREAMING_SNAKE_CASE_ = RagRetriever(
_A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , _A) , )
return retriever
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = Dataset.from_dict(
{
'id': ['0', '1'],
'text': ['foo', 'bar'],
'title': ['Foo', 'Bar'],
'embeddings': [np.ones(self.retrieval_vector_size + 1), 2 * np.ones(self.retrieval_vector_size + 1)],
})
dataset.add_faiss_index('embeddings' , string_factory='Flat' , metric_type=faiss.METRIC_INNER_PRODUCT)
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , 'hf_bert_base.hnswSQ8_correct_phi_128.c_index')
dataset.save_faiss_index('embeddings' , index_file_name + '.index.dpr')
pickle.dump(dataset['id'] , open(index_file_name + '.index_meta.dpr' , 'wb'))
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , 'psgs_w100.tsv.pkl')
SCREAMING_SNAKE_CASE_ = {sample['id']: [sample['text'], sample['title']] for sample in dataset}
pickle.dump(_A , open(_A , 'wb'))
SCREAMING_SNAKE_CASE_ = RagConfig(
retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='legacy' , index_path=self.tmpdirname , )
SCREAMING_SNAKE_CASE_ = RagRetriever(
_A , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer())
return retriever
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever()
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=_A)
self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size))
self.assertEqual(len(_A) , 2)
self.assertEqual(sorted(doc_dicts[0]) , ['embeddings', 'id', 'text', 'title'])
self.assertEqual(len(doc_dicts[0]['id']) , _A)
self.assertEqual(doc_dicts[0]['id'][0] , '1') # max inner product is reached with second doc
self.assertEqual(doc_dicts[1]['id'][0] , '0') # max inner product is reached with first doc
self.assertListEqual(doc_ids.tolist() , [[1], [0]])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever()
with tempfile.TemporaryDirectory() as tmp_dirname:
with patch('transformers.models.rag.retrieval_rag.load_dataset') as mock_load_dataset:
SCREAMING_SNAKE_CASE_ = self.get_dummy_dataset()
retriever.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(_A)
self.assertIsInstance(_A , _A)
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=1)
self.assertTrue(out is not None)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=_A)
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=_A)
self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size))
self.assertEqual(len(_A) , 2)
self.assertEqual(sorted(doc_dicts[0]) , ['embeddings', 'id', 'text', 'title'])
self.assertEqual(len(doc_dicts[0]['id']) , _A)
self.assertEqual(doc_dicts[0]['id'][0] , '1') # max inner product is reached with second doc
self.assertEqual(doc_dicts[1]['id'][0] , '0') # max inner product is reached with first doc
self.assertListEqual(doc_ids.tolist() , [[1], [0]])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=_A)
with tempfile.TemporaryDirectory() as tmp_dirname:
retriever.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(_A)
self.assertIsInstance(_A , _A)
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=1)
self.assertTrue(out is not None)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=_A)
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=_A)
self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size))
self.assertEqual(len(_A) , 2)
self.assertEqual(sorted(doc_dicts[0]) , ['embeddings', 'id', 'text', 'title'])
self.assertEqual(len(doc_dicts[0]['id']) , _A)
self.assertEqual(doc_dicts[0]['id'][0] , '1') # max inner product is reached with second doc
self.assertEqual(doc_dicts[1]['id'][0] , '0') # max inner product is reached with first doc
self.assertListEqual(doc_ids.tolist() , [[1], [0]])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=_A)
with tempfile.TemporaryDirectory() as tmp_dirname:
retriever.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(_A)
self.assertIsInstance(_A , _A)
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=1)
self.assertTrue(out is not None)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever()
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=_A)
self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size))
self.assertEqual(len(_A) , 2)
self.assertEqual(sorted(doc_dicts[0]) , ['text', 'title'])
self.assertEqual(len(doc_dicts[0]['text']) , _A)
self.assertEqual(doc_dicts[0]['text'][0] , 'bar') # max inner product is reached with second doc
self.assertEqual(doc_dicts[1]['text'][0] , 'foo') # max inner product is reached with first doc
self.assertListEqual(doc_ids.tolist() , [[1], [0]])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_dummy_legacy_index_retriever()
with tempfile.TemporaryDirectory() as tmp_dirname:
retriever.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = RagRetriever.from_pretrained(_A)
self.assertIsInstance(_A , _A)
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = retriever.retrieve(_A , n_docs=1)
self.assertTrue(out is not None)
@require_torch
@require_tokenizers
@require_sentencepiece
def lowerCAmelCase__ ( self):
import torch
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = self.get_dummy_canonical_hf_index_retriever()
SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]]
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = retriever(_A , _A , prefix=retriever.config.generator.prefix , n_docs=_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = (
out['context_input_ids'],
out['context_attention_mask'],
out['retrieved_doc_embeds'],
)
self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size))
self.assertIsInstance(_A , _A)
self.assertIsInstance(_A , _A)
self.assertIsInstance(_A , np.ndarray)
SCREAMING_SNAKE_CASE_ = retriever(
_A , _A , prefix=retriever.config.generator.prefix , n_docs=_A , return_tensors='pt' , )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = ( # noqa: F841
out['context_input_ids'],
out['context_attention_mask'],
out['retrieved_doc_embeds'],
out['doc_ids'],
)
self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size))
self.assertIsInstance(_A , torch.Tensor)
self.assertIsInstance(_A , torch.Tensor)
self.assertIsInstance(_A , torch.Tensor)
@require_torch
@require_tokenizers
@require_sentencepiece
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_dpr_ctx_encoder_tokenizer()
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = self.get_dummy_custom_hf_index_retriever(from_disk=_A)
retriever.set_ctx_encoder_tokenizer(_A)
SCREAMING_SNAKE_CASE_ = [[5, 7], [10, 11]]
SCREAMING_SNAKE_CASE_ = np.array(
[np.ones(self.retrieval_vector_size), -np.ones(self.retrieval_vector_size)] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = retriever(_A , _A , prefix=retriever.config.generator.prefix , n_docs=_A)
self.assertEqual(
len(_A) , 6) # check whether the retriever output consist of 6 attributes including tokenized docs
self.assertEqual(
all(k in out for k in ('tokenized_doc_ids', 'tokenized_doc_attention_mask')) , _A) # check for doc token related keys in dictionary.
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Optional[int] = {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
),
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Optional[int] = 'dpr'
def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1E-12 , _A=0 , _A="absolute" , _A = 0 , **_A , ):
super().__init__(pad_token_id=_A , **_A)
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = projection_dim
SCREAMING_SNAKE_CASE_ = position_embedding_type
| 620 | 1 |
import os
import warnings
from typing import List, Optional
from ...tokenization_utils_base import BatchEncoding
from ...utils import logging
from .configuration_rag import RagConfig
UpperCamelCase__ : Dict = logging.get_logger(__name__)
class __snake_case :
def __init__( self , _A , _A):
SCREAMING_SNAKE_CASE_ = question_encoder
SCREAMING_SNAKE_CASE_ = generator
SCREAMING_SNAKE_CASE_ = self.question_encoder
def lowerCAmelCase__ ( self , _A):
if os.path.isfile(_A):
raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""")
os.makedirs(_A , exist_ok=_A)
SCREAMING_SNAKE_CASE_ = os.path.join(_A , 'question_encoder_tokenizer')
SCREAMING_SNAKE_CASE_ = os.path.join(_A , 'generator_tokenizer')
self.question_encoder.save_pretrained(_A)
self.generator.save_pretrained(_A)
@classmethod
def lowerCAmelCase__ ( cls , _A , **_A):
# dynamically import AutoTokenizer
from ..auto.tokenization_auto import AutoTokenizer
SCREAMING_SNAKE_CASE_ = kwargs.pop('config' , _A)
if config is None:
SCREAMING_SNAKE_CASE_ = RagConfig.from_pretrained(_A)
SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(
_A , config=config.question_encoder , subfolder='question_encoder_tokenizer')
SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(
_A , config=config.generator , subfolder='generator_tokenizer')
return cls(question_encoder=_A , generator=_A)
def __call__( self , *_A , **_A):
return self.current_tokenizer(*_A , **_A)
def lowerCAmelCase__ ( self , *_A , **_A):
return self.generator.batch_decode(*_A , **_A)
def lowerCAmelCase__ ( self , *_A , **_A):
return self.generator.decode(*_A , **_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.question_encoder
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.generator
def lowerCAmelCase__ ( self , _A , _A = None , _A = None , _A = None , _A = "longest" , _A = None , _A = True , **_A , ):
warnings.warn(
'`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the '
'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` '
'context manager to prepare your targets. See the documentation of your specific tokenizer for more '
'details' , _A , )
if max_length is None:
SCREAMING_SNAKE_CASE_ = self.current_tokenizer.model_max_length
SCREAMING_SNAKE_CASE_ = self(
_A , add_special_tokens=_A , return_tensors=_A , max_length=_A , padding=_A , truncation=_A , **_A , )
if tgt_texts is None:
return model_inputs
# Process tgt_texts
if max_target_length is None:
SCREAMING_SNAKE_CASE_ = self.current_tokenizer.model_max_length
SCREAMING_SNAKE_CASE_ = self(
text_target=_A , add_special_tokens=_A , return_tensors=_A , padding=_A , max_length=_A , truncation=_A , **_A , )
SCREAMING_SNAKE_CASE_ = labels['input_ids']
return model_inputs
| 620 |
import pytest
import datasets
# Import fixture modules as plugins
UpperCamelCase__ : Union[str, Any] = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for item in items:
if any(marker in item.keywords for marker in ['integration', 'unit'] ):
continue
item.add_marker(pytest.mark.unit )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = tmp_path_factory.getbasetemp() / 'cache'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'datasets'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'metrics'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'modules'
monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads'
monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads' / 'extracted'
monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE , scope='session' )
def _UpperCAmelCase ( ):
"""simple docstring"""
datasets.disable_progress_bar()
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , _SCREAMING_SNAKE_CASE )
| 620 | 1 |
import logging
from pathlib import Path
import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = filter(lambda _SCREAMING_SNAKE_CASE : p.requires_grad , model.parameters() )
SCREAMING_SNAKE_CASE_ = sum([np.prod(p.size() ) for p in model_parameters] )
return params
UpperCamelCase__ : Tuple = logging.getLogger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
if metric == "rouge2":
SCREAMING_SNAKE_CASE_ = '{val_avg_rouge2:.4f}-{step_count}'
elif metric == "bleu":
SCREAMING_SNAKE_CASE_ = '{val_avg_bleu:.4f}-{step_count}'
elif metric == "em":
SCREAMING_SNAKE_CASE_ = '{val_avg_em:.4f}-{step_count}'
else:
raise NotImplementedError(
f"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this"""
' function.' )
SCREAMING_SNAKE_CASE_ = ModelCheckpoint(
dirpath=_SCREAMING_SNAKE_CASE , filename=_SCREAMING_SNAKE_CASE , monitor=f"""val_{metric}""" , mode='max' , save_top_k=3 , every_n_epochs=1 , )
return checkpoint_callback
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
return EarlyStopping(
monitor=f"""val_{metric}""" , mode='min' if 'loss' in metric else 'max' , patience=_SCREAMING_SNAKE_CASE , verbose=_SCREAMING_SNAKE_CASE , )
class __snake_case ( pl.Callback ):
def lowerCAmelCase__ ( self , _A , _A):
SCREAMING_SNAKE_CASE_ = {f"""lr_group_{i}""": param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups)}
pl_module.logger.log_metrics(_A)
@rank_zero_only
def lowerCAmelCase__ ( self , _A , _A , _A , _A=True):
logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""")
SCREAMING_SNAKE_CASE_ = trainer.callback_metrics
trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']})
# Log results
SCREAMING_SNAKE_CASE_ = Path(pl_module.hparams.output_dir)
if type_path == "test":
SCREAMING_SNAKE_CASE_ = od / 'test_results.txt'
SCREAMING_SNAKE_CASE_ = od / 'test_generations.txt'
else:
# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
# If people want this it will be easy enough to add back.
SCREAMING_SNAKE_CASE_ = od / f"""{type_path}_results/{trainer.global_step:05d}.txt"""
SCREAMING_SNAKE_CASE_ = od / f"""{type_path}_generations/{trainer.global_step:05d}.txt"""
results_file.parent.mkdir(exist_ok=_A)
generations_file.parent.mkdir(exist_ok=_A)
with open(_A , 'a+') as writer:
for key in sorted(_A):
if key in ["log", "progress_bar", "preds"]:
continue
SCREAMING_SNAKE_CASE_ = metrics[key]
if isinstance(_A , torch.Tensor):
SCREAMING_SNAKE_CASE_ = val.item()
SCREAMING_SNAKE_CASE_ = f"""{key}: {val:.6f}\n"""
writer.write(_A)
if not save_generations:
return
if "preds" in metrics:
SCREAMING_SNAKE_CASE_ = '\n'.join(metrics['preds'])
generations_file.open('w+').write(_A)
@rank_zero_only
def lowerCAmelCase__ ( self , _A , _A):
try:
SCREAMING_SNAKE_CASE_ = pl_module.model.model.num_parameters()
except AttributeError:
SCREAMING_SNAKE_CASE_ = pl_module.model.num_parameters()
SCREAMING_SNAKE_CASE_ = count_trainable_parameters(_A)
# mp stands for million parameters
trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6})
@rank_zero_only
def lowerCAmelCase__ ( self , _A , _A):
save_json(pl_module.metrics , pl_module.metrics_save_path)
return self._write_logs(_A , _A , 'test')
@rank_zero_only
def lowerCAmelCase__ ( self , _A , _A):
save_json(pl_module.metrics , pl_module.metrics_save_path)
# Uncommenting this will save val generations
# return self._write_logs(trainer, pl_module, "valid")
| 620 |
from typing import List
import numpy as np
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {key: len(_SCREAMING_SNAKE_CASE ) for key, value in gen_kwargs.items() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
'Sharding is ambiguous for this dataset: '
+ 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
+ '\n'.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items() )
+ '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
+ 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
) )
SCREAMING_SNAKE_CASE_ = max(lists_lengths.values() , default=0 )
return max(1 , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for group_idx in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
SCREAMING_SNAKE_CASE_ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
SCREAMING_SNAKE_CASE_ = range(_SCREAMING_SNAKE_CASE , start + num_shards_to_add )
shards_indices_per_group.append(_SCREAMING_SNAKE_CASE )
return shards_indices_per_group
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = _number_of_shards_in_gen_kwargs(_SCREAMING_SNAKE_CASE )
if num_shards == 1:
return [dict(_SCREAMING_SNAKE_CASE )]
else:
SCREAMING_SNAKE_CASE_ = _distribute_shards(num_shards=_SCREAMING_SNAKE_CASE , max_num_jobs=_SCREAMING_SNAKE_CASE )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(_SCREAMING_SNAKE_CASE ) )
]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[dict] ):
"""simple docstring"""
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key] , _SCREAMING_SNAKE_CASE )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : np.random.Generator , _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {len(_SCREAMING_SNAKE_CASE ) for value in gen_kwargs.values() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
SCREAMING_SNAKE_CASE_ = {}
for size in list_sizes:
SCREAMING_SNAKE_CASE_ = list(range(_SCREAMING_SNAKE_CASE ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
SCREAMING_SNAKE_CASE_ = dict(_SCREAMING_SNAKE_CASE )
for key, value in shuffled_kwargs.items():
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = [value[i] for i in indices_per_size[len(_SCREAMING_SNAKE_CASE )]]
return shuffled_kwargs
| 620 | 1 |
import os
import unittest
from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : List[Any] = PhobertTokenizer
__lowerCAmelCase : int = False
def lowerCAmelCase__ ( self):
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
SCREAMING_SNAKE_CASE_ = ['T@@', 'i', 'I', 'R@@', 'r', 'e@@']
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = ['#version: 0.2', 'l à</w>']
SCREAMING_SNAKE_CASE_ = {'unk_token': '<unk>'}
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = 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 lowerCAmelCase__ ( self , **_A):
kwargs.update(self.special_tokens_map)
return PhobertTokenizer.from_pretrained(self.tmpdirname , **_A)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = 'Tôi là VinAI Research'
SCREAMING_SNAKE_CASE_ = 'T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>'
return input_text, output_text
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map)
SCREAMING_SNAKE_CASE_ = 'Tôi là VinAI Research'
SCREAMING_SNAKE_CASE_ = 'T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'.split()
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(_A)
print(_A)
self.assertListEqual(_A , _A)
SCREAMING_SNAKE_CASE_ = tokens + [tokenizer.unk_token]
SCREAMING_SNAKE_CASE_ = [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)
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
UpperCamelCase__ : List[str] = {
"microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json",
# See all BioGPT models at https://huggingface.co/models?filter=biogpt
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Any = 'biogpt'
def __init__( self , _A=42384 , _A=1024 , _A=24 , _A=16 , _A=4096 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1024 , _A=0.0_2 , _A=1E-12 , _A=True , _A=True , _A=0.0 , _A=0.0 , _A=1 , _A=0 , _A=2 , **_A , ):
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = scale_embedding
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = layerdrop
SCREAMING_SNAKE_CASE_ = activation_dropout
super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A)
| 620 | 1 |
import argparse
from pathlib import Path
import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version
from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging
if version.parse(fairseq.__version__) < version.parse("0.12.2"):
raise Exception("requires fairseq >= 0.12.2")
if version.parse(fairseq.__version__) > version.parse("2"):
raise Exception("requires fairseq < v2")
logging.set_verbosity_info()
UpperCamelCase__ : Any = logging.get_logger(__name__)
UpperCamelCase__ : Union[str, Any] = "Hello, World!"
UpperCamelCase__ : str = "en_XX"
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : bool ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = Path('data_bin' )
SCREAMING_SNAKE_CASE_ = FairseqXmodModel.from_pretrained(
model_name_or_path=str(Path(_SCREAMING_SNAKE_CASE ).parent ) , checkpoint_file=Path(_SCREAMING_SNAKE_CASE ).name , _name='xmod_base' , arch='xmod_base' , task='multilingual_masked_lm' , data_name_or_path=str(_SCREAMING_SNAKE_CASE ) , bpe='sentencepiece' , sentencepiece_model=str(Path(_SCREAMING_SNAKE_CASE ).parent / 'sentencepiece.bpe.model' ) , src_dict=str(data_dir / 'dict.txt' ) , )
xmod.eval() # disable dropout
print(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.sentence_encoder
SCREAMING_SNAKE_CASE_ = XmodConfig(
vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , 'bottleneck' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , )
if classification_head:
SCREAMING_SNAKE_CASE_ = xmod.model.classification_heads['mnli'].out_proj.weight.shape[0]
print('Our X-MOD config:' , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = XmodForSequenceClassification(_SCREAMING_SNAKE_CASE ) if classification_head else XmodForMaskedLM(_SCREAMING_SNAKE_CASE )
model.eval()
# Now let's copy all the weights.
# Embeddings
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.embed_tokens.weight
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.embed_positions.weight
SCREAMING_SNAKE_CASE_ = torch.zeros_like(
model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them.
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.layernorm_embedding.weight
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.layernorm_embedding.bias
for i in range(config.num_hidden_layers ):
# Encoder: start of layer
SCREAMING_SNAKE_CASE_ = model.roberta.encoder.layer[i]
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.layers[i]
# self attention
SCREAMING_SNAKE_CASE_ = layer.attention.self
if not (
xmod_layer.self_attn.k_proj.weight.data.shape
== xmod_layer.self_attn.q_proj.weight.data.shape
== xmod_layer.self_attn.v_proj.weight.data.shape
== torch.Size((config.hidden_size, config.hidden_size) )
):
raise AssertionError('Dimensions of self-attention weights do not match.' )
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.q_proj.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.q_proj.bias
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.k_proj.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.k_proj.bias
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.v_proj.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.v_proj.bias
# self-attention output
SCREAMING_SNAKE_CASE_ = layer.attention.output
if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
raise AssertionError('Dimensions of self-attention output weights do not match.' )
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.out_proj.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn.out_proj.bias
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn_layer_norm.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.self_attn_layer_norm.bias
# intermediate
SCREAMING_SNAKE_CASE_ = layer.intermediate
if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
raise AssertionError('Dimensions of intermediate weights do not match.' )
SCREAMING_SNAKE_CASE_ = xmod_layer.fca.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.fca.bias
# output
SCREAMING_SNAKE_CASE_ = layer.output
if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
raise AssertionError('Dimensions of feed-forward weights do not match.' )
SCREAMING_SNAKE_CASE_ = xmod_layer.fca.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.fca.bias
SCREAMING_SNAKE_CASE_ = xmod_layer.final_layer_norm.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.final_layer_norm.bias
if bert_output.adapter_layer_norm is not None:
SCREAMING_SNAKE_CASE_ = xmod_layer.adapter_layer_norm.weight
SCREAMING_SNAKE_CASE_ = xmod_layer.adapter_layer_norm.bias
if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ):
raise AssertionError('Lists of language adapters do not match.' )
for lang_code, adapter in xmod_layer.adapter_modules.items():
SCREAMING_SNAKE_CASE_ = bert_output.adapter_modules[lang_code]
SCREAMING_SNAKE_CASE_ = xmod_layer.adapter_modules[lang_code]
SCREAMING_SNAKE_CASE_ = from_adapter.fca.weight
SCREAMING_SNAKE_CASE_ = from_adapter.fca.bias
SCREAMING_SNAKE_CASE_ = from_adapter.fca.weight
SCREAMING_SNAKE_CASE_ = from_adapter.fca.bias
# end of layer
if xmod_sent_encoder.layer_norm is not None:
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.layer_norm.weight
SCREAMING_SNAKE_CASE_ = xmod_sent_encoder.layer_norm.bias
if classification_head:
SCREAMING_SNAKE_CASE_ = xmod.model.classification_heads['mnli'].dense.weight
SCREAMING_SNAKE_CASE_ = xmod.model.classification_heads['mnli'].dense.bias
SCREAMING_SNAKE_CASE_ = xmod.model.classification_heads['mnli'].out_proj.weight
SCREAMING_SNAKE_CASE_ = xmod.model.classification_heads['mnli'].out_proj.bias
else:
# LM Head
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.lm_head.dense.weight
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.lm_head.dense.bias
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.lm_head.layer_norm.weight
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.lm_head.layer_norm.bias
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.lm_head.weight
SCREAMING_SNAKE_CASE_ = xmod.model.encoder.lm_head.bias
# Let's check that we get the same results.
SCREAMING_SNAKE_CASE_ = xmod.encode(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) # batch of size 1
model.roberta.set_default_language(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = model(_SCREAMING_SNAKE_CASE )[0]
if classification_head:
SCREAMING_SNAKE_CASE_ = xmod.model.classification_heads['mnli'](xmod.extract_features(_SCREAMING_SNAKE_CASE ) )
else:
SCREAMING_SNAKE_CASE_ = xmod.model(_SCREAMING_SNAKE_CASE , lang_id=[SAMPLE_LANGUAGE] )[0]
print(our_output.shape , their_output.shape )
SCREAMING_SNAKE_CASE_ = torch.max(torch.abs(our_output - their_output ) ).item()
print(f"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7
SCREAMING_SNAKE_CASE_ = torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 )
print('Do both models output the same tensors?' , '🔥' if success else '💩' )
if not success:
raise Exception('Something went wRoNg' )
Path(_SCREAMING_SNAKE_CASE ).mkdir(parents=_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : Optional[int] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--xmod_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."
)
parser.add_argument(
"--classification_head", action="store_true", help="Whether to convert a final classification head."
)
UpperCamelCase__ : Dict = parser.parse_args()
convert_xmod_checkpoint_to_pytorch(
args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
)
| 620 |
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A , _A , _A = None , ):
super().__init__()
self.register_modules(transformer=_A , vae=_A , scheduler=_A)
# create a imagenet -> id dictionary for easier use
SCREAMING_SNAKE_CASE_ = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(','):
SCREAMING_SNAKE_CASE_ = int(_A)
SCREAMING_SNAKE_CASE_ = dict(sorted(self.labels.items()))
def lowerCAmelCase__ ( self , _A):
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = list(_A)
for l in label:
if l not in self.labels:
raise ValueError(
f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""")
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self , _A , _A = 4.0 , _A = None , _A = 50 , _A = "pil" , _A = True , ):
SCREAMING_SNAKE_CASE_ = len(_A)
SCREAMING_SNAKE_CASE_ = self.transformer.config.sample_size
SCREAMING_SNAKE_CASE_ = self.transformer.config.in_channels
SCREAMING_SNAKE_CASE_ = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=_A , device=self.device , dtype=self.transformer.dtype , )
SCREAMING_SNAKE_CASE_ = torch.cat([latents] * 2) if guidance_scale > 1 else latents
SCREAMING_SNAKE_CASE_ = torch.tensor(_A , device=self.device).reshape(-1)
SCREAMING_SNAKE_CASE_ = torch.tensor([1000] * batch_size , device=self.device)
SCREAMING_SNAKE_CASE_ = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(_A)
for t in self.progress_bar(self.scheduler.timesteps):
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ = latent_model_input[: len(_A) // 2]
SCREAMING_SNAKE_CASE_ = torch.cat([half, half] , dim=0)
SCREAMING_SNAKE_CASE_ = self.scheduler.scale_model_input(_A , _A)
SCREAMING_SNAKE_CASE_ = t
if not torch.is_tensor(_A):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
SCREAMING_SNAKE_CASE_ = latent_model_input.device.type == 'mps'
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = torch.floataa if is_mps else torch.floataa
else:
SCREAMING_SNAKE_CASE_ = torch.intaa if is_mps else torch.intaa
SCREAMING_SNAKE_CASE_ = torch.tensor([timesteps] , dtype=_A , device=latent_model_input.device)
elif len(timesteps.shape) == 0:
SCREAMING_SNAKE_CASE_ = timesteps[None].to(latent_model_input.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
SCREAMING_SNAKE_CASE_ = timesteps.expand(latent_model_input.shape[0])
# predict noise model_output
SCREAMING_SNAKE_CASE_ = self.transformer(
_A , timestep=_A , class_labels=_A).sample
# perform guidance
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , len(_A) // 2 , dim=0)
SCREAMING_SNAKE_CASE_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
SCREAMING_SNAKE_CASE_ = torch.cat([half_eps, half_eps] , dim=0)
SCREAMING_SNAKE_CASE_ = torch.cat([eps, rest] , dim=1)
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , _A , dim=1)
else:
SCREAMING_SNAKE_CASE_ = noise_pred
# compute previous image: x_t -> x_t-1
SCREAMING_SNAKE_CASE_ = self.scheduler.step(_A , _A , _A).prev_sample
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = latent_model_input.chunk(2 , dim=0)
else:
SCREAMING_SNAKE_CASE_ = latent_model_input
SCREAMING_SNAKE_CASE_ = 1 / self.vae.config.scaling_factor * latents
SCREAMING_SNAKE_CASE_ = self.vae.decode(_A).sample
SCREAMING_SNAKE_CASE_ = (samples / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
SCREAMING_SNAKE_CASE_ = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_A)
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=_A)
| 620 | 1 |
from __future__ import annotations
import math
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = str(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = [n]
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ):
list_nums.append(int(str_num[i:] ) )
list_nums.append(int(str_num[:-i] ) )
return list_nums
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if len(str(_SCREAMING_SNAKE_CASE ) ) > 3:
if not is_prime(int(str(_SCREAMING_SNAKE_CASE )[-3:] ) ) or not is_prime(int(str(_SCREAMING_SNAKE_CASE )[:3] ) ):
return False
return True
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 11 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 13
while len(_SCREAMING_SNAKE_CASE ) != count:
if validate(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = list_truncated_nums(_SCREAMING_SNAKE_CASE )
if all(is_prime(_SCREAMING_SNAKE_CASE ) for i in list_nums ):
list_truncated_primes.append(_SCREAMING_SNAKE_CASE )
num += 2
return list_truncated_primes
def _UpperCAmelCase ( ):
"""simple docstring"""
return sum(compute_truncated_primes(11 ) )
if __name__ == "__main__":
print(F'{sum(compute_truncated_primes(11)) = }')
| 620 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class __snake_case :
def __init__( self , _A , _A , _A , _A , _A , _A=0.2 , _A=0.2):
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = conva_get[:2]
SCREAMING_SNAKE_CASE_ = conva_get[2]
SCREAMING_SNAKE_CASE_ = size_pa
SCREAMING_SNAKE_CASE_ = rate_w
SCREAMING_SNAKE_CASE_ = rate_t
SCREAMING_SNAKE_CASE_ = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5)
for i in range(self.conva[1])
]
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.conva[1]) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
def lowerCAmelCase__ ( self , _A):
# save model dict with pickle
SCREAMING_SNAKE_CASE_ = {
'num_bp1': self.num_bpa,
'num_bp2': self.num_bpa,
'num_bp3': self.num_bpa,
'conv1': self.conva,
'step_conv1': self.step_conva,
'size_pooling1': self.size_poolinga,
'rate_weight': self.rate_weight,
'rate_thre': self.rate_thre,
'w_conv1': self.w_conva,
'wkj': self.wkj,
'vji': self.vji,
'thre_conv1': self.thre_conva,
'thre_bp2': self.thre_bpa,
'thre_bp3': self.thre_bpa,
}
with open(_A , 'wb') as f:
pickle.dump(_A , _A)
print(f"""Model saved: {save_path}""")
@classmethod
def lowerCAmelCase__ ( cls , _A):
# read saved model
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = pickle.load(_A) # noqa: S301
SCREAMING_SNAKE_CASE_ = model_dic.get('conv1')
conv_get.append(model_dic.get('step_conv1'))
SCREAMING_SNAKE_CASE_ = model_dic.get('size_pooling1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp3')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_weight')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_thre')
# create model instance
SCREAMING_SNAKE_CASE_ = CNN(_A , _A , _A , _A , _A , _A , _A)
# modify model parameter
SCREAMING_SNAKE_CASE_ = model_dic.get('w_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('wkj')
SCREAMING_SNAKE_CASE_ = model_dic.get('vji')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp3')
return conv_ins
def lowerCAmelCase__ ( self , _A):
return 1 / (1 + np.exp(-1 * x))
def lowerCAmelCase__ ( self , _A):
return round(_A , 3)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
# convolution process
SCREAMING_SNAKE_CASE_ = convs[0]
SCREAMING_SNAKE_CASE_ = convs[1]
SCREAMING_SNAKE_CASE_ = np.shape(_A)[0]
# get the data slice of original image data, data_focus
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , size_data - size_conv + 1 , _A):
for j_focus in range(0 , size_data - size_conv + 1 , _A):
SCREAMING_SNAKE_CASE_ = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(_A)
# calculate the feature map of every single kernel, and saved as list of matrix
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = int((size_data - size_conv) / conv_step + 1)
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(len(_A)):
SCREAMING_SNAKE_CASE_ = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map]))
- thre_convs[i_map]
)
featuremap.append(self.sig(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(
_A , _A)
data_featuremap.append(_A)
# expanding the data slice to One dimenssion
SCREAMING_SNAKE_CASE_ = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(_A))
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return focus_list, data_featuremap
def lowerCAmelCase__ ( self , _A , _A , _A="average_pool"):
# pooling process
SCREAMING_SNAKE_CASE_ = len(featuremaps[0])
SCREAMING_SNAKE_CASE_ = int(size_map / size_pooling)
SCREAMING_SNAKE_CASE_ = []
for i_map in range(len(_A)):
SCREAMING_SNAKE_CASE_ = featuremaps[i_map]
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , _A , _A):
for j_focus in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(_A))
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(_A , _A)
featuremap_pooled.append(_A)
return featuremap_pooled
def lowerCAmelCase__ ( self , _A):
# expanding three dimension data to one dimension list
SCREAMING_SNAKE_CASE_ = []
for i in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.shape(data[i])
SCREAMING_SNAKE_CASE_ = data[i].reshape(1 , shapes[0] * shapes[1])
SCREAMING_SNAKE_CASE_ = data_listed.getA().tolist()[0]
data_expanded.extend(_A)
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return data_expanded
def lowerCAmelCase__ ( self , _A):
# expanding matrix to one dimension list
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = data_mat.reshape(1 , shapes[0] * shapes[1])
return data_expanded
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = np.ones((size_map, size_map))
for i in range(0 , _A , _A):
for j in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = pd_pool[
i_pool
]
SCREAMING_SNAKE_CASE_ = i_pool + 1
SCREAMING_SNAKE_CASE_ = np.multiply(
_A , np.multiply(out_map[i_map] , (1 - out_map[i_map])))
pd_all.append(_A)
return pd_all
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , _A=bool):
# model traning
print('----------------------Start Training-------------------------')
print((' - - Shape: Train_Data ', np.shape(_A)))
print((' - - Shape: Teach_Data ', np.shape(_A)))
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 10000
while rp < n_repeat and mse >= error_accuracy:
SCREAMING_SNAKE_CASE_ = 0
print(f"""-------------Learning Time {rp}--------------""")
for p in range(len(_A)):
# print('------------Learning Image: %d--------------'%p)
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_train[p])
SCREAMING_SNAKE_CASE_ = np.asarray(datas_teach[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.wkj.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
SCREAMING_SNAKE_CASE_ = np.multiply(
(data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.multiply(
np.dot(_A , self.wkj) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji)
SCREAMING_SNAKE_CASE_ = pd_i_all / (self.size_poolinga * self.size_poolinga)
SCREAMING_SNAKE_CASE_ = pd_conva_pooled.T.getA().tolist()
SCREAMING_SNAKE_CASE_ = self._calculate_gradient_from_pool(
_A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1]):
SCREAMING_SNAKE_CASE_ = self._expand_mat(pd_conva_all[k_conv])
SCREAMING_SNAKE_CASE_ = self.rate_weight * np.dot(_A , _A)
SCREAMING_SNAKE_CASE_ = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]))
SCREAMING_SNAKE_CASE_ = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv]) * self.rate_thre
)
# all connected layer
SCREAMING_SNAKE_CASE_ = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.vji + pd_j_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_k_all * self.rate_thre
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
SCREAMING_SNAKE_CASE_ = np.sum(abs(data_teach - bp_outa))
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
SCREAMING_SNAKE_CASE_ = rp + 1
SCREAMING_SNAKE_CASE_ = error_count / patterns
all_mse.append(_A)
def draw_error():
SCREAMING_SNAKE_CASE_ = [error_accuracy for i in range(int(n_repeat * 1.2))]
plt.plot(_A , '+-')
plt.plot(_A , 'r--')
plt.xlabel('Learning Times')
plt.ylabel('All_mse')
plt.grid(_A , alpha=0.5)
plt.show()
print('------------------Training Complished---------------------')
print((' - - Training epoch: ', rp, f""" - - Mse: {mse:.6f}"""))
if draw_e:
draw_error()
return mse
def lowerCAmelCase__ ( self , _A):
# model predict
SCREAMING_SNAKE_CASE_ = []
print('-------------------Start Testing-------------------------')
print((' - - Shape: Test_Data ', np.shape(_A)))
for p in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_test[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = bp_outa * self.vji.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = bp_outa * self.wkj.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
produce_out.extend(bp_outa.getA().tolist())
SCREAMING_SNAKE_CASE_ = [list(map(self.do_round , _A)) for each in produce_out]
return np.asarray(_A)
def lowerCAmelCase__ ( self , _A):
# return the data of image after convoluting process so we can check it out
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 620 | 1 |
import os
import zipfile
import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int=7 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = None
if token is not None:
SCREAMING_SNAKE_CASE_ = {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}
# The id of a workflow (not of a workflow run)
SCREAMING_SNAKE_CASE_ = '636036'
SCREAMING_SNAKE_CASE_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""
SCREAMING_SNAKE_CASE_ = requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).json()
return result["workflow_runs"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_daily_ci_runs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = None
for workflow_run in workflow_runs:
if workflow_run["status"] == "completed":
SCREAMING_SNAKE_CASE_ = workflow_run['id']
break
return workflow_run_id
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE )
if workflow_run_id is not None:
SCREAMING_SNAKE_CASE_ = get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
for artifact_name in artifact_names:
if artifact_name in artifacts_links:
SCREAMING_SNAKE_CASE_ = artifacts_links[artifact_name]
download_artifact(
artifact_name=_SCREAMING_SNAKE_CASE , artifact_url=_SCREAMING_SNAKE_CASE , output_dir=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
for artifact_name in artifact_names:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{artifact_name}.zip""" )
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = {}
with zipfile.ZipFile(_SCREAMING_SNAKE_CASE ) as z:
for filename in z.namelist():
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
# read the file
with z.open(_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ = f.read().decode('UTF-8' )
return results
| 620 |
import os
import zipfile
import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int=7 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = None
if token is not None:
SCREAMING_SNAKE_CASE_ = {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}
# The id of a workflow (not of a workflow run)
SCREAMING_SNAKE_CASE_ = '636036'
SCREAMING_SNAKE_CASE_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""
SCREAMING_SNAKE_CASE_ = requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).json()
return result["workflow_runs"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_daily_ci_runs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = None
for workflow_run in workflow_runs:
if workflow_run["status"] == "completed":
SCREAMING_SNAKE_CASE_ = workflow_run['id']
break
return workflow_run_id
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE )
if workflow_run_id is not None:
SCREAMING_SNAKE_CASE_ = get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
for artifact_name in artifact_names:
if artifact_name in artifacts_links:
SCREAMING_SNAKE_CASE_ = artifacts_links[artifact_name]
download_artifact(
artifact_name=_SCREAMING_SNAKE_CASE , artifact_url=_SCREAMING_SNAKE_CASE , output_dir=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
for artifact_name in artifact_names:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{artifact_name}.zip""" )
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = {}
with zipfile.ZipFile(_SCREAMING_SNAKE_CASE ) as z:
for filename in z.namelist():
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
# read the file
with z.open(_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ = f.read().decode('UTF-8' )
return results
| 620 | 1 |
import argparse
import collections
import json
import os
import re
import string
import sys
import numpy as np
UpperCamelCase__ : Dict = re.compile(r"\b(a|an|the)\b", re.UNICODE)
UpperCamelCase__ : Optional[int] = None
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' )
parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.' )
parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.' )
parser.add_argument(
'--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).' )
parser.add_argument(
'--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.' )
parser.add_argument(
'--na-prob-thresh' , '-t' , type=_SCREAMING_SNAKE_CASE , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , )
parser.add_argument(
'--out-image-dir' , '-p' , metavar='out_images' , default=_SCREAMING_SNAKE_CASE , help='Save precision-recall curves to directory.' )
parser.add_argument('--verbose' , '-v' , action='store_true' )
if len(sys.argv ) == 1:
parser.print_help()
sys.exit(1 )
return parser.parse_args()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {}
for article in dataset:
for p in article["paragraphs"]:
for qa in p["qas"]:
SCREAMING_SNAKE_CASE_ = bool(qa['answers']['text'] )
return qid_to_has_ans
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
def remove_articles(_SCREAMING_SNAKE_CASE : Union[str, Any] ):
return ARTICLES_REGEX.sub(' ' , _SCREAMING_SNAKE_CASE )
def white_space_fix(_SCREAMING_SNAKE_CASE : str ):
return " ".join(text.split() )
def remove_punc(_SCREAMING_SNAKE_CASE : List[str] ):
SCREAMING_SNAKE_CASE_ = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(_SCREAMING_SNAKE_CASE : str ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(_SCREAMING_SNAKE_CASE ) ) ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
if not s:
return []
return normalize_answer(_SCREAMING_SNAKE_CASE ).split()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
return int(normalize_answer(_SCREAMING_SNAKE_CASE ) == normalize_answer(_SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_tokens(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = get_tokens(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = collections.Counter(_SCREAMING_SNAKE_CASE ) & collections.Counter(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = sum(common.values() )
if len(_SCREAMING_SNAKE_CASE ) == 0 or len(_SCREAMING_SNAKE_CASE ) == 0:
# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
return int(gold_toks == pred_toks )
if num_same == 0:
return 0
SCREAMING_SNAKE_CASE_ = 1.0 * num_same / len(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 1.0 * num_same / len(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = (2 * precision * recall) / (precision + recall)
return fa
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = {}
for article in dataset:
for p in article["paragraphs"]:
for qa in p["qas"]:
SCREAMING_SNAKE_CASE_ = qa['id']
SCREAMING_SNAKE_CASE_ = [t for t in qa['answers']['text'] if normalize_answer(_SCREAMING_SNAKE_CASE )]
if not gold_answers:
# For unanswerable questions, only correct answer is empty string
SCREAMING_SNAKE_CASE_ = ['']
if qid not in preds:
print(f"""Missing prediction for {qid}""" )
continue
SCREAMING_SNAKE_CASE_ = preds[qid]
# Take max over all gold answers
SCREAMING_SNAKE_CASE_ = max(compute_exact(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for a in gold_answers )
SCREAMING_SNAKE_CASE_ = max(compute_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for a in gold_answers )
return exact_scores, fa_scores
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {}
for qid, s in scores.items():
SCREAMING_SNAKE_CASE_ = na_probs[qid] > na_prob_thresh
if pred_na:
SCREAMING_SNAKE_CASE_ = float(not qid_to_has_ans[qid] )
else:
SCREAMING_SNAKE_CASE_ = s
return new_scores
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[Any]=None ):
"""simple docstring"""
if not qid_list:
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE )
return collections.OrderedDict(
[
('exact', 100.0 * sum(exact_scores.values() ) / total),
('f1', 100.0 * sum(fa_scores.values() ) / total),
('total', total),
] )
else:
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE )
return collections.OrderedDict(
[
('exact', 100.0 * sum(exact_scores[k] for k in qid_list ) / total),
('f1', 100.0 * sum(fa_scores[k] for k in qid_list ) / total),
('total', total),
] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
for k in new_eval:
SCREAMING_SNAKE_CASE_ = new_eval[k]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
plt.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , color='b' , alpha=0.2 , where='post' )
plt.fill_between(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , step='post' , alpha=0.2 , color='b' )
plt.xlabel('Recall' )
plt.ylabel('Precision' )
plt.xlim([0.0, 1.05] )
plt.ylim([0.0, 1.05] )
plt.title(_SCREAMING_SNAKE_CASE )
plt.savefig(_SCREAMING_SNAKE_CASE )
plt.clf()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any=None , _SCREAMING_SNAKE_CASE : List[Any]=None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : na_probs[k] )
SCREAMING_SNAKE_CASE_ = 0.0
SCREAMING_SNAKE_CASE_ = 1.0
SCREAMING_SNAKE_CASE_ = 0.0
SCREAMING_SNAKE_CASE_ = [1.0]
SCREAMING_SNAKE_CASE_ = [0.0]
SCREAMING_SNAKE_CASE_ = 0.0
for i, qid in enumerate(_SCREAMING_SNAKE_CASE ):
if qid_to_has_ans[qid]:
true_pos += scores[qid]
SCREAMING_SNAKE_CASE_ = true_pos / float(i + 1 )
SCREAMING_SNAKE_CASE_ = true_pos / float(_SCREAMING_SNAKE_CASE )
if i == len(_SCREAMING_SNAKE_CASE ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
# i.e., if we can put a threshold after this point
avg_prec += cur_p * (cur_r - recalls[-1])
precisions.append(_SCREAMING_SNAKE_CASE )
recalls.append(_SCREAMING_SNAKE_CASE )
if out_image:
plot_pr_curve(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
return {"ap": 100.0 * avg_prec}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
if out_image_dir and not os.path.exists(_SCREAMING_SNAKE_CASE ):
os.makedirs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = sum(1 for v in qid_to_has_ans.values() if v )
if num_true_pos == 0:
return
SCREAMING_SNAKE_CASE_ = make_precision_recall_eval(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , out_image=os.path.join(_SCREAMING_SNAKE_CASE , 'pr_exact.png' ) , title='Precision-Recall curve for Exact Match score' , )
SCREAMING_SNAKE_CASE_ = make_precision_recall_eval(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , out_image=os.path.join(_SCREAMING_SNAKE_CASE , 'pr_f1.png' ) , title='Precision-Recall curve for F1 score' , )
SCREAMING_SNAKE_CASE_ = {k: float(_SCREAMING_SNAKE_CASE ) for k, v in qid_to_has_ans.items()}
SCREAMING_SNAKE_CASE_ = make_precision_recall_eval(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , out_image=os.path.join(_SCREAMING_SNAKE_CASE , 'pr_oracle.png' ) , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , )
merge_eval(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'pr_exact' )
merge_eval(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'pr_f1' )
merge_eval(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'pr_oracle' )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if not qid_list:
return
SCREAMING_SNAKE_CASE_ = [na_probs[k] for k in qid_list]
SCREAMING_SNAKE_CASE_ = np.ones_like(_SCREAMING_SNAKE_CASE ) / float(len(_SCREAMING_SNAKE_CASE ) )
plt.hist(_SCREAMING_SNAKE_CASE , weights=_SCREAMING_SNAKE_CASE , bins=20 , range=(0.0, 1.0) )
plt.xlabel('Model probability of no-answer' )
plt.ylabel('Proportion of dataset' )
plt.title(f"""Histogram of no-answer probability: {name}""" )
plt.savefig(os.path.join(_SCREAMING_SNAKE_CASE , f"""na_prob_hist_{name}.png""" ) )
plt.clf()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] )
SCREAMING_SNAKE_CASE_ = num_no_ans
SCREAMING_SNAKE_CASE_ = cur_score
SCREAMING_SNAKE_CASE_ = 0.0
SCREAMING_SNAKE_CASE_ = sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : na_probs[k] )
for i, qid in enumerate(_SCREAMING_SNAKE_CASE ):
if qid not in scores:
continue
if qid_to_has_ans[qid]:
SCREAMING_SNAKE_CASE_ = scores[qid]
else:
if preds[qid]:
SCREAMING_SNAKE_CASE_ = -1
else:
SCREAMING_SNAKE_CASE_ = 0
cur_score += diff
if cur_score > best_score:
SCREAMING_SNAKE_CASE_ = cur_score
SCREAMING_SNAKE_CASE_ = na_probs[qid]
return 100.0 * best_score / len(_SCREAMING_SNAKE_CASE ), best_thresh
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = find_best_thresh(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = find_best_thresh(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = best_exact
SCREAMING_SNAKE_CASE_ = exact_thresh
SCREAMING_SNAKE_CASE_ = best_fa
SCREAMING_SNAKE_CASE_ = fa_thresh
def _UpperCAmelCase ( ):
"""simple docstring"""
with open(OPTS.data_file ) as f:
SCREAMING_SNAKE_CASE_ = json.load(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = dataset_json['data']
with open(OPTS.pred_file ) as f:
SCREAMING_SNAKE_CASE_ = json.load(_SCREAMING_SNAKE_CASE )
if OPTS.na_prob_file:
with open(OPTS.na_prob_file ) as f:
SCREAMING_SNAKE_CASE_ = json.load(_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = {k: 0.0 for k in preds}
SCREAMING_SNAKE_CASE_ = make_qid_to_has_ans(_SCREAMING_SNAKE_CASE ) # maps qid to True/False
SCREAMING_SNAKE_CASE_ = [k for k, v in qid_to_has_ans.items() if v]
SCREAMING_SNAKE_CASE_ = [k for k, v in qid_to_has_ans.items() if not v]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = get_raw_scores(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = apply_no_ans_threshold(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , OPTS.na_prob_thresh )
SCREAMING_SNAKE_CASE_ = apply_no_ans_threshold(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , OPTS.na_prob_thresh )
SCREAMING_SNAKE_CASE_ = make_eval_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if has_ans_qids:
SCREAMING_SNAKE_CASE_ = make_eval_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , qid_list=_SCREAMING_SNAKE_CASE )
merge_eval(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'HasAns' )
if no_ans_qids:
SCREAMING_SNAKE_CASE_ = make_eval_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , qid_list=_SCREAMING_SNAKE_CASE )
merge_eval(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'NoAns' )
if OPTS.na_prob_file:
find_all_best_thresh(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if OPTS.na_prob_file and OPTS.out_image_dir:
run_precision_recall_analysis(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , OPTS.out_image_dir )
histogram_na_prob(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , OPTS.out_image_dir , 'hasAns' )
histogram_na_prob(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , OPTS.out_image_dir , 'noAns' )
if OPTS.out_file:
with open(OPTS.out_file , 'w' ) as f:
json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else:
print(json.dumps(_SCREAMING_SNAKE_CASE , indent=2 ) )
if __name__ == "__main__":
UpperCamelCase__ : int = parse_args()
if OPTS.out_image_dir:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
main()
| 620 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase__ : Any = {
"configuration_mvp": ["MVP_PRETRAINED_CONFIG_ARCHIVE_MAP", "MvpConfig", "MvpOnnxConfig"],
"tokenization_mvp": ["MvpTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[int] = ["MvpTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"MVP_PRETRAINED_MODEL_ARCHIVE_LIST",
"MvpForCausalLM",
"MvpForConditionalGeneration",
"MvpForQuestionAnswering",
"MvpForSequenceClassification",
"MvpModel",
"MvpPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
import fire
from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , **_SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = AutoModelForSeqaSeqLM.from_config(_SCREAMING_SNAKE_CASE )
model.save_pretrained(_SCREAMING_SNAKE_CASE )
AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ).save_pretrained(_SCREAMING_SNAKE_CASE )
return model
if __name__ == "__main__":
fire.Fire(save_randomly_initialized_version)
| 620 |
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Dict = inspect.getfile(accelerate.test_utils )
__lowerCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
__lowerCAmelCase : Tuple = ['accelerate', 'launch']
__lowerCAmelCase : Union[str, Any] = Path.home() / '.cache/huggingface/accelerate'
__lowerCAmelCase : List[str] = 'default_config.yaml'
__lowerCAmelCase : List[Any] = config_folder / config_file
__lowerCAmelCase : str = config_folder / '_default_config.yaml'
__lowerCAmelCase : Optional[int] = Path('tests/test_configs' )
@classmethod
def lowerCAmelCase__ ( cls):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path)
@classmethod
def lowerCAmelCase__ ( cls):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
for config in sorted(self.test_config_path.glob('**/*.yaml')):
with self.subTest(config_file=_A):
execute_subprocess_async(
self.base_cmd + ['--config_file', str(_A), self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy())
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[Any] = 'test-tpu'
__lowerCAmelCase : str = 'us-central1-a'
__lowerCAmelCase : Union[str, Any] = 'ls'
__lowerCAmelCase : Union[str, Any] = ['accelerate', 'tpu-config']
__lowerCAmelCase : Union[str, Any] = 'cd /usr/share'
__lowerCAmelCase : List[Any] = 'tests/test_samples/test_command_file.sh'
__lowerCAmelCase : Dict = 'Running gcloud compute tpus tpu-vm ssh'
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command',
self.command,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A)
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--command',
self.command,
'--command',
'echo "Hello World"',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command_file',
self.command_file,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--install_accelerate',
'--accelerate_version',
'12.0.0',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
| 620 | 1 |
from typing import Union
import fire
import torch
from tqdm import tqdm
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str = "cpu" , _SCREAMING_SNAKE_CASE : Union[str, None] = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location=_SCREAMING_SNAKE_CASE )
for k, v in tqdm(state_dict.items() ):
if not isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ):
raise TypeError('FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin' )
SCREAMING_SNAKE_CASE_ = v.half()
if save_path is None: # overwrite src_path
SCREAMING_SNAKE_CASE_ = src_path
torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
fire.Fire(convert)
| 620 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCamelCase__ : Tuple = {
"configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
"processing_trocr": ["TrOCRProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
"TrOCRForCausalLM",
"TrOCRPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
import argparse
import json
import torch
from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any]=1 ):
"""simple docstring"""
if n_shave_prefix_segments >= 0:
return ".".join(path.split('.' )[n_shave_prefix_segments:] )
else:
return ".".join(path.split('.' )[:n_shave_prefix_segments] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : List[str]=0 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for old_item in old_list:
SCREAMING_SNAKE_CASE_ = old_item.replace('in_layers.0' , 'norm1' )
SCREAMING_SNAKE_CASE_ = new_item.replace('in_layers.2' , 'conv1' )
SCREAMING_SNAKE_CASE_ = new_item.replace('out_layers.0' , 'norm2' )
SCREAMING_SNAKE_CASE_ = new_item.replace('out_layers.3' , 'conv2' )
SCREAMING_SNAKE_CASE_ = new_item.replace('emb_layers.1' , 'time_emb_proj' )
SCREAMING_SNAKE_CASE_ = new_item.replace('skip_connection' , 'conv_shortcut' )
SCREAMING_SNAKE_CASE_ = shave_segments(_SCREAMING_SNAKE_CASE , n_shave_prefix_segments=_SCREAMING_SNAKE_CASE )
mapping.append({'old': old_item, 'new': new_item} )
return mapping
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Tuple=0 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for old_item in old_list:
SCREAMING_SNAKE_CASE_ = old_item
SCREAMING_SNAKE_CASE_ = new_item.replace('norm.weight' , 'group_norm.weight' )
SCREAMING_SNAKE_CASE_ = new_item.replace('norm.bias' , 'group_norm.bias' )
SCREAMING_SNAKE_CASE_ = new_item.replace('proj_out.weight' , 'proj_attn.weight' )
SCREAMING_SNAKE_CASE_ = new_item.replace('proj_out.bias' , 'proj_attn.bias' )
SCREAMING_SNAKE_CASE_ = shave_segments(_SCREAMING_SNAKE_CASE , n_shave_prefix_segments=_SCREAMING_SNAKE_CASE )
mapping.append({'old': old_item, 'new': new_item} )
return mapping
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Union[str, Any]=None , _SCREAMING_SNAKE_CASE : Any=None , _SCREAMING_SNAKE_CASE : Dict=None ):
"""simple docstring"""
assert isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), "Paths should be a list of dicts containing 'old' and 'new' keys."
# Splits the attention layers into three variables.
if attention_paths_to_split is not None:
for path, path_map in attention_paths_to_split.items():
SCREAMING_SNAKE_CASE_ = old_checkpoint[path]
SCREAMING_SNAKE_CASE_ = old_tensor.shape[0] // 3
SCREAMING_SNAKE_CASE_ = (-1, channels) if len(old_tensor.shape ) == 3 else (-1)
SCREAMING_SNAKE_CASE_ = old_tensor.shape[0] // config['num_head_channels'] // 3
SCREAMING_SNAKE_CASE_ = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = old_tensor.split(channels // num_heads , dim=1 )
SCREAMING_SNAKE_CASE_ = query.reshape(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = key.reshape(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = value.reshape(_SCREAMING_SNAKE_CASE )
for path in paths:
SCREAMING_SNAKE_CASE_ = path['new']
# These have already been assigned
if attention_paths_to_split is not None and new_path in attention_paths_to_split:
continue
# Global renaming happens here
SCREAMING_SNAKE_CASE_ = new_path.replace('middle_block.0' , 'mid_block.resnets.0' )
SCREAMING_SNAKE_CASE_ = new_path.replace('middle_block.1' , 'mid_block.attentions.0' )
SCREAMING_SNAKE_CASE_ = new_path.replace('middle_block.2' , 'mid_block.resnets.1' )
if additional_replacements is not None:
for replacement in additional_replacements:
SCREAMING_SNAKE_CASE_ = new_path.replace(replacement['old'] , replacement['new'] )
# proj_attn.weight has to be converted from conv 1D to linear
if "proj_attn.weight" in new_path:
SCREAMING_SNAKE_CASE_ = old_checkpoint[path['old']][:, :, 0]
else:
SCREAMING_SNAKE_CASE_ = old_checkpoint[path['old']]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = checkpoint['time_embed.0.weight']
SCREAMING_SNAKE_CASE_ = checkpoint['time_embed.0.bias']
SCREAMING_SNAKE_CASE_ = checkpoint['time_embed.2.weight']
SCREAMING_SNAKE_CASE_ = checkpoint['time_embed.2.bias']
SCREAMING_SNAKE_CASE_ = checkpoint['input_blocks.0.0.weight']
SCREAMING_SNAKE_CASE_ = checkpoint['input_blocks.0.0.bias']
SCREAMING_SNAKE_CASE_ = checkpoint['out.0.weight']
SCREAMING_SNAKE_CASE_ = checkpoint['out.0.bias']
SCREAMING_SNAKE_CASE_ = checkpoint['out.2.weight']
SCREAMING_SNAKE_CASE_ = checkpoint['out.2.bias']
# Retrieves the keys for the input blocks only
SCREAMING_SNAKE_CASE_ = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} )
SCREAMING_SNAKE_CASE_ = {
layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key]
for layer_id in range(_SCREAMING_SNAKE_CASE )
}
# Retrieves the keys for the middle blocks only
SCREAMING_SNAKE_CASE_ = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} )
SCREAMING_SNAKE_CASE_ = {
layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key]
for layer_id in range(_SCREAMING_SNAKE_CASE )
}
# Retrieves the keys for the output blocks only
SCREAMING_SNAKE_CASE_ = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} )
SCREAMING_SNAKE_CASE_ = {
layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key]
for layer_id in range(_SCREAMING_SNAKE_CASE )
}
for i in range(1 , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = (i - 1) // (config['num_res_blocks'] + 1)
SCREAMING_SNAKE_CASE_ = (i - 1) % (config['num_res_blocks'] + 1)
SCREAMING_SNAKE_CASE_ = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key]
SCREAMING_SNAKE_CASE_ = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key]
if f"""input_blocks.{i}.0.op.weight""" in checkpoint:
SCREAMING_SNAKE_CASE_ = checkpoint[
f"""input_blocks.{i}.0.op.weight"""
]
SCREAMING_SNAKE_CASE_ = checkpoint[
f"""input_blocks.{i}.0.op.bias"""
]
continue
SCREAMING_SNAKE_CASE_ = renew_resnet_paths(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""}
SCREAMING_SNAKE_CASE_ = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'}
assign_to_checkpoint(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , additional_replacements=[meta_path, resnet_op] , config=_SCREAMING_SNAKE_CASE )
if len(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = renew_attention_paths(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {
'old': f"""input_blocks.{i}.1""",
'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""",
}
SCREAMING_SNAKE_CASE_ = {
f"""input_blocks.{i}.1.qkv.bias""": {
'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""",
'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""",
'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""",
},
f"""input_blocks.{i}.1.qkv.weight""": {
'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""",
'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""",
'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""",
},
}
assign_to_checkpoint(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , additional_replacements=[meta_path] , attention_paths_to_split=_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = middle_blocks[0]
SCREAMING_SNAKE_CASE_ = middle_blocks[1]
SCREAMING_SNAKE_CASE_ = middle_blocks[2]
SCREAMING_SNAKE_CASE_ = renew_resnet_paths(_SCREAMING_SNAKE_CASE )
assign_to_checkpoint(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = renew_resnet_paths(_SCREAMING_SNAKE_CASE )
assign_to_checkpoint(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = renew_attention_paths(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {
'middle_block.1.qkv.bias': {
'key': 'mid_block.attentions.0.key.bias',
'query': 'mid_block.attentions.0.query.bias',
'value': 'mid_block.attentions.0.value.bias',
},
'middle_block.1.qkv.weight': {
'key': 'mid_block.attentions.0.key.weight',
'query': 'mid_block.attentions.0.query.weight',
'value': 'mid_block.attentions.0.value.weight',
},
}
assign_to_checkpoint(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , attention_paths_to_split=_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE )
for i in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = i // (config['num_res_blocks'] + 1)
SCREAMING_SNAKE_CASE_ = i % (config['num_res_blocks'] + 1)
SCREAMING_SNAKE_CASE_ = [shave_segments(_SCREAMING_SNAKE_CASE , 2 ) for name in output_blocks[i]]
SCREAMING_SNAKE_CASE_ = {}
for layer in output_block_layers:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = layer.split('.' )[0], shave_segments(_SCREAMING_SNAKE_CASE , 1 )
if layer_id in output_block_list:
output_block_list[layer_id].append(_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = [layer_name]
if len(_SCREAMING_SNAKE_CASE ) > 1:
SCREAMING_SNAKE_CASE_ = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key]
SCREAMING_SNAKE_CASE_ = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key]
SCREAMING_SNAKE_CASE_ = renew_resnet_paths(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = renew_resnet_paths(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""}
assign_to_checkpoint(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , additional_replacements=[meta_path] , config=_SCREAMING_SNAKE_CASE )
if ["conv.weight", "conv.bias"] in output_block_list.values():
SCREAMING_SNAKE_CASE_ = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] )
SCREAMING_SNAKE_CASE_ = checkpoint[
f"""output_blocks.{i}.{index}.conv.weight"""
]
SCREAMING_SNAKE_CASE_ = checkpoint[
f"""output_blocks.{i}.{index}.conv.bias"""
]
# Clear attentions as they have been attributed above.
if len(_SCREAMING_SNAKE_CASE ) == 2:
SCREAMING_SNAKE_CASE_ = []
if len(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = renew_attention_paths(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {
'old': f"""output_blocks.{i}.1""",
'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""",
}
SCREAMING_SNAKE_CASE_ = {
f"""output_blocks.{i}.1.qkv.bias""": {
'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""",
'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""",
'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""",
},
f"""output_blocks.{i}.1.qkv.weight""": {
'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""",
'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""",
'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""",
},
}
assign_to_checkpoint(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=_SCREAMING_SNAKE_CASE , )
else:
SCREAMING_SNAKE_CASE_ = renew_resnet_paths(_SCREAMING_SNAKE_CASE , n_shave_prefix_segments=1 )
for path in resnet_0_paths:
SCREAMING_SNAKE_CASE_ = '.'.join(['output_blocks', str(_SCREAMING_SNAKE_CASE ), path['old']] )
SCREAMING_SNAKE_CASE_ = '.'.join(['up_blocks', str(_SCREAMING_SNAKE_CASE ), 'resnets', str(_SCREAMING_SNAKE_CASE ), path['new']] )
SCREAMING_SNAKE_CASE_ = checkpoint[old_path]
return new_checkpoint
if __name__ == "__main__":
UpperCamelCase__ : Union[str, Any] = argparse.ArgumentParser()
parser.add_argument(
"--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The config json file corresponding to the architecture.",
)
parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
UpperCamelCase__ : List[Any] = parser.parse_args()
UpperCamelCase__ : Tuple = torch.load(args.checkpoint_path)
with open(args.config_file) as f:
UpperCamelCase__ : Optional[Any] = json.loads(f.read())
UpperCamelCase__ : List[str] = convert_ldm_checkpoint(checkpoint, config)
if "ldm" in config:
del config["ldm"]
UpperCamelCase__ : Tuple = UNetaDModel(**config)
model.load_state_dict(converted_checkpoint)
try:
UpperCamelCase__ : List[str] = DDPMScheduler.from_config("/".join(args.checkpoint_path.split("/")[:-1]))
UpperCamelCase__ : int = VQModel.from_pretrained("/".join(args.checkpoint_path.split("/")[:-1]))
UpperCamelCase__ : str = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae)
pipe.save_pretrained(args.dump_path)
except: # noqa: E722
model.save_pretrained(args.dump_path)
| 620 |
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
UpperCamelCase__ : int = Lock()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0 , 10 ):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
SCREAMING_SNAKE_CASE_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# after all swaps are performed, send the values back to main
result_pipe[1].send(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe() )
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ):
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(
len(_SCREAMING_SNAKE_CASE ) - 1,
arr[len(_SCREAMING_SNAKE_CASE ) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1],
) , ) )
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE_ = result_pipe[p][0].recv()
process_array_[p].join()
return arr
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = list(range(10 , 0 , -1 ) )
print('Initial List' )
print(*_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = odd_even_transposition(_SCREAMING_SNAKE_CASE )
print('Sorted List\n' )
print(*_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : Tuple = logging.get_logger(__name__)
UpperCamelCase__ : str = {
"MIT/ast-finetuned-audioset-10-10-0.4593": (
"https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json"
),
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Dict = 'audio-spectrogram-transformer'
def __init__( self , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1E-12 , _A=16 , _A=True , _A=10 , _A=10 , _A=1024 , _A=128 , **_A , ):
super().__init__(**_A)
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = patch_size
SCREAMING_SNAKE_CASE_ = qkv_bias
SCREAMING_SNAKE_CASE_ = frequency_stride
SCREAMING_SNAKE_CASE_ = time_stride
SCREAMING_SNAKE_CASE_ = max_length
SCREAMING_SNAKE_CASE_ = num_mel_bins
| 620 |
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
UpperCamelCase__ : int = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n"
class __snake_case ( unittest.TestCase , lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering')
self.tool.setup()
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering' , remote=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
| 620 | 1 |
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
UpperCamelCase__ : int = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n"
class __snake_case ( unittest.TestCase , lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering')
self.tool.setup()
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering' , remote=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
| 620 |
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import BeitImageProcessor
class __snake_case ( unittest.TestCase ):
def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=False , ):
SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 20, 'width': 20}
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 18, 'width': 18}
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = min_resolution
SCREAMING_SNAKE_CASE_ = max_resolution
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean
SCREAMING_SNAKE_CASE_ = image_std
SCREAMING_SNAKE_CASE_ = do_reduce_labels
def lowerCAmelCase__ ( self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_reduce_labels": self.do_reduce_labels,
}
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[1]['file'] )
return image, map
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[1]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[2]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[3]['file'] )
return [imagea, imagea], [mapa, mapa]
@require_torch
@require_vision
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Union[str, Any] = BeitImageProcessor if is_vision_available() else None
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BeitImageProcessingTester(self)
@property
def lowerCAmelCase__ ( self):
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(_A , 'do_resize'))
self.assertTrue(hasattr(_A , 'size'))
self.assertTrue(hasattr(_A , 'do_center_crop'))
self.assertTrue(hasattr(_A , 'center_crop'))
self.assertTrue(hasattr(_A , 'do_normalize'))
self.assertTrue(hasattr(_A , 'image_mean'))
self.assertTrue(hasattr(_A , 'image_std'))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 20, 'width': 20})
self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18})
self.assertEqual(image_processor.do_reduce_labels , _A)
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A)
self.assertEqual(image_processor.size , {'height': 42, 'width': 42})
self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84})
self.assertEqual(image_processor.do_reduce_labels , _A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A)
for image in image_inputs:
self.assertIsInstance(_A , Image.Image)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A)
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
SCREAMING_SNAKE_CASE_ = []
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
maps.append(torch.zeros(image.shape[-2:]).long())
# Test not batched input
SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , maps[0] , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test not batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_batch_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
2,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
2,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 150)
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
| 620 | 1 |
from math import factorial
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if n < k or k < 0:
raise ValueError('Please enter positive integers for n and k where n >= k' )
return factorial(_SCREAMING_SNAKE_CASE ) // (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k ))
if __name__ == "__main__":
print(
"The number of five-card hands possible from a standard",
F'fifty-two card deck is: {combinations(52, 5)}\n',
)
print(
"If a class of 40 students must be arranged into groups of",
F'4 for group projects, there are {combinations(40, 4)} ways',
"to arrange them.\n",
)
print(
"If 10 teams are competing in a Formula One race, there",
F'are {combinations(10, 3)} ways that first, second and',
"third place can be awarded.",
)
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 200 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [1, 2, 5, 10, 20, 50, 100, 200]
SCREAMING_SNAKE_CASE_ = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(_SCREAMING_SNAKE_CASE , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73_682
| 620 | 1 |
import mpmath # for roots of unity
import numpy as np
class __snake_case :
def __init__( self , _A=None , _A=None):
# Input as list
SCREAMING_SNAKE_CASE_ = list(poly_a or [0])[:]
SCREAMING_SNAKE_CASE_ = list(poly_b or [0])[:]
# Remove leading zero coefficients
while self.polyA[-1] == 0:
self.polyA.pop()
SCREAMING_SNAKE_CASE_ = len(self.polyA)
while self.polyB[-1] == 0:
self.polyB.pop()
SCREAMING_SNAKE_CASE_ = len(self.polyB)
# Add 0 to make lengths equal a power of 2
SCREAMING_SNAKE_CASE_ = int(
2 ** np.ceil(np.loga(len(self.polyA) + len(self.polyB) - 1)))
while len(self.polyA) < self.c_max_length:
self.polyA.append(0)
while len(self.polyB) < self.c_max_length:
self.polyB.append(0)
# A complex root used for the fourier transform
SCREAMING_SNAKE_CASE_ = complex(mpmath.root(x=1 , n=self.c_max_length , k=1))
# The product
SCREAMING_SNAKE_CASE_ = self.__multiply()
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = [[x] for x in self.polyA] if which == 'A' else [[x] for x in self.polyB]
# Corner case
if len(_A) <= 1:
return dft[0]
#
SCREAMING_SNAKE_CASE_ = self.c_max_length // 2
while next_ncol > 0:
SCREAMING_SNAKE_CASE_ = [[] for i in range(_A)]
SCREAMING_SNAKE_CASE_ = self.root**next_ncol
# First half of next step
SCREAMING_SNAKE_CASE_ = 1
for j in range(self.c_max_length // (next_ncol * 2)):
for i in range(_A):
new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j])
current_root *= root
# Second half of next step
SCREAMING_SNAKE_CASE_ = 1
for j in range(self.c_max_length // (next_ncol * 2)):
for i in range(_A):
new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j])
current_root *= root
# Update
SCREAMING_SNAKE_CASE_ = new_dft
SCREAMING_SNAKE_CASE_ = next_ncol // 2
return dft[0]
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.__dft('A')
SCREAMING_SNAKE_CASE_ = self.__dft('B')
SCREAMING_SNAKE_CASE_ = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]]
del dft_a
del dft_b
# Corner Case
if len(inverce_c[0]) <= 1:
return inverce_c[0]
# Inverse DFT
SCREAMING_SNAKE_CASE_ = 2
while next_ncol <= self.c_max_length:
SCREAMING_SNAKE_CASE_ = [[] for i in range(_A)]
SCREAMING_SNAKE_CASE_ = self.root ** (next_ncol // 2)
SCREAMING_SNAKE_CASE_ = 1
# First half of next step
for j in range(self.c_max_length // next_ncol):
for i in range(next_ncol // 2):
# Even positions
new_inverse_c[i].append(
(
inverce_c[i][j]
+ inverce_c[i][j + self.c_max_length // next_ncol]
)
/ 2)
# Odd positions
new_inverse_c[i + next_ncol // 2].append(
(
inverce_c[i][j]
- inverce_c[i][j + self.c_max_length // next_ncol]
)
/ (2 * current_root))
current_root *= root
# Update
SCREAMING_SNAKE_CASE_ = new_inverse_c
next_ncol *= 2
# Unpack
SCREAMING_SNAKE_CASE_ = [round(x[0].real , 8) + round(x[0].imag , 8) * 1J for x in inverce_c]
# Remove leading 0's
while inverce_c[-1] == 0:
inverce_c.pop()
return inverce_c
def __str__( self):
SCREAMING_SNAKE_CASE_ = 'A = ' + ' + '.join(
f"""{coef}*x^{i}""" for coef, i in enumerate(self.polyA[: self.len_A]))
SCREAMING_SNAKE_CASE_ = 'B = ' + ' + '.join(
f"""{coef}*x^{i}""" for coef, i in enumerate(self.polyB[: self.len_B]))
SCREAMING_SNAKE_CASE_ = 'A*B = ' + ' + '.join(
f"""{coef}*x^{i}""" for coef, i in enumerate(self.product))
return f"""{a}\n{b}\n{c}"""
# Unit tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if index == number_of_items:
return 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 )
if weights[index] <= max_weight:
SCREAMING_SNAKE_CASE_ = values[index] + knapsack(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 )
return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 | 1 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConformerConfig,
WavaVecaConformerForCTC,
WavaVecaConformerForPreTraining,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
UpperCamelCase__ : int = logging.get_logger(__name__)
UpperCamelCase__ : int = {
"post_extract_proj": "feature_projection.projection",
"encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
"self_attn.linear_k": "encoder.layers.*.self_attn.linear_k",
"self_attn.linear_v": "encoder.layers.*.self_attn.linear_v",
"self_attn.linear_q": "encoder.layers.*.self_attn.linear_q",
"self_attn.pos_bias_u": "encoder.layers.*.self_attn.pos_bias_u",
"self_attn.pos_bias_v": "encoder.layers.*.self_attn.pos_bias_v",
"self_attn.linear_out": "encoder.layers.*.self_attn.linear_out",
"self_attn.linear_pos": "encoder.layers.*.self_attn.linear_pos",
"self_attn.rotary_emb": "encoder.embed_positions",
"self_attn_layer_norm": "encoder.layers.*.self_attn_layer_norm",
"conv_module.pointwise_conv1": "encoder.layers.*.conv_module.pointwise_conv1",
"conv_module.pointwise_conv2": "encoder.layers.*.conv_module.pointwise_conv2",
"conv_module.depthwise_conv": "encoder.layers.*.conv_module.depthwise_conv",
"conv_module.batch_norm": "encoder.layers.*.conv_module.batch_norm",
"conv_module.layer_norm": "encoder.layers.*.conv_module.layer_norm",
"ffn1.w_1": "encoder.layers.*.ffn1.intermediate_dense",
"ffn1.w_2": "encoder.layers.*.ffn1.output_dense",
"ffn1.layer_norm": "encoder.layers.*.ffn1_layer_norm",
"ffn2.w_1": "encoder.layers.*.ffn2.intermediate_dense",
"ffn2.w_2": "encoder.layers.*.ffn2.output_dense",
"ffn2.layer_norm": "encoder.layers.*.ffn2_layer_norm",
"final_layer_norm": "encoder.layers.*.final_layer_norm",
"encoder.layer_norm": "encoder.layer_norm",
"w2v_model.layer_norm": "feature_projection.layer_norm",
"quantizer.weight_proj": "quantizer.weight_proj",
"quantizer.vars": "quantizer.codevectors",
"project_q": "project_q",
"final_proj": "project_hid",
"w2v_encoder.proj": "lm_head",
"mask_emb": "masked_spec_embed",
}
UpperCamelCase__ : List[Any] = [
"lm_head",
"quantizer.weight_proj",
"quantizer.codevectors",
"project_q",
"project_hid",
]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
for attribute in key.split('.' ):
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if weight_type is not None:
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape
else:
SCREAMING_SNAKE_CASE_ = 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":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "weight_g":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "weight_v":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "bias":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "running_mean":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "running_var":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "num_batches_tracked":
SCREAMING_SNAKE_CASE_ = value
elif weight_type == "inv_freq":
SCREAMING_SNAKE_CASE_ = value
else:
SCREAMING_SNAKE_CASE_ = value
logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = fairseq_model.state_dict()
SCREAMING_SNAKE_CASE_ = hf_model.wavaveca_conformer.feature_extractor
for name, value in fairseq_dict.items():
SCREAMING_SNAKE_CASE_ = False
if "conv_layers" in name:
load_conv_layer(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , )
SCREAMING_SNAKE_CASE_ = True
else:
for key, mapped_key in MAPPING.items():
SCREAMING_SNAKE_CASE_ = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
SCREAMING_SNAKE_CASE_ = True
if "*" in mapped_key:
SCREAMING_SNAKE_CASE_ = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2]
SCREAMING_SNAKE_CASE_ = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE )
if "pos_bias_u" in name:
SCREAMING_SNAKE_CASE_ = None
elif "pos_bias_v" in name:
SCREAMING_SNAKE_CASE_ = None
elif "weight_g" in name:
SCREAMING_SNAKE_CASE_ = 'weight_g'
elif "weight_v" in name:
SCREAMING_SNAKE_CASE_ = 'weight_v'
elif "bias" in name:
SCREAMING_SNAKE_CASE_ = 'bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
SCREAMING_SNAKE_CASE_ = 'weight'
elif "running_mean" in name:
SCREAMING_SNAKE_CASE_ = 'running_mean'
elif "inv_freq" in name:
SCREAMING_SNAKE_CASE_ = 'inv_freq'
elif "running_var" in name:
SCREAMING_SNAKE_CASE_ = 'running_var'
elif "num_batches_tracked" in name:
SCREAMING_SNAKE_CASE_ = 'num_batches_tracked'
else:
SCREAMING_SNAKE_CASE_ = None
set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
continue
if not is_used:
unused_weights.append(_SCREAMING_SNAKE_CASE )
logger.warning(f"""Unused weights: {unused_weights}""" )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = full_name.split('conv_layers.' )[-1]
SCREAMING_SNAKE_CASE_ = name.split('.' )
SCREAMING_SNAKE_CASE_ = int(items[0] )
SCREAMING_SNAKE_CASE_ = 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.""" )
SCREAMING_SNAKE_CASE_ = 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.""" )
SCREAMING_SNAKE_CASE_ = value
logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
raise ValueError(
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" )
SCREAMING_SNAKE_CASE_ = value
logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
f"""{full_name} has size {value.shape}, but"""
f""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" )
SCREAMING_SNAKE_CASE_ = value
logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(_SCREAMING_SNAKE_CASE )
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Tuple=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Any=True ):
"""simple docstring"""
if config_path is not None:
SCREAMING_SNAKE_CASE_ = WavaVecaConformerConfig.from_pretrained(_SCREAMING_SNAKE_CASE , hidden_act='swish' )
else:
SCREAMING_SNAKE_CASE_ = WavaVecaConformerConfig()
if "rope" in checkpoint_path:
SCREAMING_SNAKE_CASE_ = 'rotary'
if is_finetuned:
if dict_path:
SCREAMING_SNAKE_CASE_ = Dictionary.load(_SCREAMING_SNAKE_CASE )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
SCREAMING_SNAKE_CASE_ = target_dict.pad_index
SCREAMING_SNAKE_CASE_ = target_dict.bos_index
SCREAMING_SNAKE_CASE_ = target_dict.eos_index
SCREAMING_SNAKE_CASE_ = len(target_dict.symbols )
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , 'vocab.json' )
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_SCREAMING_SNAKE_CASE ) )
return
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = target_dict.indices
# fairseq has the <pad> and <s> switched
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 1
with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as vocab_handle:
json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = WavaVecaCTCTokenizer(
_SCREAMING_SNAKE_CASE , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = True if config.feat_extract_norm == 'layer' else False
SCREAMING_SNAKE_CASE_ = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE )
processor.save_pretrained(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = WavaVecaConformerForCTC(_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = WavaVecaConformerForPreTraining(_SCREAMING_SNAKE_CASE )
if is_finetuned:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
else:
SCREAMING_SNAKE_CASE_ = argparse.Namespace(task='audio_pretraining' )
SCREAMING_SNAKE_CASE_ = fairseq.tasks.setup_task(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = model[0].eval()
recursively_load_weights(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , not is_finetuned )
hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : List[Any] = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
parser.add_argument(
"--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
)
UpperCamelCase__ : Tuple = parser.parse_args()
convert_wavaveca_conformer_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 620 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase__ : List[Any] = torch.device("cpu")
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = dct.pop(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = val
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for k in state_dict.keys():
SCREAMING_SNAKE_CASE_ = k
if ".pwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.pwconv' , '.point_wise_conv' )
if ".dwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.dwconv' , '.depth_wise_conv' )
if ".Proj." in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.Proj.' , '.proj.' )
if "patch_embed" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' )
if "network" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.split('.' )
if ls[2].isdigit():
SCREAMING_SNAKE_CASE_ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] )
else:
SCREAMING_SNAKE_CASE_ = k_new.replace('network' , 'swiftformer.encoder.network' )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
SCREAMING_SNAKE_CASE_ = 1_000
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json'
SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
SCREAMING_SNAKE_CASE_ = [3, 3, 6, 4]
SCREAMING_SNAKE_CASE_ = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
SCREAMING_SNAKE_CASE_ = [3, 3, 9, 6]
SCREAMING_SNAKE_CASE_ = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
SCREAMING_SNAKE_CASE_ = [4, 3, 10, 5]
SCREAMING_SNAKE_CASE_ = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
SCREAMING_SNAKE_CASE_ = [4, 4, 12, 6]
SCREAMING_SNAKE_CASE_ = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith('https' ):
SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
SCREAMING_SNAKE_CASE_ = checkpoint
SCREAMING_SNAKE_CASE_ = create_rename_keys(_SCREAMING_SNAKE_CASE )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
SCREAMING_SNAKE_CASE_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval()
hf_model.load_state_dict(_SCREAMING_SNAKE_CASE )
# prepare test inputs
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = ViTImageProcessor.from_pretrained('preprocessor_config' )
SCREAMING_SNAKE_CASE_ = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
# compare outputs from both models
SCREAMING_SNAKE_CASE_ = get_expected_output(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = hf_model(inputs['pixel_values'] ).logits
assert hf_logits.shape == torch.Size([1, 1_000] )
assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1E-3 )
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--swiftformer_name",
default="swiftformer_xs",
choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"],
type=str,
help="Name of the SwiftFormer model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="./converted_outputs/",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.")
UpperCamelCase__ : Union[str, Any] = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 620 | 1 |
import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SwiftFormerConfig,
SwiftFormerForImageClassification,
ViTImageProcessor,
)
from transformers.utils import logging
logging.set_verbosity_info()
UpperCamelCase__ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase__ : List[Any] = torch.device("cpu")
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg'
SCREAMING_SNAKE_CASE_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw )
return im
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if swiftformer_name == "swiftformer_xs":
return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] )
elif swiftformer_name == "swiftformer_s":
return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] )
elif swiftformer_name == "swiftformer_l1":
return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] )
elif swiftformer_name == "swiftformer_l3":
return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = dct.pop(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = val
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for k in state_dict.keys():
SCREAMING_SNAKE_CASE_ = k
if ".pwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.pwconv' , '.point_wise_conv' )
if ".dwconv" in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.dwconv' , '.depth_wise_conv' )
if ".Proj." in k:
SCREAMING_SNAKE_CASE_ = k_new.replace('.Proj.' , '.proj.' )
if "patch_embed" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' )
if "network" in k_new:
SCREAMING_SNAKE_CASE_ = k_new.split('.' )
if ls[2].isdigit():
SCREAMING_SNAKE_CASE_ = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] )
else:
SCREAMING_SNAKE_CASE_ = k_new.replace('network' , 'swiftformer.encoder.network' )
rename_keys.append((k, k_new) )
return rename_keys
@torch.no_grad()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = SwiftFormerConfig()
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
SCREAMING_SNAKE_CASE_ = 1_000
SCREAMING_SNAKE_CASE_ = 'huggingface/label-files'
SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json'
SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type='dataset' ) , 'r' ) )
SCREAMING_SNAKE_CASE_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE_ = idalabel
SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()}
# size of the architecture
if swiftformer_name == "swiftformer_xs":
SCREAMING_SNAKE_CASE_ = [3, 3, 6, 4]
SCREAMING_SNAKE_CASE_ = [48, 56, 112, 220]
elif swiftformer_name == "swiftformer_s":
SCREAMING_SNAKE_CASE_ = [3, 3, 9, 6]
SCREAMING_SNAKE_CASE_ = [48, 64, 168, 224]
elif swiftformer_name == "swiftformer_l1":
SCREAMING_SNAKE_CASE_ = [4, 3, 10, 5]
SCREAMING_SNAKE_CASE_ = [48, 96, 192, 384]
elif swiftformer_name == "swiftformer_l3":
SCREAMING_SNAKE_CASE_ = [4, 4, 12, 6]
SCREAMING_SNAKE_CASE_ = [64, 128, 320, 512]
# load state_dict of original model, remove and rename some keys
if original_ckpt:
if original_ckpt.startswith('https' ):
SCREAMING_SNAKE_CASE_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location='cpu' , check_hash=_SCREAMING_SNAKE_CASE )
else:
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )
SCREAMING_SNAKE_CASE_ = checkpoint
SCREAMING_SNAKE_CASE_ = create_rename_keys(_SCREAMING_SNAKE_CASE )
for rename_key_src, rename_key_dest in rename_keys:
rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# load HuggingFace model
SCREAMING_SNAKE_CASE_ = SwiftFormerForImageClassification(_SCREAMING_SNAKE_CASE ).eval()
hf_model.load_state_dict(_SCREAMING_SNAKE_CASE )
# prepare test inputs
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = ViTImageProcessor.from_pretrained('preprocessor_config' )
SCREAMING_SNAKE_CASE_ = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
# compare outputs from both models
SCREAMING_SNAKE_CASE_ = get_expected_output(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = hf_model(inputs['pixel_values'] ).logits
assert hf_logits.shape == torch.Size([1, 1_000] )
assert torch.allclose(hf_logits[0, 0:5] , _SCREAMING_SNAKE_CASE , atol=1E-3 )
Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE )
print(f"""Saving model {swiftformer_name} to {pytorch_dump_folder_path}""" )
hf_model.save_pretrained(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
UpperCamelCase__ : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--swiftformer_name",
default="swiftformer_xs",
choices=["swiftformer_xs", "swiftformer_s", "swiftformer_l1", "swiftformer_l3"],
type=str,
help="Name of the SwiftFormer model you'd like to convert.",
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="./converted_outputs/",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--original_ckpt", default=None, type=str, help="Path to the original model checkpoint.")
UpperCamelCase__ : Union[str, Any] = parser.parse_args()
convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
| 620 |
def _UpperCAmelCase ( ):
"""simple docstring"""
for n in range(1 , 1_000_000 ):
yield n * (n + 1) // 2
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = 2
while i * i <= n:
SCREAMING_SNAKE_CASE_ = 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 _UpperCAmelCase ( ):
"""simple docstring"""
return next(i for i in triangle_number_generator() if count_divisors(_SCREAMING_SNAKE_CASE ) > 500 )
if __name__ == "__main__":
print(solution())
| 620 | 1 |
from typing import Optional, Union
import torch
from torch import nn
from ...configuration_utils import ConfigMixin, register_to_config
from ...models.modeling_utils import ModelMixin
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 768 , ):
super().__init__()
SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.zeros(1 , _A))
SCREAMING_SNAKE_CASE_ = nn.Parameter(torch.ones(1 , _A))
def lowerCAmelCase__ ( self , _A = None , _A = None , ):
SCREAMING_SNAKE_CASE_ = nn.Parameter(self.mean.to(_A).to(_A))
SCREAMING_SNAKE_CASE_ = nn.Parameter(self.std.to(_A).to(_A))
return self
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = (embeds - self.mean) * 1.0 / self.std
return embeds
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = (embeds * self.std) + self.mean
return embeds
| 620 |
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional
import pyarrow as pa
import pyarrow.json as paj
import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline
UpperCamelCase__ : Optional[int] = datasets.utils.logging.get_logger(__name__)
@dataclass
class __snake_case ( datasets.BuilderConfig ):
__lowerCAmelCase : Optional[datasets.Features] = None
__lowerCAmelCase : str = "utf-8"
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : Optional[str] = None
__lowerCAmelCase : bool = True # deprecated
__lowerCAmelCase : Optional[int] = None # deprecated
__lowerCAmelCase : int = 10 << 20 # 10MB
__lowerCAmelCase : Optional[bool] = None
class __snake_case ( datasets.ArrowBasedBuilder ):
__lowerCAmelCase : int = JsonConfig
def lowerCAmelCase__ ( self):
if self.config.block_size is not None:
logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead')
SCREAMING_SNAKE_CASE_ = self.config.block_size
if self.config.use_threads is not True:
logger.warning(
'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.')
if self.config.newlines_in_values is not None:
raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported')
return datasets.DatasetInfo(features=self.config.features)
def lowerCAmelCase__ ( self , _A):
if not self.config.data_files:
raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
SCREAMING_SNAKE_CASE_ = dl_manager.download_and_extract(self.config.data_files)
if isinstance(_A , (str, list, tuple)):
SCREAMING_SNAKE_CASE_ = data_files
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files})]
SCREAMING_SNAKE_CASE_ = []
for split_name, files in data_files.items():
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [files]
SCREAMING_SNAKE_CASE_ = [dl_manager.iter_files(_A) for file in files]
splits.append(datasets.SplitGenerator(name=_A , gen_kwargs={'files': files}))
return splits
def lowerCAmelCase__ ( self , _A):
if self.config.features is not None:
# adding missing columns
for column_name in set(self.config.features) - set(pa_table.column_names):
SCREAMING_SNAKE_CASE_ = self.config.features.arrow_schema.field(_A).type
SCREAMING_SNAKE_CASE_ = pa_table.append_column(_A , pa.array([None] * len(_A) , type=_A))
# more expensive cast to support nested structures with keys in a different order
# allows str <-> int/float or str to Audio for example
SCREAMING_SNAKE_CASE_ = table_cast(_A , self.config.features.arrow_schema)
return pa_table
def lowerCAmelCase__ ( self , _A):
for file_idx, file in enumerate(itertools.chain.from_iterable(_A)):
# If the file is one json object and if we need to look at the list of items in one specific field
if self.config.field is not None:
with open(_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
# We keep only the field we are interested in
SCREAMING_SNAKE_CASE_ = dataset[self.config.field]
# We accept two format: a list of dicts or a dict of lists
if isinstance(_A , (list, tuple)):
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
else:
SCREAMING_SNAKE_CASE_ = dataset
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
yield file_idx, self._cast_table(_A)
# If the file has one json object per line
else:
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = 0
# Use block_size equal to the chunk size divided by 32 to leverage multithreading
# Set a default minimum value of 16kB if the chunk size is really small
SCREAMING_SNAKE_CASE_ = max(self.config.chunksize // 32 , 16 << 10)
SCREAMING_SNAKE_CASE_ = (
self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
)
while True:
SCREAMING_SNAKE_CASE_ = f.read(self.config.chunksize)
if not batch:
break
# Finish current line
try:
batch += f.readline()
except (AttributeError, io.UnsupportedOperation):
batch += readline(_A)
# PyArrow only accepts utf-8 encoded bytes
if self.config.encoding != "utf-8":
SCREAMING_SNAKE_CASE_ = batch.decode(self.config.encoding , errors=_A).encode('utf-8')
try:
while True:
try:
SCREAMING_SNAKE_CASE_ = paj.read_json(
io.BytesIO(_A) , read_options=paj.ReadOptions(block_size=_A))
break
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
if (
isinstance(_A , pa.ArrowInvalid)
and "straddling" not in str(_A)
or block_size > len(_A)
):
raise
else:
# Increase the block size in case it was too small.
# The block size will be reset for the next file.
logger.debug(
f"""Batch of {len(_A)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""")
block_size *= 2
except pa.ArrowInvalid as e:
try:
with open(
_A , encoding=self.config.encoding , errors=self.config.encoding_errors) as f:
SCREAMING_SNAKE_CASE_ = json.load(_A)
except json.JSONDecodeError:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise e
# If possible, parse the file as a list of json objects and exit the loop
if isinstance(_A , _A): # list is the only sequence type supported in JSON
try:
SCREAMING_SNAKE_CASE_ = set().union(*[row.keys() for row in dataset])
SCREAMING_SNAKE_CASE_ = {col: [row.get(_A) for row in dataset] for col in keys}
SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict(_A)
except (pa.ArrowInvalid, AttributeError) as e:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(f"""Not able to read records in the JSON file at {file}.""") from None
yield file_idx, self._cast_table(_A)
break
else:
logger.error(f"""Failed to read file '{file}' with error {type(_A)}: {e}""")
raise ValueError(
f"""Not able to read records in the JSON file at {file}. """
f"""You should probably indicate the field of the JSON file containing your records. """
f"""This JSON file contain the following fields: {str(list(dataset.keys()))}. """
f"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """) from None
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(_A)
batch_idx += 1
| 620 | 1 |
from typing import List, Optional, Union
import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
UpperCamelCase__ : Tuple = logging.get_logger(__name__)
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Dict = ['input_features', 'attention_mask']
def __init__( self , _A=80 , _A=16000 , _A=80 , _A=0.0 , _A=True , _A=True , _A=True , **_A , ):
super().__init__(feature_size=_A , sampling_rate=_A , padding_value=_A , **_A)
SCREAMING_SNAKE_CASE_ = num_mel_bins
SCREAMING_SNAKE_CASE_ = do_ceptral_normalize
SCREAMING_SNAKE_CASE_ = normalize_means
SCREAMING_SNAKE_CASE_ = normalize_vars
SCREAMING_SNAKE_CASE_ = True
def lowerCAmelCase__ ( self , _A , ):
SCREAMING_SNAKE_CASE_ = waveform * (2**15) # Kaldi compliance: 16-bit signed integers
SCREAMING_SNAKE_CASE_ = torch.from_numpy(_A).unsqueeze(0)
SCREAMING_SNAKE_CASE_ = ta_kaldi.fbank(_A , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate)
return features.numpy()
@staticmethod
def lowerCAmelCase__ ( _A , _A , _A = True , _A = True , _A = 0.0 , ):
# make sure we normalize float32 arrays
if normalize_means:
SCREAMING_SNAKE_CASE_ = x[:input_length].mean(axis=0)
SCREAMING_SNAKE_CASE_ = np.subtract(_A , _A)
if normalize_vars:
SCREAMING_SNAKE_CASE_ = x[:input_length].std(axis=0)
SCREAMING_SNAKE_CASE_ = np.divide(_A , _A)
if input_length < x.shape[0]:
SCREAMING_SNAKE_CASE_ = padding_value
# make sure array is in float32
SCREAMING_SNAKE_CASE_ = x.astype(np.floataa)
return x
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
return [
self.utterance_cmvn(_A , _A , self.normalize_means , self.normalize_vars , self.padding_value)
for x, n in zip(_A , _A)
]
def __call__( self , _A , _A = False , _A = None , _A = False , _A = None , _A = None , _A = None , _A = None , **_A , ):
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"""
f""" {self.sampling_rate} and not {sampling_rate}.""")
else:
logger.warning(
'It is strongly recommended to pass the `sampling_rate` argument to this function. '
'Failing to do so can result in silent errors that might be hard to debug.')
SCREAMING_SNAKE_CASE_ = 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}""")
SCREAMING_SNAKE_CASE_ = is_batched_numpy or (
isinstance(_A , (list, tuple)) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list)))
)
if is_batched:
SCREAMING_SNAKE_CASE_ = [np.asarray(_A , dtype=np.floataa) for speech in raw_speech]
elif not is_batched and not isinstance(_A , np.ndarray):
SCREAMING_SNAKE_CASE_ = np.asarray(_A , dtype=np.floataa)
elif isinstance(_A , np.ndarray) and raw_speech.dtype is np.dtype(np.floataa):
SCREAMING_SNAKE_CASE_ = raw_speech.astype(np.floataa)
# always return batch
if not is_batched:
SCREAMING_SNAKE_CASE_ = [raw_speech]
# extract fbank features
SCREAMING_SNAKE_CASE_ = [self._extract_fbank_features(_A) for waveform in raw_speech]
# convert into correct format for padding
SCREAMING_SNAKE_CASE_ = BatchFeature({'input_features': features})
SCREAMING_SNAKE_CASE_ = self.pad(
_A , padding=_A , max_length=_A , truncation=_A , pad_to_multiple_of=_A , return_attention_mask=_A , **_A , )
# make sure list is in array format
SCREAMING_SNAKE_CASE_ = padded_inputs.get('input_features')
if isinstance(input_features[0] , _A):
SCREAMING_SNAKE_CASE_ = [np.asarray(_A , dtype=np.floataa) for feature in input_features]
SCREAMING_SNAKE_CASE_ = padded_inputs.get('attention_mask')
if attention_mask is not None:
SCREAMING_SNAKE_CASE_ = [np.asarray(_A , dtype=np.intaa) for array in attention_mask]
# Utterance-level cepstral mean and variance normalization
if self.do_ceptral_normalize:
SCREAMING_SNAKE_CASE_ = (
np.array(_A , dtype=np.intaa)
if self._get_padding_strategies(_A , max_length=_A) is not PaddingStrategy.DO_NOT_PAD
else None
)
SCREAMING_SNAKE_CASE_ = self.normalize(
padded_inputs['input_features'] , attention_mask=_A)
if return_tensors is not None:
SCREAMING_SNAKE_CASE_ = padded_inputs.convert_to_tensors(_A)
return padded_inputs
| 620 |
import unittest
from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM
@require_torch
class __snake_case :
def __init__( self , _A , _A=99 , _A=13 , _A=16 , _A=7 , _A=True , _A=True , _A=True , _A=False , _A=True , _A=2 , _A=32 , _A=4 , _A=4 , _A=30 , _A=0 , _A=1 , _A=2 , _A=None , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE_ = self.decoder_seq_length
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_attention_mask
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_ffn_dim
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = eos_token_id
SCREAMING_SNAKE_CASE_ = bos_token_id
SCREAMING_SNAKE_CASE_ = pad_token_id
SCREAMING_SNAKE_CASE_ = decoder_start_token_id
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = decoder_seq_length
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_attention_mask:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2)
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = TrOCRConfig(
vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , )
return (config, input_ids, attention_mask, lm_labels)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , ):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = TrOCRDecoder(config=_A).to(_A).eval()
SCREAMING_SNAKE_CASE_ = input_ids[:2]
input_ids[input_ids == 0] += 1
# first forward pass
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
self.parent.assertTrue(len(_A) == len(_A))
self.parent.assertTrue(len(_A) == len(_A) + 1)
SCREAMING_SNAKE_CASE_ = outputs['past_key_values']
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE_ = ids_tensor((2, 1) , config.vocab_size - 1) + 1
# append to next input_ids and
SCREAMING_SNAKE_CASE_ = torch.cat([input_ids, next_tokens] , dim=-1)
SCREAMING_SNAKE_CASE_ = model(_A)['last_hidden_state']
SCREAMING_SNAKE_CASE_ = model(_A , past_key_values=_A)['last_hidden_state']
# select random slice
SCREAMING_SNAKE_CASE_ = ids_tensor((1,) , output_from_past.shape[-1]).item()
SCREAMING_SNAKE_CASE_ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE_ = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(_A , _A , atol=1E-3)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
@require_torch
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Tuple = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
__lowerCAmelCase : Union[str, Any] = (TrOCRForCausalLM,) if is_torch_available() else ()
__lowerCAmelCase : str = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
__lowerCAmelCase : Any = True
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TrOCRStandaloneDecoderModelTester(self , is_training=_A)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*_A)
def lowerCAmelCase__ ( self):
return
@unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :)
def lowerCAmelCase__ ( self):
pass
| 620 | 1 |
# limitations under the License.
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401
from .utils import deprecate
deprecate(
"pipelines_utils",
"0.22.0",
"Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.",
standard_warn=False,
stacklevel=3,
)
| 620 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : torch.FloatTensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ):
super().__init__()
# pass init params to Encoder
SCREAMING_SNAKE_CASE_ = Encoder(
in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , )
SCREAMING_SNAKE_CASE_ = vq_embed_dim if vq_embed_dim is not None else latent_channels
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
SCREAMING_SNAKE_CASE_ = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A)
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
# pass init params to Decoder
SCREAMING_SNAKE_CASE_ = Decoder(
in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , )
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = self.encoder(_A)
SCREAMING_SNAKE_CASE_ = self.quant_conv(_A)
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_A)
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = False , _A = True):
# also go through quantization layer
if not force_not_quantize:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.quantize(_A)
else:
SCREAMING_SNAKE_CASE_ = h
SCREAMING_SNAKE_CASE_ = self.post_quant_conv(_A)
SCREAMING_SNAKE_CASE_ = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None)
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = sample
SCREAMING_SNAKE_CASE_ = self.encode(_A).latents
SCREAMING_SNAKE_CASE_ = self.decode(_A).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
| 620 | 1 |
from __future__ import annotations
from typing import Any
class __snake_case :
def __init__( self , _A):
SCREAMING_SNAKE_CASE_ = num_of_nodes
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = {}
def lowerCAmelCase__ ( self , _A , _A , _A):
self.m_edges.append([u_node, v_node, weight])
def lowerCAmelCase__ ( self , _A):
if self.m_component[u_node] == u_node:
return u_node
return self.find_component(self.m_component[u_node])
def lowerCAmelCase__ ( self , _A):
if self.m_component[u_node] != u_node:
for k in self.m_component:
SCREAMING_SNAKE_CASE_ = self.find_component(_A)
def lowerCAmelCase__ ( self , _A , _A , _A):
if component_size[u_node] <= component_size[v_node]:
SCREAMING_SNAKE_CASE_ = v_node
component_size[v_node] += component_size[u_node]
self.set_component(_A)
elif component_size[u_node] >= component_size[v_node]:
SCREAMING_SNAKE_CASE_ = self.find_component(_A)
component_size[u_node] += component_size[v_node]
self.set_component(_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = [-1] * self.m_num_of_nodes
# A list of components (initialized to all of the nodes)
for node in range(self.m_num_of_nodes):
self.m_component.update({node: node})
component_size.append(1)
SCREAMING_SNAKE_CASE_ = self.m_num_of_nodes
while num_of_components > 1:
for edge in self.m_edges:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = edge
SCREAMING_SNAKE_CASE_ = self.m_component[u]
SCREAMING_SNAKE_CASE_ = self.m_component[v]
if u_component != v_component:
for component in (u_component, v_component):
if (
minimum_weight_edge[component] == -1
or minimum_weight_edge[component][2] > w
):
SCREAMING_SNAKE_CASE_ = [u, v, w]
for edge in minimum_weight_edge:
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = edge
SCREAMING_SNAKE_CASE_ = self.m_component[u]
SCREAMING_SNAKE_CASE_ = self.m_component[v]
if u_component != v_component:
mst_weight += w
self.union(_A , _A , _A)
print(f"""Added edge [{u} - {v}]\nAdded weight: {w}\n""")
num_of_components -= 1
SCREAMING_SNAKE_CASE_ = [-1] * self.m_num_of_nodes
print(f"""The total weight of the minimal spanning tree is: {mst_weight}""")
def _UpperCAmelCase ( ):
"""simple docstring"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
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
UpperCamelCase__ : Optional[int] = logging.getLogger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : torch.nn.Module , _SCREAMING_SNAKE_CASE : BnbQuantizationConfig , _SCREAMING_SNAKE_CASE : Union[str, os.PathLike] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[str, Union[int, str, torch.device]]] = None , _SCREAMING_SNAKE_CASE : Optional[List[str]] = None , _SCREAMING_SNAKE_CASE : Optional[Dict[Union[int, str], Union[int, str]]] = None , _SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , _SCREAMING_SNAKE_CASE : bool = False , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.load_in_abit
SCREAMING_SNAKE_CASE_ = 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.' )
SCREAMING_SNAKE_CASE_ = []
# custom device map
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(device_map.keys() ) > 1:
SCREAMING_SNAKE_CASE_ = [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:
SCREAMING_SNAKE_CASE_ = get_keys_to_not_convert(_SCREAMING_SNAKE_CASE )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(_SCREAMING_SNAKE_CASE )
# compatibility with peft
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = load_in_abit
SCREAMING_SNAKE_CASE_ = get_parameter_device(_SCREAMING_SNAKE_CASE )
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.' )
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
# convert param to the right dtype
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = name.replace('.weight' , '' ).replace('.bias' , '' )
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(_SCREAMING_SNAKE_CASE ):
param.to(_SCREAMING_SNAKE_CASE )
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():
SCREAMING_SNAKE_CASE_ = replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , modules_to_not_convert=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = get_quantized_model_device_map(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_memory=_SCREAMING_SNAKE_CASE , no_split_module_classes=_SCREAMING_SNAKE_CASE , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] )
load_checkpoint_in_model(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=bnb_quantization_config.torch_dtype , offload_folder=_SCREAMING_SNAKE_CASE , offload_state_dict=_SCREAMING_SNAKE_CASE , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(_SCREAMING_SNAKE_CASE , device_map=_SCREAMING_SNAKE_CASE , offload_dir=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : List[str]=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if device_map is None:
if torch.cuda.is_available():
SCREAMING_SNAKE_CASE_ = {'': 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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
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\'.' )
SCREAMING_SNAKE_CASE_ = {}
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 )
} )
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = special_dtypes
SCREAMING_SNAKE_CASE_ = no_split_module_classes
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
SCREAMING_SNAKE_CASE_ = get_balanced_memory(
_SCREAMING_SNAKE_CASE , low_zero=(device_map == 'balanced_low_0') , max_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
SCREAMING_SNAKE_CASE_ = max_memory
SCREAMING_SNAKE_CASE_ = infer_auto_device_map(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
# check if don't have any quantized module on the cpu
SCREAMING_SNAKE_CASE_ = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
SCREAMING_SNAKE_CASE_ = {
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int=None , _SCREAMING_SNAKE_CASE : Union[str, Any]=None ):
"""simple docstring"""
if modules_to_not_convert is None:
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Optional[Any]=None , _SCREAMING_SNAKE_CASE : str=None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = False
for name, module in model.named_children():
if current_key_name is None:
SCREAMING_SNAKE_CASE_ = []
current_key_name.append(_SCREAMING_SNAKE_CASE )
if isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
SCREAMING_SNAKE_CASE_ = '.'.join(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = 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:
SCREAMING_SNAKE_CASE_ = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_SCREAMING_SNAKE_CASE , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
SCREAMING_SNAKE_CASE_ = 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' )
SCREAMING_SNAKE_CASE_ = module.weight.data
if module.bias is not None:
SCREAMING_SNAKE_CASE_ = module.bias.data
bnb_module.requires_grad_(_SCREAMING_SNAKE_CASE )
setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = True
if len(list(module.children() ) ) > 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _replace_with_bnb_layers(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
with init_empty_weights():
SCREAMING_SNAKE_CASE_ = deepcopy(_SCREAMING_SNAKE_CASE ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
SCREAMING_SNAKE_CASE_ = find_tied_parameters(_SCREAMING_SNAKE_CASE )
# For compatibility with Accelerate < 0.18
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
SCREAMING_SNAKE_CASE_ = sum(_SCREAMING_SNAKE_CASE , [] )
SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE ) > 0
# Check if it is a base model
SCREAMING_SNAKE_CASE_ = False
if hasattr(_SCREAMING_SNAKE_CASE , 'base_model_prefix' ):
SCREAMING_SNAKE_CASE_ = not hasattr(_SCREAMING_SNAKE_CASE , 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
SCREAMING_SNAKE_CASE_ = list(model.named_children() )
SCREAMING_SNAKE_CASE_ = [list_modules[-1][0]]
# add last module together with tied weights
SCREAMING_SNAKE_CASE_ = set(_SCREAMING_SNAKE_CASE ) - set(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = list(set(_SCREAMING_SNAKE_CASE ) ) + list(_SCREAMING_SNAKE_CASE )
# remove ".weight" from the keys
SCREAMING_SNAKE_CASE_ = ['.weight', '.bias']
SCREAMING_SNAKE_CASE_ = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
SCREAMING_SNAKE_CASE_ = name.replace(_SCREAMING_SNAKE_CASE , '' )
filtered_module_names.append(_SCREAMING_SNAKE_CASE )
return filtered_module_names
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for m in model.modules():
if isinstance(_SCREAMING_SNAKE_CASE , bnb.nn.Linearabit ):
return True
return False
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : nn.Module ):
"""simple docstring"""
return next(parameter.parameters() ).device
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
if fpaa_statistics is None:
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 0 , dtype=_SCREAMING_SNAKE_CASE , value=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = param_name
SCREAMING_SNAKE_CASE_ = model
if "." in tensor_name:
SCREAMING_SNAKE_CASE_ = tensor_name.split('.' )
for split in splits[:-1]:
SCREAMING_SNAKE_CASE_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if new_module is None:
raise ValueError(f"""{module} has no attribute {split}.""" )
SCREAMING_SNAKE_CASE_ = new_module
SCREAMING_SNAKE_CASE_ = splits[-1]
# offload weights
SCREAMING_SNAKE_CASE_ = False
offload_weight(module._parameters[tensor_name] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
if hasattr(module._parameters[tensor_name] , 'SCB' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE , )
else:
offload_weight(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
offload_weight(_SCREAMING_SNAKE_CASE , param_name.replace('weight' , 'SCB' ) , _SCREAMING_SNAKE_CASE , index=_SCREAMING_SNAKE_CASE )
set_module_tensor_to_device(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'meta' , dtype=_SCREAMING_SNAKE_CASE , value=torch.empty(*param.size() ) )
| 620 | 1 |
import math
from enum import Enum
from typing import Optional, Union
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR
from .utils import logging
UpperCamelCase__ : List[str] = logging.get_logger(__name__)
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = 'linear'
__lowerCAmelCase : Any = 'cosine'
__lowerCAmelCase : List[Any] = 'cosine_with_restarts'
__lowerCAmelCase : int = 'polynomial'
__lowerCAmelCase : int = 'constant'
__lowerCAmelCase : Optional[Any] = 'constant_with_warmup'
__lowerCAmelCase : Tuple = 'piecewise_constant'
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optimizer , _SCREAMING_SNAKE_CASE : int = -1 ):
"""simple docstring"""
return LambdaLR(_SCREAMING_SNAKE_CASE , lambda _SCREAMING_SNAKE_CASE : 1 , last_epoch=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optimizer , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int = -1 ):
"""simple docstring"""
def lr_lambda(_SCREAMING_SNAKE_CASE : int ):
if current_step < num_warmup_steps:
return float(_SCREAMING_SNAKE_CASE ) / float(max(1.0 , _SCREAMING_SNAKE_CASE ) )
return 1.0
return LambdaLR(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optimizer , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int = -1 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = step_rules.split(',' )
for rule_str in rule_list[:-1]:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = rule_str.split(':' )
SCREAMING_SNAKE_CASE_ = int(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = float(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = value
SCREAMING_SNAKE_CASE_ = float(rule_list[-1] )
def create_rules_function(_SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] ):
def rule_func(_SCREAMING_SNAKE_CASE : int ) -> float:
SCREAMING_SNAKE_CASE_ = sorted(rules_dict.keys() )
for i, sorted_step in enumerate(_SCREAMING_SNAKE_CASE ):
if steps < sorted_step:
return rules_dict[sorted_steps[i]]
return last_lr_multiple
return rule_func
SCREAMING_SNAKE_CASE_ = create_rules_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
return LambdaLR(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any=-1 ):
"""simple docstring"""
def lr_lambda(_SCREAMING_SNAKE_CASE : int ):
if current_step < num_warmup_steps:
return float(_SCREAMING_SNAKE_CASE ) / float(max(1 , _SCREAMING_SNAKE_CASE ) )
return max(
0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) )
return LambdaLR(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optimizer , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : float = 0.5 , _SCREAMING_SNAKE_CASE : int = -1 ):
"""simple docstring"""
def lr_lambda(_SCREAMING_SNAKE_CASE : Dict ):
if current_step < num_warmup_steps:
return float(_SCREAMING_SNAKE_CASE ) / float(max(1 , _SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) )
return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(_SCREAMING_SNAKE_CASE ) * 2.0 * progress )) )
return LambdaLR(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optimizer , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int = 1 , _SCREAMING_SNAKE_CASE : int = -1 ):
"""simple docstring"""
def lr_lambda(_SCREAMING_SNAKE_CASE : Tuple ):
if current_step < num_warmup_steps:
return float(_SCREAMING_SNAKE_CASE ) / float(max(1 , _SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) )
if progress >= 1.0:
return 0.0
return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(_SCREAMING_SNAKE_CASE ) * progress) % 1.0) )) )
return LambdaLR(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Union[str, Any]=1E-7 , _SCREAMING_SNAKE_CASE : List[str]=1.0 , _SCREAMING_SNAKE_CASE : int=-1 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = optimizer.defaults['lr']
if not (lr_init > lr_end):
raise ValueError(f"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" )
def lr_lambda(_SCREAMING_SNAKE_CASE : int ):
if current_step < num_warmup_steps:
return float(_SCREAMING_SNAKE_CASE ) / float(max(1 , _SCREAMING_SNAKE_CASE ) )
elif current_step > num_training_steps:
return lr_end / lr_init # as LambdaLR multiplies by lr_init
else:
SCREAMING_SNAKE_CASE_ = lr_init - lr_end
SCREAMING_SNAKE_CASE_ = num_training_steps - num_warmup_steps
SCREAMING_SNAKE_CASE_ = 1 - (current_step - num_warmup_steps) / decay_steps
SCREAMING_SNAKE_CASE_ = lr_range * pct_remaining**power + lr_end
return decay / lr_init # as LambdaLR multiplies by lr_init
return LambdaLR(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
UpperCamelCase__ : str = {
SchedulerType.LINEAR: get_linear_schedule_with_warmup,
SchedulerType.COSINE: get_cosine_schedule_with_warmup,
SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup,
SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup,
SchedulerType.CONSTANT: get_constant_schedule,
SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup,
SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule,
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, SchedulerType] , _SCREAMING_SNAKE_CASE : Optimizer , _SCREAMING_SNAKE_CASE : Optional[str] = None , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : int = 1 , _SCREAMING_SNAKE_CASE : float = 1.0 , _SCREAMING_SNAKE_CASE : int = -1 , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = SchedulerType(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = TYPE_TO_SCHEDULER_FUNCTION[name]
if name == SchedulerType.CONSTANT:
return schedule_func(_SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE )
if name == SchedulerType.PIECEWISE_CONSTANT:
return schedule_func(_SCREAMING_SNAKE_CASE , step_rules=_SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE )
# All other schedulers require `num_warmup_steps`
if num_warmup_steps is None:
raise ValueError(f"""{name} requires `num_warmup_steps`, please provide that argument.""" )
if name == SchedulerType.CONSTANT_WITH_WARMUP:
return schedule_func(_SCREAMING_SNAKE_CASE , num_warmup_steps=_SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE )
# All other schedulers require `num_training_steps`
if num_training_steps is None:
raise ValueError(f"""{name} requires `num_training_steps`, please provide that argument.""" )
if name == SchedulerType.COSINE_WITH_RESTARTS:
return schedule_func(
_SCREAMING_SNAKE_CASE , num_warmup_steps=_SCREAMING_SNAKE_CASE , num_training_steps=_SCREAMING_SNAKE_CASE , num_cycles=_SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE , )
if name == SchedulerType.POLYNOMIAL:
return schedule_func(
_SCREAMING_SNAKE_CASE , num_warmup_steps=_SCREAMING_SNAKE_CASE , num_training_steps=_SCREAMING_SNAKE_CASE , power=_SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE , )
return schedule_func(
_SCREAMING_SNAKE_CASE , num_warmup_steps=_SCREAMING_SNAKE_CASE , num_training_steps=_SCREAMING_SNAKE_CASE , last_epoch=_SCREAMING_SNAKE_CASE )
| 620 |
import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__)
UpperCamelCase__ : Optional[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
# See all BART models at https://huggingface.co/models?filter=bart
UpperCamelCase__ : List[str] = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
}
UpperCamelCase__ : str = {
"facebook/bart-base": 1_024,
"facebook/bart-large": 1_024,
"facebook/bart-large-mnli": 1_024,
"facebook/bart-large-cnn": 1_024,
"facebook/bart-large-xsum": 1_024,
"yjernite/bart_eli5": 1_024,
}
@lru_cache()
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = (
list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) )
)
SCREAMING_SNAKE_CASE_ = bs[:]
SCREAMING_SNAKE_CASE_ = 0
for b in range(2**8 ):
if b not in bs:
bs.append(_SCREAMING_SNAKE_CASE )
cs.append(2**8 + n )
n += 1
SCREAMING_SNAKE_CASE_ = [chr(_SCREAMING_SNAKE_CASE ) for n in cs]
return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = set()
SCREAMING_SNAKE_CASE_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
SCREAMING_SNAKE_CASE_ = char
return pairs
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : str = VOCAB_FILES_NAMES
__lowerCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP
__lowerCAmelCase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowerCAmelCase : List[Any] = ['input_ids', 'attention_mask']
def __init__( self , _A , _A , _A="replace" , _A="<s>" , _A="</s>" , _A="</s>" , _A="<s>" , _A="<unk>" , _A="<pad>" , _A="<mask>" , _A=False , **_A , ):
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else bos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else eos_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else sep_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else cls_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else unk_token
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
SCREAMING_SNAKE_CASE_ = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else mask_token
super().__init__(
errors=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , cls_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , **_A , )
with open(_A , encoding='utf-8') as vocab_handle:
SCREAMING_SNAKE_CASE_ = json.load(_A)
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.encoder.items()}
SCREAMING_SNAKE_CASE_ = errors # how to handle errors in decoding
SCREAMING_SNAKE_CASE_ = bytes_to_unicode()
SCREAMING_SNAKE_CASE_ = {v: k for k, v in self.byte_encoder.items()}
with open(_A , encoding='utf-8') as merges_handle:
SCREAMING_SNAKE_CASE_ = merges_handle.read().split('\n')[1:-1]
SCREAMING_SNAKE_CASE_ = [tuple(merge.split()) for merge in bpe_merges]
SCREAMING_SNAKE_CASE_ = dict(zip(_A , range(len(_A))))
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
SCREAMING_SNAKE_CASE_ = re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+')
@property
def lowerCAmelCase__ ( self):
return len(self.encoder)
def lowerCAmelCase__ ( self):
return dict(self.encoder , **self.added_tokens_encoder)
def lowerCAmelCase__ ( self , _A):
if token in self.cache:
return self.cache[token]
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
if not pairs:
return token
while True:
SCREAMING_SNAKE_CASE_ = min(_A , key=lambda _A: self.bpe_ranks.get(_A , float('inf')))
if bigram not in self.bpe_ranks:
break
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = bigram
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
while i < len(_A):
try:
SCREAMING_SNAKE_CASE_ = word.index(_A , _A)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
SCREAMING_SNAKE_CASE_ = j
if word[i] == first and i < len(_A) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
SCREAMING_SNAKE_CASE_ = tuple(_A)
SCREAMING_SNAKE_CASE_ = new_word
if len(_A) == 1:
break
else:
SCREAMING_SNAKE_CASE_ = get_pairs(_A)
SCREAMING_SNAKE_CASE_ = ' '.join(_A)
SCREAMING_SNAKE_CASE_ = word
return word
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = []
for token in re.findall(self.pat , _A):
SCREAMING_SNAKE_CASE_ = ''.join(
self.byte_encoder[b] for b in token.encode('utf-8')) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_A).split(' '))
return bpe_tokens
def lowerCAmelCase__ ( self , _A):
return self.encoder.get(_A , self.encoder.get(self.unk_token))
def lowerCAmelCase__ ( self , _A):
return self.decoder.get(_A)
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = ''.join(_A)
SCREAMING_SNAKE_CASE_ = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8' , errors=self.errors)
return text
def lowerCAmelCase__ ( self , _A , _A = None):
if not os.path.isdir(_A):
logger.error(f"""Vocabulary path ({save_directory}) should be a directory""")
return
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'])
SCREAMING_SNAKE_CASE_ = os.path.join(
_A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'])
with open(_A , 'w' , encoding='utf-8') as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_A , ensure_ascii=_A) + '\n')
SCREAMING_SNAKE_CASE_ = 0
with open(_A , 'w' , encoding='utf-8') as writer:
writer.write('#version: 0.2\n')
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _A: kv[1]):
if index != token_index:
logger.warning(
f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
' Please check that the tokenizer is not corrupted!')
SCREAMING_SNAKE_CASE_ = token_index
writer.write(' '.join(_A) + '\n')
index += 1
return vocab_file, merge_file
def lowerCAmelCase__ ( self , _A , _A = None):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def lowerCAmelCase__ ( self , _A , _A = None , _A = False):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A)
if token_ids_a is None:
return [1] + ([0] * len(_A)) + [1]
return [1] + ([0] * len(_A)) + [1, 1] + ([0] * len(_A)) + [1]
def lowerCAmelCase__ ( self , _A , _A = None):
SCREAMING_SNAKE_CASE_ = [self.sep_token_id]
SCREAMING_SNAKE_CASE_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
def lowerCAmelCase__ ( self , _A , _A=False , **_A):
SCREAMING_SNAKE_CASE_ = kwargs.pop('add_prefix_space' , self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(_A) > 0 and not text[0].isspace()):
SCREAMING_SNAKE_CASE_ = ' ' + text
return (text, kwargs)
| 620 | 1 |
from itertools import product
from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = k_size // 2
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = mgrid[0 - center : k_size - center, 0 - center : k_size - center]
SCREAMING_SNAKE_CASE_ = 1 / (2 * pi * sigma) * exp(-(square(_SCREAMING_SNAKE_CASE ) + square(_SCREAMING_SNAKE_CASE )) / (2 * square(_SCREAMING_SNAKE_CASE )) )
return g
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = image.shape[0], image.shape[1]
# dst image height and width
SCREAMING_SNAKE_CASE_ = height - k_size + 1
SCREAMING_SNAKE_CASE_ = width - k_size + 1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
SCREAMING_SNAKE_CASE_ = zeros((dst_height * dst_width, k_size * k_size) )
SCREAMING_SNAKE_CASE_ = 0
for i, j in product(range(_SCREAMING_SNAKE_CASE ) , range(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE_ = ravel(image[i : i + k_size, j : j + k_size] )
SCREAMING_SNAKE_CASE_ = window
row += 1
# turn the kernel into shape(k*k, 1)
SCREAMING_SNAKE_CASE_ = gen_gaussian_kernel(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = ravel(_SCREAMING_SNAKE_CASE )
# reshape and get the dst image
SCREAMING_SNAKE_CASE_ = dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).astype(_SCREAMING_SNAKE_CASE )
return dst
if __name__ == "__main__":
# read original image
UpperCamelCase__ : Union[str, Any] = imread(r"../image_data/lena.jpg")
# turn image in gray scale value
UpperCamelCase__ : int = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
UpperCamelCase__ : Dict = gaussian_filter(gray, 3, sigma=1)
UpperCamelCase__ : List[Any] = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow("gaussian filter with 3x3 mask", gaussianaxa)
imshow("gaussian filter with 5x5 mask", gaussianaxa)
waitKey()
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Optional[int] = {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
),
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Optional[int] = 'dpr'
def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1E-12 , _A=0 , _A="absolute" , _A = 0 , **_A , ):
super().__init__(pad_token_id=_A , **_A)
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = projection_dim
SCREAMING_SNAKE_CASE_ = position_embedding_type
| 620 | 1 |
import os
import unittest
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import (
VOCAB_FILES_NAMES,
BasicTokenizer,
BertTokenizer,
WordpieceTokenizer,
_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 __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Any = BertTokenizer
__lowerCAmelCase : List[Any] = BertTokenizerFast
__lowerCAmelCase : Union[str, Any] = True
__lowerCAmelCase : int = True
__lowerCAmelCase : Optional[int] = filter_non_english
def lowerCAmelCase__ ( self):
super().setUp()
SCREAMING_SNAKE_CASE_ = [
'[UNK]',
'[CLS]',
'[SEP]',
'[PAD]',
'[MASK]',
'want',
'##want',
'##ed',
'wa',
'un',
'runn',
'##ing',
',',
'low',
'lowest',
]
SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'])
with open(self.vocab_file , 'w' , encoding='utf-8') as vocab_writer:
vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]))
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = 'UNwant\u00E9d,running'
SCREAMING_SNAKE_CASE_ = 'unwanted, running'
return input_text, output_text
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tokenizer_class(self.vocab_file)
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize('UNwant\u00E9d,running')
self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'])
self.assertListEqual(tokenizer.convert_tokens_to_ids(_A) , [9, 6, 7, 12, 10, 11])
def lowerCAmelCase__ ( self):
if not self.test_rust_tokenizer:
return
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE_ = 'UNwant\u00E9d,running'
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(_A)
SCREAMING_SNAKE_CASE_ = rust_tokenizer.tokenize(_A)
self.assertListEqual(_A , _A)
SCREAMING_SNAKE_CASE_ = tokenizer.encode(_A , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = rust_tokenizer.encode(_A , add_special_tokens=_A)
self.assertListEqual(_A , _A)
SCREAMING_SNAKE_CASE_ = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE_ = tokenizer.encode(_A)
SCREAMING_SNAKE_CASE_ = rust_tokenizer.encode(_A)
self.assertListEqual(_A , _A)
# With lower casing
SCREAMING_SNAKE_CASE_ = self.get_tokenizer(do_lower_case=_A)
SCREAMING_SNAKE_CASE_ = self.get_rust_tokenizer(do_lower_case=_A)
SCREAMING_SNAKE_CASE_ = 'UNwant\u00E9d,running'
SCREAMING_SNAKE_CASE_ = tokenizer.tokenize(_A)
SCREAMING_SNAKE_CASE_ = rust_tokenizer.tokenize(_A)
self.assertListEqual(_A , _A)
SCREAMING_SNAKE_CASE_ = tokenizer.encode(_A , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = rust_tokenizer.encode(_A , add_special_tokens=_A)
self.assertListEqual(_A , _A)
SCREAMING_SNAKE_CASE_ = self.get_rust_tokenizer()
SCREAMING_SNAKE_CASE_ = tokenizer.encode(_A)
SCREAMING_SNAKE_CASE_ = rust_tokenizer.encode(_A)
self.assertListEqual(_A , _A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz') , ['ah', '\u535A', '\u63A8', 'zz'])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(do_lower_case=_A)
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ') , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(do_lower_case=_A , strip_accents=_A)
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(do_lower_case=_A , strip_accents=_A)
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ') , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'])
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]') , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'])
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BasicTokenizer()
SCREAMING_SNAKE_CASE_ = 'a\n\'ll !!to?\'d of, can\'t.'
SCREAMING_SNAKE_CASE_ = ['a', '\'', 'll', '!', '!', 'to', '?', '\'', 'd', 'of', ',', 'can', '\'', 't', '.']
self.assertListEqual(tokenizer.tokenize(_A) , _A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing']
SCREAMING_SNAKE_CASE_ = {}
for i, token in enumerate(_A):
SCREAMING_SNAKE_CASE_ = i
SCREAMING_SNAKE_CASE_ = WordpieceTokenizer(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 lowerCAmelCase__ ( self):
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 lowerCAmelCase__ ( self):
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 lowerCAmelCase__ ( self):
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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.get_tokenizer()
SCREAMING_SNAKE_CASE_ = self.get_rust_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]']])
self.assertListEqual(
[rust_tokenizer.tokenize(_A) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']])
@slow
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tokenizer_class.from_pretrained('bert-base-uncased')
SCREAMING_SNAKE_CASE_ = tokenizer.encode('sequence builders' , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer.encode('multi-sequence build' , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer.build_inputs_with_special_tokens(_A)
SCREAMING_SNAKE_CASE_ = tokenizer.build_inputs_with_special_tokens(_A , _A)
assert encoded_sentence == [101] + text + [102]
assert encoded_pair == [101] + text + [102] + text_a + [102]
def lowerCAmelCase__ ( self):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
SCREAMING_SNAKE_CASE_ = self.rust_tokenizer_class.from_pretrained(_A , **_A)
SCREAMING_SNAKE_CASE_ = f"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence."""
SCREAMING_SNAKE_CASE_ = tokenizer_r.encode_plus(
_A , return_attention_mask=_A , return_token_type_ids=_A , return_offsets_mapping=_A , add_special_tokens=_A , )
SCREAMING_SNAKE_CASE_ = tokenizer_r.do_lower_case if hasattr(_A , 'do_lower_case') else False
SCREAMING_SNAKE_CASE_ = (
[
((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 lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ['的', '人', '有']
SCREAMING_SNAKE_CASE_ = ''.join(_A)
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = self.tokenizer_class.from_pretrained(_A , **_A)
SCREAMING_SNAKE_CASE_ = self.rust_tokenizer_class.from_pretrained(_A , **_A)
SCREAMING_SNAKE_CASE_ = tokenizer_p.encode(_A , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer_r.encode(_A , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer_r.convert_ids_to_tokens(_A)
SCREAMING_SNAKE_CASE_ = 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)
SCREAMING_SNAKE_CASE_ = False
SCREAMING_SNAKE_CASE_ = self.rust_tokenizer_class.from_pretrained(_A , **_A)
SCREAMING_SNAKE_CASE_ = self.tokenizer_class.from_pretrained(_A , **_A)
SCREAMING_SNAKE_CASE_ = tokenizer_r.encode(_A , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer_p.encode(_A , add_special_tokens=_A)
SCREAMING_SNAKE_CASE_ = tokenizer_r.convert_ids_to_tokens(_A)
SCREAMING_SNAKE_CASE_ = tokenizer_p.convert_ids_to_tokens(_A)
# it is expected that only the first Chinese character is not preceded by "##".
SCREAMING_SNAKE_CASE_ = [
f"""##{token}""" if idx != 0 else token for idx, token in enumerate(_A)
]
self.assertListEqual(_A , _A)
self.assertListEqual(_A , _A)
| 620 |
import pytest
import datasets
# Import fixture modules as plugins
UpperCamelCase__ : Union[str, Any] = ["tests.fixtures.files", "tests.fixtures.hub", "tests.fixtures.fsspec"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Dict ):
"""simple docstring"""
for item in items:
if any(marker in item.keywords for marker in ['integration', 'unit'] ):
continue
item.add_marker(pytest.mark.unit )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = tmp_path_factory.getbasetemp() / 'cache'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'datasets'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'metrics'
SCREAMING_SNAKE_CASE_ = test_hf_cache_home / 'modules'
monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads'
monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
SCREAMING_SNAKE_CASE_ = test_hf_datasets_cache / 'downloads' / 'extracted'
monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(_SCREAMING_SNAKE_CASE ) )
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE , scope='session' )
def _UpperCAmelCase ( ):
"""simple docstring"""
datasets.disable_progress_bar()
@pytest.fixture(autouse=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , _SCREAMING_SNAKE_CASE )
@pytest.fixture
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple ):
"""simple docstring"""
monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , _SCREAMING_SNAKE_CASE )
| 620 | 1 |
from __future__ import annotations
import inspect
import unittest
import numpy as np
from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFDeiTForImageClassification,
TFDeiTForImageClassificationWithTeacher,
TFDeiTForMaskedImageModeling,
TFDeiTModel,
)
from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DeiTImageProcessor
class __snake_case :
def __init__( self , _A , _A=13 , _A=30 , _A=2 , _A=3 , _A=True , _A=True , _A=32 , _A=2 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=10 , _A=0.0_2 , _A=3 , _A=None , _A=2 , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = patch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = type_sequence_label_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = scope
SCREAMING_SNAKE_CASE_ = encoder_stride
# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
SCREAMING_SNAKE_CASE_ = (image_size // patch_size) ** 2
SCREAMING_SNAKE_CASE_ = num_patches + 2
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size] , self.type_sequence_label_size)
SCREAMING_SNAKE_CASE_ = self.get_config()
return config, pixel_values, labels
def lowerCAmelCase__ ( self):
return DeiTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def lowerCAmelCase__ ( self , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = TFDeiTModel(config=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def lowerCAmelCase__ ( self , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = TFDeiTForMaskedImageModeling(config=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size))
# test greyscale images
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = TFDeiTForMaskedImageModeling(_A)
SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
SCREAMING_SNAKE_CASE_ = model(_A)
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size))
def lowerCAmelCase__ ( self , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = self.type_sequence_label_size
SCREAMING_SNAKE_CASE_ = TFDeiTForImageClassification(_A)
SCREAMING_SNAKE_CASE_ = model(_A , labels=_A)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
# test greyscale images
SCREAMING_SNAKE_CASE_ = 1
SCREAMING_SNAKE_CASE_ = TFDeiTForImageClassification(_A)
SCREAMING_SNAKE_CASE_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
SCREAMING_SNAKE_CASE_ = model(_A , labels=_A)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Any = (
(
TFDeiTModel,
TFDeiTForImageClassification,
TFDeiTForImageClassificationWithTeacher,
TFDeiTForMaskedImageModeling,
)
if is_tf_available()
else ()
)
__lowerCAmelCase : str = (
{
'feature-extraction': TFDeiTModel,
'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
}
if is_tf_available()
else {}
)
__lowerCAmelCase : Tuple = False
__lowerCAmelCase : int = False
__lowerCAmelCase : Any = False
__lowerCAmelCase : List[Any] = False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TFDeiTModelTester(self)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=37)
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
@unittest.skip(reason='DeiT does not use inputs_embeds')
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
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(_A)
self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer))
SCREAMING_SNAKE_CASE_ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_A , tf.keras.layers.Dense))
def lowerCAmelCase__ ( self):
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(_A)
SCREAMING_SNAKE_CASE_ = inspect.signature(model.call)
# 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] , _A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_A)
def lowerCAmelCase__ ( self , _A , _A , _A=False):
SCREAMING_SNAKE_CASE_ = super()._prepare_for_class(_A , _A , return_labels=_A)
if return_labels:
if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters:
del inputs_dict["labels"]
return inputs_dict
@slow
def lowerCAmelCase__ ( self):
for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE_ = TFDeiTModel.from_pretrained(_A)
self.assertIsNotNone(_A)
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_tf
@require_vision
class __snake_case ( unittest.TestCase ):
@cached_property
def lowerCAmelCase__ ( self):
return (
DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224')
if is_vision_available()
else None
)
@slow
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224')
SCREAMING_SNAKE_CASE_ = self.default_image_processor
SCREAMING_SNAKE_CASE_ = prepare_img()
SCREAMING_SNAKE_CASE_ = image_processor(images=_A , return_tensors='tf')
# forward pass
SCREAMING_SNAKE_CASE_ = model(**_A)
# verify the logits
SCREAMING_SNAKE_CASE_ = tf.TensorShape((1, 1000))
self.assertEqual(outputs.logits.shape , _A)
SCREAMING_SNAKE_CASE_ = tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1])
self.assertTrue(np.allclose(outputs.logits[0, :3] , _A , atol=1E-4))
| 620 |
from typing import List
import numpy as np
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {key: len(_SCREAMING_SNAKE_CASE ) for key, value in gen_kwargs.items() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
'Sharding is ambiguous for this dataset: '
+ 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
+ '\n'.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items() )
+ '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
+ 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
) )
SCREAMING_SNAKE_CASE_ = max(lists_lengths.values() , default=0 )
return max(1 , _SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
for group_idx in range(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
SCREAMING_SNAKE_CASE_ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
SCREAMING_SNAKE_CASE_ = range(_SCREAMING_SNAKE_CASE , start + num_shards_to_add )
shards_indices_per_group.append(_SCREAMING_SNAKE_CASE )
return shards_indices_per_group
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = _number_of_shards_in_gen_kwargs(_SCREAMING_SNAKE_CASE )
if num_shards == 1:
return [dict(_SCREAMING_SNAKE_CASE )]
else:
SCREAMING_SNAKE_CASE_ = _distribute_shards(num_shards=_SCREAMING_SNAKE_CASE , max_num_jobs=_SCREAMING_SNAKE_CASE )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(_SCREAMING_SNAKE_CASE ) )
]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[dict] ):
"""simple docstring"""
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key] , _SCREAMING_SNAKE_CASE )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : np.random.Generator , _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = {len(_SCREAMING_SNAKE_CASE ) for value in gen_kwargs.values() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
SCREAMING_SNAKE_CASE_ = {}
for size in list_sizes:
SCREAMING_SNAKE_CASE_ = list(range(_SCREAMING_SNAKE_CASE ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
SCREAMING_SNAKE_CASE_ = dict(_SCREAMING_SNAKE_CASE )
for key, value in shuffled_kwargs.items():
if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = [value[i] for i in indices_per_size[len(_SCREAMING_SNAKE_CASE )]]
return shuffled_kwargs
| 620 | 1 |
import unittest
import numpy as np
import torch
from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device
UpperCamelCase__ : List[Any] = False
class __snake_case ( unittest.TestCase ):
pass
@slow
@require_torch_gpu
class __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion')
pipe.to(_A)
pipe.set_progress_bar_config(disable=_A)
SCREAMING_SNAKE_CASE_ = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg')
SCREAMING_SNAKE_CASE_ = torch.manual_seed(0)
SCREAMING_SNAKE_CASE_ = pipe(
image=_A , generator=_A , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images
SCREAMING_SNAKE_CASE_ = image[0, 253:256, 253:256, -1]
assert image.shape == (1, 512, 512, 3)
SCREAMING_SNAKE_CASE_ = np.array([0.0_4_4_1, 0.0_4_6_9, 0.0_5_0_7, 0.0_5_7_5, 0.0_6_3_2, 0.0_6_5_0, 0.0_8_6_5, 0.0_9_0_9, 0.0_9_4_5])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
| 620 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
UpperCamelCase__ : List[str] = {
"microsoft/biogpt": "https://huggingface.co/microsoft/biogpt/resolve/main/config.json",
# See all BioGPT models at https://huggingface.co/models?filter=biogpt
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Any = 'biogpt'
def __init__( self , _A=42384 , _A=1024 , _A=24 , _A=16 , _A=4096 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1024 , _A=0.0_2 , _A=1E-12 , _A=True , _A=True , _A=0.0 , _A=0.0 , _A=1 , _A=0 , _A=2 , **_A , ):
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = scale_embedding
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = layerdrop
SCREAMING_SNAKE_CASE_ = activation_dropout
super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A)
| 620 | 1 |
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__ : Any = logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase__ )
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , **_A):
super().__init__(**_A)
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 , _A , **_A):
return super().__call__(_A , **_A)
def lowerCAmelCase__ ( self , **_A):
SCREAMING_SNAKE_CASE_ = {}
if "candidate_labels" in kwargs:
SCREAMING_SNAKE_CASE_ = kwargs['candidate_labels']
if "hypothesis_template" in kwargs:
SCREAMING_SNAKE_CASE_ = kwargs['hypothesis_template']
return preprocess_params, {}, {}
def lowerCAmelCase__ ( self , _A , _A=None , _A="This is a photo of {}."):
SCREAMING_SNAKE_CASE_ = load_image(_A)
SCREAMING_SNAKE_CASE_ = self.image_processor(images=[image] , return_tensors=self.framework)
SCREAMING_SNAKE_CASE_ = candidate_labels
SCREAMING_SNAKE_CASE_ = [hypothesis_template.format(_A) for x in candidate_labels]
SCREAMING_SNAKE_CASE_ = self.tokenizer(_A , return_tensors=self.framework , padding=_A)
SCREAMING_SNAKE_CASE_ = [text_inputs]
return inputs
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = model_inputs.pop('candidate_labels')
SCREAMING_SNAKE_CASE_ = model_inputs.pop('text_inputs')
if isinstance(text_inputs[0] , _A):
SCREAMING_SNAKE_CASE_ = text_inputs[0]
else:
# Batching case.
SCREAMING_SNAKE_CASE_ = text_inputs[0][0]
SCREAMING_SNAKE_CASE_ = self.model(**_A , **_A)
SCREAMING_SNAKE_CASE_ = {
'candidate_labels': candidate_labels,
'logits': outputs.logits_per_image,
}
return model_outputs
def lowerCAmelCase__ ( self , _A):
SCREAMING_SNAKE_CASE_ = model_outputs.pop('candidate_labels')
SCREAMING_SNAKE_CASE_ = model_outputs['logits'][0]
if self.framework == "pt":
SCREAMING_SNAKE_CASE_ = logits.softmax(dim=-1).squeeze(-1)
SCREAMING_SNAKE_CASE_ = probs.tolist()
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = [scores]
elif self.framework == "tf":
SCREAMING_SNAKE_CASE_ = stable_softmax(_A , axis=-1)
SCREAMING_SNAKE_CASE_ = probs.numpy().tolist()
else:
raise ValueError(f"""Unsupported framework: {self.framework}""")
SCREAMING_SNAKE_CASE_ = [
{'score': score, 'label': candidate_label}
for score, candidate_label in sorted(zip(_A , _A) , key=lambda _A: -x[0])
]
return result
| 620 |
from typing import Dict, List, Optional, Tuple, Union
import torch
from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __snake_case ( lowerCAmelCase__ ):
def __init__( self , _A , _A , _A , _A = None , ):
super().__init__()
self.register_modules(transformer=_A , vae=_A , scheduler=_A)
# create a imagenet -> id dictionary for easier use
SCREAMING_SNAKE_CASE_ = {}
if idalabel is not None:
for key, value in idalabel.items():
for label in value.split(','):
SCREAMING_SNAKE_CASE_ = int(_A)
SCREAMING_SNAKE_CASE_ = dict(sorted(self.labels.items()))
def lowerCAmelCase__ ( self , _A):
if not isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = list(_A)
for l in label:
if l not in self.labels:
raise ValueError(
f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""")
return [self.labels[l] for l in label]
@torch.no_grad()
def __call__( self , _A , _A = 4.0 , _A = None , _A = 50 , _A = "pil" , _A = True , ):
SCREAMING_SNAKE_CASE_ = len(_A)
SCREAMING_SNAKE_CASE_ = self.transformer.config.sample_size
SCREAMING_SNAKE_CASE_ = self.transformer.config.in_channels
SCREAMING_SNAKE_CASE_ = randn_tensor(
shape=(batch_size, latent_channels, latent_size, latent_size) , generator=_A , device=self.device , dtype=self.transformer.dtype , )
SCREAMING_SNAKE_CASE_ = torch.cat([latents] * 2) if guidance_scale > 1 else latents
SCREAMING_SNAKE_CASE_ = torch.tensor(_A , device=self.device).reshape(-1)
SCREAMING_SNAKE_CASE_ = torch.tensor([1000] * batch_size , device=self.device)
SCREAMING_SNAKE_CASE_ = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels
# set step values
self.scheduler.set_timesteps(_A)
for t in self.progress_bar(self.scheduler.timesteps):
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ = latent_model_input[: len(_A) // 2]
SCREAMING_SNAKE_CASE_ = torch.cat([half, half] , dim=0)
SCREAMING_SNAKE_CASE_ = self.scheduler.scale_model_input(_A , _A)
SCREAMING_SNAKE_CASE_ = t
if not torch.is_tensor(_A):
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
# This would be a good case for the `match` statement (Python 3.10+)
SCREAMING_SNAKE_CASE_ = latent_model_input.device.type == 'mps'
if isinstance(_A , _A):
SCREAMING_SNAKE_CASE_ = torch.floataa if is_mps else torch.floataa
else:
SCREAMING_SNAKE_CASE_ = torch.intaa if is_mps else torch.intaa
SCREAMING_SNAKE_CASE_ = torch.tensor([timesteps] , dtype=_A , device=latent_model_input.device)
elif len(timesteps.shape) == 0:
SCREAMING_SNAKE_CASE_ = timesteps[None].to(latent_model_input.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
SCREAMING_SNAKE_CASE_ = timesteps.expand(latent_model_input.shape[0])
# predict noise model_output
SCREAMING_SNAKE_CASE_ = self.transformer(
_A , timestep=_A , class_labels=_A).sample
# perform guidance
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , len(_A) // 2 , dim=0)
SCREAMING_SNAKE_CASE_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps)
SCREAMING_SNAKE_CASE_ = torch.cat([half_eps, half_eps] , dim=0)
SCREAMING_SNAKE_CASE_ = torch.cat([eps, rest] , dim=1)
# learned sigma
if self.transformer.config.out_channels // 2 == latent_channels:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch.split(_A , _A , dim=1)
else:
SCREAMING_SNAKE_CASE_ = noise_pred
# compute previous image: x_t -> x_t-1
SCREAMING_SNAKE_CASE_ = self.scheduler.step(_A , _A , _A).prev_sample
if guidance_scale > 1:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = latent_model_input.chunk(2 , dim=0)
else:
SCREAMING_SNAKE_CASE_ = latent_model_input
SCREAMING_SNAKE_CASE_ = 1 / self.vae.config.scaling_factor * latents
SCREAMING_SNAKE_CASE_ = self.vae.decode(_A).sample
SCREAMING_SNAKE_CASE_ = (samples / 2 + 0.5).clamp(0 , 1)
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
SCREAMING_SNAKE_CASE_ = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy()
if output_type == "pil":
SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_A)
if not return_dict:
return (samples,)
return ImagePipelineOutput(images=_A)
| 620 | 1 |
import numpy as np
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : np.array ):
"""simple docstring"""
return (2 / (1 + np.exp(-2 * vector ))) - 1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
import pickle
import numpy as np
from matplotlib import pyplot as plt
class __snake_case :
def __init__( self , _A , _A , _A , _A , _A , _A=0.2 , _A=0.2):
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = bp_numa
SCREAMING_SNAKE_CASE_ = conva_get[:2]
SCREAMING_SNAKE_CASE_ = conva_get[2]
SCREAMING_SNAKE_CASE_ = size_pa
SCREAMING_SNAKE_CASE_ = rate_w
SCREAMING_SNAKE_CASE_ = rate_t
SCREAMING_SNAKE_CASE_ = [
np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0]) + 0.5)
for i in range(self.conva[1])
]
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa) + 0.5)
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.conva[1]) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
SCREAMING_SNAKE_CASE_ = -2 * np.random.rand(self.num_bpa) + 1
def lowerCAmelCase__ ( self , _A):
# save model dict with pickle
SCREAMING_SNAKE_CASE_ = {
'num_bp1': self.num_bpa,
'num_bp2': self.num_bpa,
'num_bp3': self.num_bpa,
'conv1': self.conva,
'step_conv1': self.step_conva,
'size_pooling1': self.size_poolinga,
'rate_weight': self.rate_weight,
'rate_thre': self.rate_thre,
'w_conv1': self.w_conva,
'wkj': self.wkj,
'vji': self.vji,
'thre_conv1': self.thre_conva,
'thre_bp2': self.thre_bpa,
'thre_bp3': self.thre_bpa,
}
with open(_A , 'wb') as f:
pickle.dump(_A , _A)
print(f"""Model saved: {save_path}""")
@classmethod
def lowerCAmelCase__ ( cls , _A):
# read saved model
with open(_A , 'rb') as f:
SCREAMING_SNAKE_CASE_ = pickle.load(_A) # noqa: S301
SCREAMING_SNAKE_CASE_ = model_dic.get('conv1')
conv_get.append(model_dic.get('step_conv1'))
SCREAMING_SNAKE_CASE_ = model_dic.get('size_pooling1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp1')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('num_bp3')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_weight')
SCREAMING_SNAKE_CASE_ = model_dic.get('rate_thre')
# create model instance
SCREAMING_SNAKE_CASE_ = CNN(_A , _A , _A , _A , _A , _A , _A)
# modify model parameter
SCREAMING_SNAKE_CASE_ = model_dic.get('w_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('wkj')
SCREAMING_SNAKE_CASE_ = model_dic.get('vji')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_conv1')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp2')
SCREAMING_SNAKE_CASE_ = model_dic.get('thre_bp3')
return conv_ins
def lowerCAmelCase__ ( self , _A):
return 1 / (1 + np.exp(-1 * x))
def lowerCAmelCase__ ( self , _A):
return round(_A , 3)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
# convolution process
SCREAMING_SNAKE_CASE_ = convs[0]
SCREAMING_SNAKE_CASE_ = convs[1]
SCREAMING_SNAKE_CASE_ = np.shape(_A)[0]
# get the data slice of original image data, data_focus
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , size_data - size_conv + 1 , _A):
for j_focus in range(0 , size_data - size_conv + 1 , _A):
SCREAMING_SNAKE_CASE_ = data[
i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
]
data_focus.append(_A)
# calculate the feature map of every single kernel, and saved as list of matrix
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = int((size_data - size_conv) / conv_step + 1)
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(len(_A)):
SCREAMING_SNAKE_CASE_ = (
np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map]))
- thre_convs[i_map]
)
featuremap.append(self.sig(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(
_A , _A)
data_featuremap.append(_A)
# expanding the data slice to One dimenssion
SCREAMING_SNAKE_CASE_ = []
for each_focus in data_focus:
focusa_list.extend(self.Expand_Mat(_A))
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return focus_list, data_featuremap
def lowerCAmelCase__ ( self , _A , _A , _A="average_pool"):
# pooling process
SCREAMING_SNAKE_CASE_ = len(featuremaps[0])
SCREAMING_SNAKE_CASE_ = int(size_map / size_pooling)
SCREAMING_SNAKE_CASE_ = []
for i_map in range(len(_A)):
SCREAMING_SNAKE_CASE_ = featuremaps[i_map]
SCREAMING_SNAKE_CASE_ = []
for i_focus in range(0 , _A , _A):
for j_focus in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = feature_map[
i_focus : i_focus + size_pooling,
j_focus : j_focus + size_pooling,
]
if pooling_type == "average_pool":
# average pooling
map_pooled.append(np.average(_A))
elif pooling_type == "max_pooling":
# max pooling
map_pooled.append(np.max(_A))
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A).reshape(_A , _A)
featuremap_pooled.append(_A)
return featuremap_pooled
def lowerCAmelCase__ ( self , _A):
# expanding three dimension data to one dimension list
SCREAMING_SNAKE_CASE_ = []
for i in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.shape(data[i])
SCREAMING_SNAKE_CASE_ = data[i].reshape(1 , shapes[0] * shapes[1])
SCREAMING_SNAKE_CASE_ = data_listed.getA().tolist()[0]
data_expanded.extend(_A)
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
return data_expanded
def lowerCAmelCase__ ( self , _A):
# expanding matrix to one dimension list
SCREAMING_SNAKE_CASE_ = np.asarray(_A)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = data_mat.reshape(1 , shapes[0] * shapes[1])
return data_expanded
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 0
for i_map in range(_A):
SCREAMING_SNAKE_CASE_ = np.ones((size_map, size_map))
for i in range(0 , _A , _A):
for j in range(0 , _A , _A):
SCREAMING_SNAKE_CASE_ = pd_pool[
i_pool
]
SCREAMING_SNAKE_CASE_ = i_pool + 1
SCREAMING_SNAKE_CASE_ = np.multiply(
_A , np.multiply(out_map[i_map] , (1 - out_map[i_map])))
pd_all.append(_A)
return pd_all
def lowerCAmelCase__ ( self , _A , _A , _A , _A , _A , _A=bool):
# model traning
print('----------------------Start Training-------------------------')
print((' - - Shape: Train_Data ', np.shape(_A)))
print((' - - Shape: Teach_Data ', np.shape(_A)))
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = 10000
while rp < n_repeat and mse >= error_accuracy:
SCREAMING_SNAKE_CASE_ = 0
print(f"""-------------Learning Time {rp}--------------""")
for p in range(len(_A)):
# print('------------Learning Image: %d--------------'%p)
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_train[p])
SCREAMING_SNAKE_CASE_ = np.asarray(datas_teach[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = np.shape(_A)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.wkj.T) - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
# --------------Model Leaning ------------------------
# calculate error and gradient---------------
SCREAMING_SNAKE_CASE_ = np.multiply(
(data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.multiply(
np.dot(_A , self.wkj) , np.multiply(_A , (1 - bp_outa)))
SCREAMING_SNAKE_CASE_ = np.dot(_A , self.vji)
SCREAMING_SNAKE_CASE_ = pd_i_all / (self.size_poolinga * self.size_poolinga)
SCREAMING_SNAKE_CASE_ = pd_conva_pooled.T.getA().tolist()
SCREAMING_SNAKE_CASE_ = self._calculate_gradient_from_pool(
_A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , )
# weight and threshold learning process---------
# convolution layer
for k_conv in range(self.conva[1]):
SCREAMING_SNAKE_CASE_ = self._expand_mat(pd_conva_all[k_conv])
SCREAMING_SNAKE_CASE_ = self.rate_weight * np.dot(_A , _A)
SCREAMING_SNAKE_CASE_ = self.w_conva[k_conv] + delta_w.reshape(
(self.conva[0], self.conva[0]))
SCREAMING_SNAKE_CASE_ = (
self.thre_conva[k_conv]
- np.sum(pd_conva_all[k_conv]) * self.rate_thre
)
# all connected layer
SCREAMING_SNAKE_CASE_ = self.wkj + pd_k_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.vji + pd_j_all.T * bp_outa * self.rate_weight
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_k_all * self.rate_thre
SCREAMING_SNAKE_CASE_ = self.thre_bpa - pd_j_all * self.rate_thre
# calculate the sum error of all single image
SCREAMING_SNAKE_CASE_ = np.sum(abs(data_teach - bp_outa))
error_count += errors
# print(' ----Teach ',data_teach)
# print(' ----BP_output ',bp_out3)
SCREAMING_SNAKE_CASE_ = rp + 1
SCREAMING_SNAKE_CASE_ = error_count / patterns
all_mse.append(_A)
def draw_error():
SCREAMING_SNAKE_CASE_ = [error_accuracy for i in range(int(n_repeat * 1.2))]
plt.plot(_A , '+-')
plt.plot(_A , 'r--')
plt.xlabel('Learning Times')
plt.ylabel('All_mse')
plt.grid(_A , alpha=0.5)
plt.show()
print('------------------Training Complished---------------------')
print((' - - Training epoch: ', rp, f""" - - Mse: {mse:.6f}"""))
if draw_e:
draw_error()
return mse
def lowerCAmelCase__ ( self , _A):
# model predict
SCREAMING_SNAKE_CASE_ = []
print('-------------------Start Testing-------------------------')
print((' - - Shape: Test_Data ', np.shape(_A)))
for p in range(len(_A)):
SCREAMING_SNAKE_CASE_ = np.asmatrix(datas_test[p])
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
SCREAMING_SNAKE_CASE_ = self._expand(_A)
SCREAMING_SNAKE_CASE_ = data_bp_input
SCREAMING_SNAKE_CASE_ = bp_outa * self.vji.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
SCREAMING_SNAKE_CASE_ = bp_outa * self.wkj.T - self.thre_bpa
SCREAMING_SNAKE_CASE_ = self.sig(_A)
produce_out.extend(bp_outa.getA().tolist())
SCREAMING_SNAKE_CASE_ = [list(map(self.do_round , _A)) for each in produce_out]
return np.asarray(_A)
def lowerCAmelCase__ ( self , _A):
# return the data of image after convoluting process so we can check it out
SCREAMING_SNAKE_CASE_ = np.asmatrix(_A)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.convolute(
_A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , )
SCREAMING_SNAKE_CASE_ = self.pooling(_A , self.size_poolinga)
return data_conveda, data_pooleda
if __name__ == "__main__":
pass
| 620 | 1 |
import json
import os
import shutil
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError
from transformers import AutoConfig, BertConfig, GPTaConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test
sys.path.append(str(Path(__file__).parent.parent / "utils"))
from test_module.custom_configuration import CustomConfig # noqa E402
UpperCamelCase__ : int = {
"return_dict": False,
"output_hidden_states": True,
"output_attentions": True,
"torchscript": True,
"torch_dtype": "float16",
"use_bfloat16": True,
"tf_legacy_loss": True,
"pruned_heads": {"a": 1},
"tie_word_embeddings": False,
"is_decoder": True,
"cross_attention_hidden_size": 128,
"add_cross_attention": True,
"tie_encoder_decoder": True,
"max_length": 50,
"min_length": 3,
"do_sample": True,
"early_stopping": True,
"num_beams": 3,
"num_beam_groups": 3,
"diversity_penalty": 0.5,
"temperature": 2.0,
"top_k": 10,
"top_p": 0.7,
"typical_p": 0.2,
"repetition_penalty": 0.8,
"length_penalty": 0.8,
"no_repeat_ngram_size": 5,
"encoder_no_repeat_ngram_size": 5,
"bad_words_ids": [1, 2, 3],
"num_return_sequences": 3,
"chunk_size_feed_forward": 5,
"output_scores": True,
"return_dict_in_generate": True,
"forced_bos_token_id": 2,
"forced_eos_token_id": 3,
"remove_invalid_values": True,
"architectures": ["BertModel"],
"finetuning_task": "translation",
"id2label": {0: "label"},
"label2id": {"label": "0"},
"tokenizer_class": "BertTokenizerFast",
"prefix": "prefix",
"bos_token_id": 6,
"pad_token_id": 7,
"eos_token_id": 8,
"sep_token_id": 9,
"decoder_start_token_id": 10,
"exponential_decay_length_penalty": (5, 1.01),
"suppress_tokens": [0, 1],
"begin_suppress_tokens": 2,
"task_specific_params": {"translation": "some_params"},
"problem_type": "regression",
}
@is_staging_test
class __snake_case ( unittest.TestCase ):
@classmethod
def lowerCAmelCase__ ( cls):
SCREAMING_SNAKE_CASE_ = TOKEN
HfFolder.save_token(_A)
@classmethod
def lowerCAmelCase__ ( cls):
try:
delete_repo(token=cls._token , repo_id='test-config')
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='valid_org/test-config-org')
except HTTPError:
pass
try:
delete_repo(token=cls._token , repo_id='test-dynamic-config')
except HTTPError:
pass
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37)
config.push_to_hub('test-config' , use_auth_token=self._token)
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained(f"""{USER}/test-config""")
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_A , getattr(_A , _A))
# Reset repo
delete_repo(token=self._token , repo_id='test-config')
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(_A , repo_id='test-config' , push_to_hub=_A , use_auth_token=self._token)
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained(f"""{USER}/test-config""")
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_A , getattr(_A , _A))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BertConfig(
vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37)
config.push_to_hub('valid_org/test-config-org' , use_auth_token=self._token)
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained('valid_org/test-config-org')
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_A , getattr(_A , _A))
# Reset repo
delete_repo(token=self._token , repo_id='valid_org/test-config-org')
# Push to hub via save_pretrained
with tempfile.TemporaryDirectory() as tmp_dir:
config.save_pretrained(
_A , repo_id='valid_org/test-config-org' , push_to_hub=_A , use_auth_token=self._token)
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained('valid_org/test-config-org')
for k, v in config.to_dict().items():
if k != "transformers_version":
self.assertEqual(_A , getattr(_A , _A))
def lowerCAmelCase__ ( self):
CustomConfig.register_for_auto_class()
SCREAMING_SNAKE_CASE_ = CustomConfig(attribute=42)
config.push_to_hub('test-dynamic-config' , use_auth_token=self._token)
# This has added the proper auto_map field to the config
self.assertDictEqual(config.auto_map , {'AutoConfig': 'custom_configuration.CustomConfig'})
SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(f"""{USER}/test-dynamic-config""" , trust_remote_code=_A)
# Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module
self.assertEqual(new_config.__class__.__name__ , 'CustomConfig')
self.assertEqual(new_config.attribute , 42)
class __snake_case ( unittest.TestCase ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = GPTaConfig()
# attempt to modify each of int/float/bool/str config records and verify they were updated
SCREAMING_SNAKE_CASE_ = c.n_embd + 1 # int
SCREAMING_SNAKE_CASE_ = c.resid_pdrop + 1.0 # float
SCREAMING_SNAKE_CASE_ = not c.scale_attn_weights # bool
SCREAMING_SNAKE_CASE_ = c.summary_type + 'foo' # str
c.update_from_string(
f"""n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}""")
self.assertEqual(_A , c.n_embd , 'mismatch for key: n_embd')
self.assertEqual(_A , c.resid_pdrop , 'mismatch for key: resid_pdrop')
self.assertEqual(_A , c.scale_attn_weights , 'mismatch for key: scale_attn_weights')
self.assertEqual(_A , c.summary_type , 'mismatch for key: summary_type')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = PretrainedConfig()
SCREAMING_SNAKE_CASE_ = [key for key in base_config.__dict__ if key not in config_common_kwargs]
# If this part of the test fails, you have arguments to addin config_common_kwargs above.
self.assertListEqual(
_A , ['is_encoder_decoder', '_name_or_path', '_commit_hash', 'transformers_version'])
SCREAMING_SNAKE_CASE_ = [key for key, value in config_common_kwargs.items() if value == getattr(_A , _A)]
if len(_A) > 0:
raise ValueError(
'The following keys are set with the default values in'
' `test_configuration_common.config_common_kwargs` pick another value for them:'
f""" {', '.join(_A)}.""")
def lowerCAmelCase__ ( self):
with self.assertRaises(_A):
# config is in subfolder, the following should not work without specifying the subfolder
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder')
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' , subfolder='bert')
self.assertIsNotNone(_A)
def lowerCAmelCase__ ( self):
# A mock response for an HTTP head request to emulate server down
SCREAMING_SNAKE_CASE_ = mock.Mock()
SCREAMING_SNAKE_CASE_ = 500
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = HTTPError
SCREAMING_SNAKE_CASE_ = {}
# Download this model to make sure it's in the cache.
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert')
# Under the mock environment we get a 500 error when trying to reach the model.
with mock.patch('requests.Session.request' , return_value=_A) as mock_head:
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert')
# This check we did call the fake head request
mock_head.assert_called()
def lowerCAmelCase__ ( self):
# This test is for deprecated behavior and can be removed in v5
SCREAMING_SNAKE_CASE_ = BertConfig.from_pretrained(
'https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained('bert-base-cased')
SCREAMING_SNAKE_CASE_ = ['config.4.0.0.json']
with tempfile.TemporaryDirectory() as tmp_dir:
configuration.save_pretrained(_A)
SCREAMING_SNAKE_CASE_ = 2
json.dump(configuration.to_dict() , open(os.path.join(_A , 'config.4.0.0.json') , 'w'))
# This should pick the new configuration file as the version of Transformers is > 4.0.0
SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(_A)
self.assertEqual(new_configuration.hidden_size , 2)
# Will need to be adjusted if we reach v42 and this test is still here.
# Should pick the old configuration file as the version of Transformers is < 4.42.0
SCREAMING_SNAKE_CASE_ = ['config.42.0.0.json']
SCREAMING_SNAKE_CASE_ = 768
configuration.save_pretrained(_A)
shutil.move(os.path.join(_A , 'config.4.0.0.json') , os.path.join(_A , 'config.42.0.0.json'))
SCREAMING_SNAKE_CASE_ = AutoConfig.from_pretrained(_A)
self.assertEqual(new_configuration.hidden_size , 768)
def lowerCAmelCase__ ( self):
# This repo has two configuration files, one for v4.0.0 and above with a different hidden size.
SCREAMING_SNAKE_CASE_ = 'hf-internal-testing/test-two-configs'
import transformers as new_transformers
SCREAMING_SNAKE_CASE_ = 'v4.0.0'
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = new_transformers.models.auto.AutoConfig.from_pretrained(
_A , return_unused_kwargs=_A)
self.assertEqual(new_configuration.hidden_size , 2)
# This checks `_configuration_file` ia not kept in the kwargs by mistake.
self.assertDictEqual(_A , {})
# Testing an older version by monkey-patching the version in the module it's used.
import transformers as old_transformers
SCREAMING_SNAKE_CASE_ = 'v3.0.0'
SCREAMING_SNAKE_CASE_ = old_transformers.models.auto.AutoConfig.from_pretrained(_A)
self.assertEqual(old_configuration.hidden_size , 768)
| 620 |
import os
import zipfile
import requests
from get_ci_error_statistics import download_artifact, get_artifacts_links
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : int=7 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = None
if token is not None:
SCREAMING_SNAKE_CASE_ = {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}
# The id of a workflow (not of a workflow run)
SCREAMING_SNAKE_CASE_ = '636036'
SCREAMING_SNAKE_CASE_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs"""
# On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results
url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}"""
SCREAMING_SNAKE_CASE_ = requests.get(_SCREAMING_SNAKE_CASE , headers=_SCREAMING_SNAKE_CASE ).json()
return result["workflow_runs"]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_daily_ci_runs(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = None
for workflow_run in workflow_runs:
if workflow_run["status"] == "completed":
SCREAMING_SNAKE_CASE_ = workflow_run['id']
break
return workflow_run_id
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_last_daily_ci_runs(_SCREAMING_SNAKE_CASE )
if workflow_run_id is not None:
SCREAMING_SNAKE_CASE_ = get_artifacts_links(worflow_run_id=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
for artifact_name in artifact_names:
if artifact_name in artifacts_links:
SCREAMING_SNAKE_CASE_ = artifacts_links[artifact_name]
download_artifact(
artifact_name=_SCREAMING_SNAKE_CASE , artifact_url=_SCREAMING_SNAKE_CASE , output_dir=_SCREAMING_SNAKE_CASE , token=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : List[Any] ):
"""simple docstring"""
get_last_daily_ci_artifacts(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
for artifact_name in artifact_names:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{artifact_name}.zip""" )
if os.path.isfile(_SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE_ = {}
with zipfile.ZipFile(_SCREAMING_SNAKE_CASE ) as z:
for filename in z.namelist():
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
# read the file
with z.open(_SCREAMING_SNAKE_CASE ) as f:
SCREAMING_SNAKE_CASE_ = f.read().decode('UTF-8' )
return results
| 620 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Optional[int] = {
"facebook/dpr-ctx_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-single-nq-base": (
"https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-reader-single-nq-base": (
"https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
),
"facebook/dpr-ctx_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-question_encoder-multiset-base": (
"https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
),
"facebook/dpr-reader-multiset-base": (
"https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
),
}
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : Optional[int] = 'dpr'
def __init__( self , _A=30522 , _A=768 , _A=12 , _A=12 , _A=3072 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=2 , _A=0.0_2 , _A=1E-12 , _A=0 , _A="absolute" , _A = 0 , **_A , ):
super().__init__(pad_token_id=_A , **_A)
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = hidden_size
SCREAMING_SNAKE_CASE_ = num_hidden_layers
SCREAMING_SNAKE_CASE_ = num_attention_heads
SCREAMING_SNAKE_CASE_ = hidden_act
SCREAMING_SNAKE_CASE_ = intermediate_size
SCREAMING_SNAKE_CASE_ = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = type_vocab_size
SCREAMING_SNAKE_CASE_ = initializer_range
SCREAMING_SNAKE_CASE_ = layer_norm_eps
SCREAMING_SNAKE_CASE_ = projection_dim
SCREAMING_SNAKE_CASE_ = position_embedding_type
| 620 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
UpperCamelCase__ : Any = {
"configuration_mvp": ["MVP_PRETRAINED_CONFIG_ARCHIVE_MAP", "MvpConfig", "MvpOnnxConfig"],
"tokenization_mvp": ["MvpTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Optional[int] = ["MvpTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
"MVP_PRETRAINED_MODEL_ARCHIVE_LIST",
"MvpForCausalLM",
"MvpForConditionalGeneration",
"MvpForQuestionAnswering",
"MvpForSequenceClassification",
"MvpModel",
"MvpPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
from .tokenization_mvp import MvpTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mvp_fast import MvpTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mvp import (
MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
MvpForCausalLM,
MvpForConditionalGeneration,
MvpForQuestionAnswering,
MvpForSequenceClassification,
MvpModel,
MvpPreTrainedModel,
)
else:
import sys
UpperCamelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
from __future__ import annotations
from collections.abc import Iterator
class __snake_case :
def __init__( self , _A):
SCREAMING_SNAKE_CASE_ = value
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = None
class __snake_case :
def __init__( self , _A):
SCREAMING_SNAKE_CASE_ = tree
def lowerCAmelCase__ ( self , _A):
if node is None:
return 0
return node.value + (
self.depth_first_search(node.left) + self.depth_first_search(node.right)
)
def __iter__( self):
yield self.depth_first_search(self.tree)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 |
import inspect
import os
import unittest
from pathlib import Path
import torch
import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Dict = inspect.getfile(accelerate.test_utils )
__lowerCAmelCase : Optional[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )
__lowerCAmelCase : Tuple = ['accelerate', 'launch']
__lowerCAmelCase : Union[str, Any] = Path.home() / '.cache/huggingface/accelerate'
__lowerCAmelCase : List[str] = 'default_config.yaml'
__lowerCAmelCase : List[Any] = config_folder / config_file
__lowerCAmelCase : str = config_folder / '_default_config.yaml'
__lowerCAmelCase : Optional[int] = Path('tests/test_configs' )
@classmethod
def lowerCAmelCase__ ( cls):
if cls.config_path.is_file():
cls.config_path.rename(cls.changed_path)
@classmethod
def lowerCAmelCase__ ( cls):
if cls.changed_path.is_file():
cls.changed_path.rename(cls.config_path)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.base_cmd
if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
cmd += ["--multi_gpu"]
execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
for config in sorted(self.test_config_path.glob('**/*.yaml')):
with self.subTest(config_file=_A):
execute_subprocess_async(
self.base_cmd + ['--config_file', str(_A), self.test_file_path] , env=os.environ.copy())
def lowerCAmelCase__ ( self):
execute_subprocess_async(['accelerate', 'test'] , env=os.environ.copy())
class __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[Any] = 'test-tpu'
__lowerCAmelCase : str = 'us-central1-a'
__lowerCAmelCase : Union[str, Any] = 'ls'
__lowerCAmelCase : Union[str, Any] = ['accelerate', 'tpu-config']
__lowerCAmelCase : Union[str, Any] = 'cd /usr/share'
__lowerCAmelCase : List[Any] = 'tests/test_samples/test_command_file.sh'
__lowerCAmelCase : Dict = 'Running gcloud compute tpus tpu-vm ssh'
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command',
self.command,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] , return_stdout=_A)
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--command',
self.command,
'--command',
'echo "Hello World"',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/0_12_0.yaml',
'--command_file',
self.command_file,
'--tpu_zone',
self.tpu_zone,
'--tpu_name',
self.tpu_name,
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = run_command(
self.cmd
+ [
'--config_file',
'tests/test_configs/latest.yaml',
'--install_accelerate',
'--accelerate_version',
'12.0.0',
'--debug',
] , return_stdout=_A , )
self.assertIn(
f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , _A , )
| 620 | 1 |
import argparse
import os
from pathlib import Path
from typing import Dict
import tensorflow as tf
import torch
from tqdm import tqdm
from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer
from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params
UpperCamelCase__ : str = [
# replace left string with right string to get the relevant state_dict key (identical state dict to bart)
["memory_attention", "encoder_attn"],
["attention", "attn"],
["/", "."],
[".LayerNorm.gamma", "_layer_norm.weight"],
[".LayerNorm.beta", "_layer_norm.bias"],
["r.layer_", "r.layers."],
["output_proj", "out_proj"],
["ffn.dense_1.", "fc2."],
["ffn.dense.", "fc1."],
["ffn_layer_norm", "final_layer_norm"],
["kernel", "weight"],
["encoder_layer_norm.", "encoder.layer_norm."],
["decoder_layer_norm.", "decoder.layer_norm."],
["embeddings.weights", "shared.weight"],
]
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
for pegasus_name, hf_name in PATTERNS:
SCREAMING_SNAKE_CASE_ = k.replace(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
return k
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : dict , _SCREAMING_SNAKE_CASE : dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = DEFAULTS.copy()
cfg_kwargs.update(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = PegasusConfig(**_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = PegasusForConditionalGeneration(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = torch_model.model.state_dict()
SCREAMING_SNAKE_CASE_ = {}
for k, v in tf_weights.items():
SCREAMING_SNAKE_CASE_ = rename_state_dict_key(_SCREAMING_SNAKE_CASE )
if new_k not in sd:
raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" )
if "dense" in k or "proj" in new_k:
SCREAMING_SNAKE_CASE_ = v.T
SCREAMING_SNAKE_CASE_ = torch.tensor(_SCREAMING_SNAKE_CASE , dtype=sd[new_k].dtype )
assert v.shape == sd[new_k].shape, f"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}"""
# make sure embedding.padding_idx is respected
SCREAMING_SNAKE_CASE_ = torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1] )
SCREAMING_SNAKE_CASE_ = mapping['shared.weight']
SCREAMING_SNAKE_CASE_ = mapping['shared.weight']
SCREAMING_SNAKE_CASE_ = {k: torch.zeros_like(_SCREAMING_SNAKE_CASE ) for k, v in sd.items() if k.endswith('bias' ) and k not in mapping}
mapping.update(**_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch_model.model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = [
k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.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 _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple="./ckpt/aeslc/model.ckpt-32000" ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = tf.train.list_variables(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = {}
SCREAMING_SNAKE_CASE_ = ['Adafactor', 'global_step']
for name, shape in tqdm(_SCREAMING_SNAKE_CASE , desc='converting tf checkpoint to dict' ):
SCREAMING_SNAKE_CASE_ = any(pat in name for pat in ignore_name )
if skip_key:
continue
SCREAMING_SNAKE_CASE_ = tf.train.load_variable(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = array
return tf_weights
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = Path(_SCREAMING_SNAKE_CASE ).parent.name
SCREAMING_SNAKE_CASE_ = task_specific_params[f"""summarization_{dataset}"""]['max_position_embeddings']
SCREAMING_SNAKE_CASE_ = PegasusTokenizer.from_pretrained('sshleifer/pegasus' , model_max_length=_SCREAMING_SNAKE_CASE )
assert tok.model_max_length == desired_max_model_length
tok.save_pretrained(_SCREAMING_SNAKE_CASE )
# convert model
SCREAMING_SNAKE_CASE_ = get_tf_weights_as_numpy(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = task_specific_params[f"""summarization_{dataset}"""]
if dataset == "large":
SCREAMING_SNAKE_CASE_ = task_specific_params
SCREAMING_SNAKE_CASE_ = convert_pegasus(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
torch_model.save_pretrained(_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = torch_model.state_dict()
sd.pop('model.decoder.embed_positions.weight' )
sd.pop('model.encoder.embed_positions.weight' )
torch.save(_SCREAMING_SNAKE_CASE , Path(_SCREAMING_SNAKE_CASE ) / 'pytorch_model.bin' )
if __name__ == "__main__":
UpperCamelCase__ : Any = argparse.ArgumentParser()
# Required parameters
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.")
UpperCamelCase__ : Union[str, Any] = parser.parse_args()
if args.save_dir is None:
UpperCamelCase__ : Optional[Any] = Path(args.tf_ckpt_path).parent.name
UpperCamelCase__ : Any = os.path.join("pegasus", dataset)
convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
| 620 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCamelCase__ : Tuple = {
"configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"],
"processing_trocr": ["TrOCRProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : Tuple = [
"TROCR_PRETRAINED_MODEL_ARCHIVE_LIST",
"TrOCRForCausalLM",
"TrOCRPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCamelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 620 | 1 |
import os
import torch
from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version
if is_torch_version(">=", FSDP_PYTORCH_VERSION):
import torch.distributed.checkpoint as dist_cp
from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
UpperCamelCase__ : int = get_logger(__name__)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : List[str]=0 ):
"""simple docstring"""
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
with FSDP.state_dict_type(
_SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
SCREAMING_SNAKE_CASE_ = model.state_dict()
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
SCREAMING_SNAKE_CASE_ = f"""{MODEL_NAME}.bin""" if model_index == 0 else f"""{MODEL_NAME}_{model_index}.bin"""
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if accelerator.process_index == 0:
logger.info(f"""Saving model to {output_model_file}""" )
torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Model saved to {output_model_file}""" )
elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
SCREAMING_SNAKE_CASE_ = (
f"""{MODEL_NAME}_rank{accelerator.process_index}.bin"""
if model_index == 0
else f"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"""
)
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Saving model to {output_model_file}""" )
torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Model saved to {output_model_file}""" )
elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{MODEL_NAME}_{model_index}""" )
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
logger.info(f"""Saving model to {ckpt_dir}""" )
SCREAMING_SNAKE_CASE_ = {'model': state_dict}
dist_cp.save_state_dict(
state_dict=_SCREAMING_SNAKE_CASE , storage_writer=dist_cp.FileSystemWriter(_SCREAMING_SNAKE_CASE ) , planner=DefaultSavePlanner() , )
logger.info(f"""Model saved to {ckpt_dir}""" )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[int]=0 ):
"""simple docstring"""
accelerator.wait_for_everyone()
with FSDP.state_dict_type(
_SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
if type(_SCREAMING_SNAKE_CASE ) != FSDP and accelerator.process_index != 0:
if not fsdp_plugin.sync_module_states:
raise ValueError(
'Set the `sync_module_states` flag to `True` so that model states are synced across processes when '
'initializing FSDP object' )
return
SCREAMING_SNAKE_CASE_ = f"""{MODEL_NAME}.bin""" if model_index == 0 else f"""{MODEL_NAME}_{model_index}.bin"""
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Loading model from {input_model_file}""" )
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE )
logger.info(f"""Model loaded from {input_model_file}""" )
elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
SCREAMING_SNAKE_CASE_ = (
f"""{MODEL_NAME}_rank{accelerator.process_index}.bin"""
if model_index == 0
else f"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"""
)
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Loading model from {input_model_file}""" )
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE )
logger.info(f"""Model loaded from {input_model_file}""" )
elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
SCREAMING_SNAKE_CASE_ = (
os.path.join(_SCREAMING_SNAKE_CASE , f"""{MODEL_NAME}_{model_index}""" )
if f"""{MODEL_NAME}""" not in input_dir
else input_dir
)
logger.info(f"""Loading model from {ckpt_dir}""" )
SCREAMING_SNAKE_CASE_ = {'model': model.state_dict()}
dist_cp.load_state_dict(
state_dict=_SCREAMING_SNAKE_CASE , storage_reader=dist_cp.FileSystemReader(_SCREAMING_SNAKE_CASE ) , planner=DefaultLoadPlanner() , )
SCREAMING_SNAKE_CASE_ = state_dict['model']
logger.info(f"""Model loaded from {ckpt_dir}""" )
model.load_state_dict(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[str]=0 ):
"""simple docstring"""
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
with FSDP.state_dict_type(
_SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
SCREAMING_SNAKE_CASE_ = FSDP.optim_state_dict(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
if accelerator.process_index == 0:
SCREAMING_SNAKE_CASE_ = (
f"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else f"""{OPTIMIZER_NAME}_{optimizer_index}.bin"""
)
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Saving Optimizer state to {output_optimizer_file}""" )
torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Optimizer state saved in {output_optimizer_file}""" )
else:
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , f"""{OPTIMIZER_NAME}_{optimizer_index}""" )
os.makedirs(_SCREAMING_SNAKE_CASE , exist_ok=_SCREAMING_SNAKE_CASE )
logger.info(f"""Saving Optimizer state to {ckpt_dir}""" )
dist_cp.save_state_dict(
state_dict={'optimizer': optim_state} , storage_writer=dist_cp.FileSystemWriter(_SCREAMING_SNAKE_CASE ) , planner=DefaultSavePlanner() , )
logger.info(f"""Optimizer state saved in {ckpt_dir}""" )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Tuple , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : List[str] , _SCREAMING_SNAKE_CASE : Optional[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any]=0 ):
"""simple docstring"""
accelerator.wait_for_everyone()
with FSDP.state_dict_type(
_SCREAMING_SNAKE_CASE , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
SCREAMING_SNAKE_CASE_ = None
# below check should work but currently it isn't working (mostly opytorch issue),
# in the meantime disabling it at the cost of excess memory usage
# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
SCREAMING_SNAKE_CASE_ = (
f"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else f"""{OPTIMIZER_NAME}_{optimizer_index}.bin"""
)
SCREAMING_SNAKE_CASE_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
logger.info(f"""Loading Optimizer state from {input_optimizer_file}""" )
SCREAMING_SNAKE_CASE_ = torch.load(_SCREAMING_SNAKE_CASE )
logger.info(f"""Optimizer state loaded from {input_optimizer_file}""" )
else:
SCREAMING_SNAKE_CASE_ = (
os.path.join(_SCREAMING_SNAKE_CASE , f"""{OPTIMIZER_NAME}_{optimizer_index}""" )
if f"""{OPTIMIZER_NAME}""" not in input_dir
else input_dir
)
logger.info(f"""Loading Optimizer from {ckpt_dir}""" )
SCREAMING_SNAKE_CASE_ = load_sharded_optimizer_state_dict(
model_state_dict=model.state_dict() , optimizer_key='optimizer' , storage_reader=dist_cp.FileSystemReader(_SCREAMING_SNAKE_CASE ) , )
SCREAMING_SNAKE_CASE_ = optim_state['optimizer']
logger.info(f"""Optimizer loaded from {ckpt_dir}""" )
SCREAMING_SNAKE_CASE_ = FSDP.optim_state_dict_to_load(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
optimizer.load_state_dict(_SCREAMING_SNAKE_CASE )
| 620 |
from multiprocessing import Lock, Pipe, Process
# lock used to ensure that two processes do not access a pipe at the same time
UpperCamelCase__ : int = Lock()
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Any ):
"""simple docstring"""
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0 , 10 ):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
SCREAMING_SNAKE_CASE_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(_SCREAMING_SNAKE_CASE )
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
SCREAMING_SNAKE_CASE_ = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
SCREAMING_SNAKE_CASE_ = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
# after all swaps are performed, send the values back to main
result_pipe[1].send(_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = []
SCREAMING_SNAKE_CASE_ = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe() )
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
for i in range(1 , len(_SCREAMING_SNAKE_CASE ) - 1 ):
SCREAMING_SNAKE_CASE_ = Pipe()
SCREAMING_SNAKE_CASE_ = Pipe()
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) )
SCREAMING_SNAKE_CASE_ = temp_rs
SCREAMING_SNAKE_CASE_ = temp_rr
process_array_.append(
Process(
target=_SCREAMING_SNAKE_CASE , args=(
len(_SCREAMING_SNAKE_CASE ) - 1,
arr[len(_SCREAMING_SNAKE_CASE ) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(_SCREAMING_SNAKE_CASE ) - 1],
) , ) )
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0 , len(_SCREAMING_SNAKE_CASE ) ):
SCREAMING_SNAKE_CASE_ = result_pipe[p][0].recv()
process_array_[p].join()
return arr
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = list(range(10 , 0 , -1 ) )
print('Initial List' )
print(*_SCREAMING_SNAKE_CASE )
SCREAMING_SNAKE_CASE_ = odd_even_transposition(_SCREAMING_SNAKE_CASE )
print('Sorted List\n' )
print(*_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 620 | 1 |
# flake8: noqa
# Lint as: python3
from typing import Dict, List, Optional, Type
from .. import config
from ..utils import logging
from .formatting import (
ArrowFormatter,
CustomFormatter,
Formatter,
PandasFormatter,
PythonFormatter,
TensorFormatter,
format_table,
query_table,
)
from .np_formatter import NumpyFormatter
UpperCamelCase__ : List[Any] = logging.get_logger(__name__)
UpperCamelCase__ : Dict[Optional[str], Type[Formatter]] = {}
UpperCamelCase__ : Dict[Optional[str], str] = {}
UpperCamelCase__ : Dict[Optional[str], Exception] = {}
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : type , _SCREAMING_SNAKE_CASE : Optional[str] , _SCREAMING_SNAKE_CASE : Optional[List[str]] = None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = aliases if aliases is not None else []
if format_type in _FORMAT_TYPES:
logger.warning(
f"""Overwriting format type '{format_type}' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})""" )
SCREAMING_SNAKE_CASE_ = formatter_cls
for alias in set(aliases + [format_type] ):
if alias in _FORMAT_TYPES_ALIASES:
logger.warning(
f"""Overwriting format type alias '{alias}' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})""" )
SCREAMING_SNAKE_CASE_ = format_type
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Exception , _SCREAMING_SNAKE_CASE : Optional[str] , _SCREAMING_SNAKE_CASE : Optional[List[str]] = None ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = aliases if aliases is not None else []
for alias in set(aliases + [format_type] ):
SCREAMING_SNAKE_CASE_ = unavailable_error
# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=["python"])
_register_formatter(ArrowFormatter, "arrow", aliases=["pa", "pyarrow"])
_register_formatter(NumpyFormatter, "numpy", aliases=["np"])
_register_formatter(PandasFormatter, "pandas", aliases=["pd"])
_register_formatter(CustomFormatter, "custom")
if config.TORCH_AVAILABLE:
from .torch_formatter import TorchFormatter
_register_formatter(TorchFormatter, "torch", aliases=["pt", "pytorch"])
else:
UpperCamelCase__ : str = ValueError("PyTorch needs to be installed to be able to return PyTorch tensors.")
_register_unavailable_formatter(_torch_error, "torch", aliases=["pt", "pytorch"])
if config.TF_AVAILABLE:
from .tf_formatter import TFFormatter
_register_formatter(TFFormatter, "tensorflow", aliases=["tf"])
else:
UpperCamelCase__ : Dict = ValueError("Tensorflow needs to be installed to be able to return Tensorflow tensors.")
_register_unavailable_formatter(_tf_error, "tensorflow", aliases=["tf"])
if config.JAX_AVAILABLE:
from .jax_formatter import JaxFormatter
_register_formatter(JaxFormatter, "jax", aliases=[])
else:
UpperCamelCase__ : Union[str, Any] = ValueError("JAX needs to be installed to be able to return JAX arrays.")
_register_unavailable_formatter(_jax_error, "jax", aliases=[])
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[str] ):
"""simple docstring"""
if format_type in _FORMAT_TYPES_ALIASES:
return _FORMAT_TYPES_ALIASES[format_type]
else:
return format_type
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : Optional[str] , **_SCREAMING_SNAKE_CASE : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = get_format_type_from_alias(_SCREAMING_SNAKE_CASE )
if format_type in _FORMAT_TYPES:
return _FORMAT_TYPES[format_type](**_SCREAMING_SNAKE_CASE )
if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
else:
raise ValueError(
f"""Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got '{format_type}'""" )
| 620 |
import unittest
from transformers import load_tool
from .test_tools_common import ToolTesterMixin
UpperCamelCase__ : int = "\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n"
class __snake_case ( unittest.TestCase , lowerCAmelCase__ ):
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering')
self.tool.setup()
SCREAMING_SNAKE_CASE_ = load_tool('text-question-answering' , remote=_A)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(_A , 'What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.remote_tool(text=_A , question='What did Hugging Face do in April 2021?')
self.assertEqual(_A , 'launched the BigScience Research Workshop')
| 620 | 1 |
from typing import List, Optional, TypeVar
from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal
UpperCamelCase__ : str = logging.get_logger(__name__)
UpperCamelCase__ : Tuple = TypeVar("DatasetType", Dataset, IterableDataset)
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[DatasetType] , _SCREAMING_SNAKE_CASE : Optional[List[float]] = None , _SCREAMING_SNAKE_CASE : Optional[int] = None , _SCREAMING_SNAKE_CASE : Optional[DatasetInfo] = None , _SCREAMING_SNAKE_CASE : Optional[NamedSplit] = None , _SCREAMING_SNAKE_CASE : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" , ):
"""simple docstring"""
from .arrow_dataset import Dataset
from .iterable_dataset import IterableDataset
if not datasets:
raise ValueError('Unable to interleave an empty list of datasets.' )
for i, dataset in enumerate(_SCREAMING_SNAKE_CASE ):
if not isinstance(_SCREAMING_SNAKE_CASE , (Dataset, IterableDataset) ):
if isinstance(_SCREAMING_SNAKE_CASE , (DatasetDict, IterableDatasetDict) ):
if not dataset:
raise ValueError(
f"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} """
'is an empty dataset dictionary.' )
raise ValueError(
f"""Dataset at position {i} has at least one split: {list(_SCREAMING_SNAKE_CASE )}\n"""
f"""Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_SCREAMING_SNAKE_CASE ) )}']""" )
raise ValueError(
f"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_SCREAMING_SNAKE_CASE ).__name__}.""" )
if i == 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = (
(Dataset, IterableDataset) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else (IterableDataset, Dataset)
)
elif not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise ValueError(
f"""Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.""" )
if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
raise ValueError(f"""{stopping_strategy} is not supported. Please enter a valid stopping_strategy.""" )
if dataset_type is Dataset:
return _interleave_map_style_datasets(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , info=_SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE , stopping_strategy=_SCREAMING_SNAKE_CASE )
else:
return _interleave_iterable_datasets(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , info=_SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE , stopping_strategy=_SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : List[DatasetType] , _SCREAMING_SNAKE_CASE : Optional[DatasetInfo] = None , _SCREAMING_SNAKE_CASE : Optional[NamedSplit] = None , _SCREAMING_SNAKE_CASE : int = 0 , ):
"""simple docstring"""
if not dsets:
raise ValueError('Unable to concatenate an empty list of datasets.' )
for i, dataset in enumerate(_SCREAMING_SNAKE_CASE ):
if not isinstance(_SCREAMING_SNAKE_CASE , (Dataset, IterableDataset) ):
if isinstance(_SCREAMING_SNAKE_CASE , (DatasetDict, IterableDatasetDict) ):
if not dataset:
raise ValueError(
f"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} """
'is an empty dataset dictionary.' )
raise ValueError(
f"""Dataset at position {i} has at least one split: {list(_SCREAMING_SNAKE_CASE )}\n"""
f"""Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_SCREAMING_SNAKE_CASE ) )}']""" )
raise ValueError(
f"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_SCREAMING_SNAKE_CASE ).__name__}.""" )
if i == 0:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = (
(Dataset, IterableDataset) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else (IterableDataset, Dataset)
)
elif not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise ValueError(
f"""Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.""" )
if dataset_type is Dataset:
return _concatenate_map_style_datasets(_SCREAMING_SNAKE_CASE , info=_SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE , axis=_SCREAMING_SNAKE_CASE )
else:
return _concatenate_iterable_datasets(_SCREAMING_SNAKE_CASE , info=_SCREAMING_SNAKE_CASE , split=_SCREAMING_SNAKE_CASE , axis=_SCREAMING_SNAKE_CASE )
| 620 |
import unittest
import numpy as np
from datasets import load_dataset
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import BeitImageProcessor
class __snake_case ( unittest.TestCase ):
def __init__( self , _A , _A=7 , _A=3 , _A=18 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=False , ):
SCREAMING_SNAKE_CASE_ = size if size is not None else {'height': 20, 'width': 20}
SCREAMING_SNAKE_CASE_ = crop_size if crop_size is not None else {'height': 18, 'width': 18}
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = num_channels
SCREAMING_SNAKE_CASE_ = image_size
SCREAMING_SNAKE_CASE_ = min_resolution
SCREAMING_SNAKE_CASE_ = max_resolution
SCREAMING_SNAKE_CASE_ = do_resize
SCREAMING_SNAKE_CASE_ = size
SCREAMING_SNAKE_CASE_ = do_center_crop
SCREAMING_SNAKE_CASE_ = crop_size
SCREAMING_SNAKE_CASE_ = do_normalize
SCREAMING_SNAKE_CASE_ = image_mean
SCREAMING_SNAKE_CASE_ = image_std
SCREAMING_SNAKE_CASE_ = do_reduce_labels
def lowerCAmelCase__ ( self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_reduce_labels": self.do_reduce_labels,
}
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(dataset[1]['file'] )
return image, map
def _UpperCAmelCase ( ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' )
SCREAMING_SNAKE_CASE_ = Image.open(ds[0]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[1]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[2]['file'] )
SCREAMING_SNAKE_CASE_ = Image.open(ds[3]['file'] )
return [imagea, imagea], [mapa, mapa]
@require_torch
@require_vision
class __snake_case ( lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Union[str, Any] = BeitImageProcessor if is_vision_available() else None
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = BeitImageProcessingTester(self)
@property
def lowerCAmelCase__ ( self):
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(_A , 'do_resize'))
self.assertTrue(hasattr(_A , 'size'))
self.assertTrue(hasattr(_A , 'do_center_crop'))
self.assertTrue(hasattr(_A , 'center_crop'))
self.assertTrue(hasattr(_A , 'do_normalize'))
self.assertTrue(hasattr(_A , 'image_mean'))
self.assertTrue(hasattr(_A , 'image_std'))
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'height': 20, 'width': 20})
self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18})
self.assertEqual(image_processor.do_reduce_labels , _A)
SCREAMING_SNAKE_CASE_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A)
self.assertEqual(image_processor.size , {'height': 42, 'width': 42})
self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84})
self.assertEqual(image_processor.do_reduce_labels , _A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A)
for image in image_inputs:
self.assertIsInstance(_A , Image.Image)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A)
for image in image_inputs:
self.assertIsInstance(_A , np.ndarray)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
# Test not batched input
SCREAMING_SNAKE_CASE_ = 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.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , return_tensors='pt').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
SCREAMING_SNAKE_CASE_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A)
SCREAMING_SNAKE_CASE_ = []
for image in image_inputs:
self.assertIsInstance(_A , torch.Tensor)
maps.append(torch.zeros(image.shape[-2:]).long())
# Test not batched input
SCREAMING_SNAKE_CASE_ = image_processing(image_inputs[0] , maps[0] , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test not batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
1,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
# Test batched input (PIL images)
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_batch_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertEqual(
encoding['pixel_values'].shape , (
2,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(
encoding['labels'].shape , (
2,
self.image_processor_tester.crop_size['height'],
self.image_processor_tester.crop_size['width'],
) , )
self.assertEqual(encoding['labels'].dtype , torch.long)
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
def lowerCAmelCase__ ( self):
# Initialize image_processing
SCREAMING_SNAKE_CASE_ = self.image_processing_class(**self.image_processor_dict)
# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prepare_semantic_single_inputs()
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 150)
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = image_processing(_A , _A , return_tensors='pt')
self.assertTrue(encoding['labels'].min().item() >= 0)
self.assertTrue(encoding['labels'].max().item() <= 255)
| 620 | 1 |
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 __snake_case ( unittest.TestCase ):
__lowerCAmelCase : Optional[int] = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
__lowerCAmelCase : List[Any] = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING
def lowerCAmelCase__ ( self , _A , _A , _A):
SCREAMING_SNAKE_CASE_ = AudioClassificationPipeline(model=_A , feature_extractor=_A)
# test with a raw waveform
SCREAMING_SNAKE_CASE_ = np.zeros((34000,))
SCREAMING_SNAKE_CASE_ = np.zeros((14000,))
return audio_classifier, [audioa, audio]
def lowerCAmelCase__ ( self , _A , _A):
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = examples
SCREAMING_SNAKE_CASE_ = audio_classifier(_A)
# by default a model is initialized with num_labels=2
self.assertEqual(
_A , [
{'score': ANY(_A), 'label': ANY(_A)},
{'score': ANY(_A), 'label': ANY(_A)},
] , )
SCREAMING_SNAKE_CASE_ = audio_classifier(_A , top_k=1)
self.assertEqual(
_A , [
{'score': ANY(_A), 'label': ANY(_A)},
] , )
self.run_torchaudio(_A)
@require_torchaudio
def lowerCAmelCase__ ( self , _A):
import datasets
# test with a local file
SCREAMING_SNAKE_CASE_ = datasets.load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation')
SCREAMING_SNAKE_CASE_ = dataset[0]['audio']['array']
SCREAMING_SNAKE_CASE_ = audio_classifier(_A)
self.assertEqual(
_A , [
{'score': ANY(_A), 'label': ANY(_A)},
{'score': ANY(_A), 'label': ANY(_A)},
] , )
@require_torch
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = 'anton-l/wav2vec2-random-tiny-classifier'
SCREAMING_SNAKE_CASE_ = pipeline('audio-classification' , model=_A)
SCREAMING_SNAKE_CASE_ = np.ones((8000,))
SCREAMING_SNAKE_CASE_ = audio_classifier(_A , top_k=4)
SCREAMING_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'},
]
SCREAMING_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(_A , decimals=4) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2])
SCREAMING_SNAKE_CASE_ = {'array': np.ones((8000,)), 'sampling_rate': audio_classifier.feature_extractor.sampling_rate}
SCREAMING_SNAKE_CASE_ = audio_classifier(_A , top_k=4)
self.assertIn(nested_simplify(_A , decimals=4) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2])
@require_torch
@slow
def lowerCAmelCase__ ( self):
import datasets
SCREAMING_SNAKE_CASE_ = 'superb/wav2vec2-base-superb-ks'
SCREAMING_SNAKE_CASE_ = pipeline('audio-classification' , model=_A)
SCREAMING_SNAKE_CASE_ = datasets.load_dataset('anton-l/superb_dummy' , 'ks' , split='test')
SCREAMING_SNAKE_CASE_ = np.array(dataset[3]['speech'] , dtype=np.floataa)
SCREAMING_SNAKE_CASE_ = audio_classifier(_A , top_k=4)
self.assertEqual(
nested_simplify(_A , 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 lowerCAmelCase__ ( self):
pass
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : int = 200 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ = [1, 2, 5, 10, 20, 50, 100, 200]
SCREAMING_SNAKE_CASE_ = [0] * (pence + 1)
SCREAMING_SNAKE_CASE_ = 1 # base case: 1 way to make 0 pence
for coin in coins:
for i in range(_SCREAMING_SNAKE_CASE , pence + 1 , 1 ):
number_of_ways[i] += number_of_ways[i - coin]
return number_of_ways[pence]
if __name__ == "__main__":
assert solution(200) == 73_682
| 620 | 1 |
import unittest
from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM
@require_torch
class __snake_case :
def __init__( self , _A , _A=99 , _A=13 , _A=16 , _A=7 , _A=True , _A=True , _A=True , _A=False , _A=True , _A=2 , _A=32 , _A=4 , _A=4 , _A=30 , _A=0 , _A=1 , _A=2 , _A=None , ):
SCREAMING_SNAKE_CASE_ = parent
SCREAMING_SNAKE_CASE_ = batch_size
SCREAMING_SNAKE_CASE_ = decoder_seq_length
# For common tests
SCREAMING_SNAKE_CASE_ = self.decoder_seq_length
SCREAMING_SNAKE_CASE_ = is_training
SCREAMING_SNAKE_CASE_ = use_attention_mask
SCREAMING_SNAKE_CASE_ = use_labels
SCREAMING_SNAKE_CASE_ = vocab_size
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = d_model
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_layers
SCREAMING_SNAKE_CASE_ = decoder_ffn_dim
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = decoder_attention_heads
SCREAMING_SNAKE_CASE_ = eos_token_id
SCREAMING_SNAKE_CASE_ = bos_token_id
SCREAMING_SNAKE_CASE_ = pad_token_id
SCREAMING_SNAKE_CASE_ = decoder_start_token_id
SCREAMING_SNAKE_CASE_ = use_cache
SCREAMING_SNAKE_CASE_ = max_position_embeddings
SCREAMING_SNAKE_CASE_ = None
SCREAMING_SNAKE_CASE_ = decoder_seq_length
SCREAMING_SNAKE_CASE_ = 2
SCREAMING_SNAKE_CASE_ = 1
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = None
if self.use_attention_mask:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2)
SCREAMING_SNAKE_CASE_ = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size)
SCREAMING_SNAKE_CASE_ = TrOCRConfig(
vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , )
return (config, input_ids, attention_mask, lm_labels)
def lowerCAmelCase__ ( self , _A , _A , _A , _A , ):
SCREAMING_SNAKE_CASE_ = True
SCREAMING_SNAKE_CASE_ = TrOCRDecoder(config=_A).to(_A).eval()
SCREAMING_SNAKE_CASE_ = input_ids[:2]
input_ids[input_ids == 0] += 1
# first forward pass
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
SCREAMING_SNAKE_CASE_ = model(_A)
SCREAMING_SNAKE_CASE_ = model(_A , use_cache=_A)
self.parent.assertTrue(len(_A) == len(_A))
self.parent.assertTrue(len(_A) == len(_A) + 1)
SCREAMING_SNAKE_CASE_ = outputs['past_key_values']
# create hypothetical next token and extent to next_input_ids
SCREAMING_SNAKE_CASE_ = ids_tensor((2, 1) , config.vocab_size - 1) + 1
# append to next input_ids and
SCREAMING_SNAKE_CASE_ = torch.cat([input_ids, next_tokens] , dim=-1)
SCREAMING_SNAKE_CASE_ = model(_A)['last_hidden_state']
SCREAMING_SNAKE_CASE_ = model(_A , past_key_values=_A)['last_hidden_state']
# select random slice
SCREAMING_SNAKE_CASE_ = ids_tensor((1,) , output_from_past.shape[-1]).item()
SCREAMING_SNAKE_CASE_ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
SCREAMING_SNAKE_CASE_ = output_from_past[:, 0, random_slice_idx].detach()
# test that outputs are equal for slice
assert torch.allclose(_A , _A , atol=1E-3)
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = config_and_inputs
SCREAMING_SNAKE_CASE_ = {'input_ids': input_ids, 'attention_mask': attention_mask}
return config, inputs_dict
@require_torch
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
__lowerCAmelCase : Tuple = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
__lowerCAmelCase : Union[str, Any] = (TrOCRForCausalLM,) if is_torch_available() else ()
__lowerCAmelCase : str = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
__lowerCAmelCase : Any = True
__lowerCAmelCase : str = False
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = TrOCRStandaloneDecoderModelTester(self , is_training=_A)
SCREAMING_SNAKE_CASE_ = ConfigTester(self , config_class=_A)
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
pass
def lowerCAmelCase__ ( self):
self.config_tester.run_common_tests()
def lowerCAmelCase__ ( self):
SCREAMING_SNAKE_CASE_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past(*_A)
def lowerCAmelCase__ ( self):
return
@unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :)
def lowerCAmelCase__ ( self):
pass
| 620 |
def _UpperCAmelCase ( _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : list , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ):
"""simple docstring"""
if index == number_of_items:
return 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = 0
SCREAMING_SNAKE_CASE_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 )
if weights[index] <= max_weight:
SCREAMING_SNAKE_CASE_ = values[index] + knapsack(
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 )
return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 620 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.