code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
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 a_ : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class _snake_case ( lowerCamelCase_ ): _lowercase : int = ['''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 , ) -> None: super().__init__(**__snake_case) SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 224} SCREAMING_SNAKE_CASE = get_size_dict(__snake_case , default_to_square=__snake_case) SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE = get_size_dict(__snake_case , default_to_square=__snake_case , 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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(__snake_case , default_to_square=__snake_case) 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(__snake_case , size=size['shortest_edge'] , default_to_square=__snake_case) return resize(__snake_case , size=__snake_case , resample=__snake_case , data_format=__snake_case , **__snake_case) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(__snake_case) 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(__snake_case , size=(size['height'], size['width']) , data_format=__snake_case , **__snake_case) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> List[Any]: return rescale(__snake_case , scale=__snake_case , data_format=__snake_case , **__snake_case) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(__snake_case , mean=__snake_case , std=__snake_case , data_format=__snake_case , **__snake_case) def SCREAMING_SNAKE_CASE__ ( 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 , ) -> PIL.Image.Image: 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(__snake_case , param_name='size' , default_to_square=__snake_case) 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(__snake_case , param_name='crop_size' , default_to_square=__snake_case) 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(__snake_case) if not valid_images(__snake_case): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_resize and size is None: 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(__snake_case) for image in images] # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(__snake_case) for image in images] if do_resize: SCREAMING_SNAKE_CASE = [self.resize(image=__snake_case , size=__snake_case , resample=__snake_case) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE = [self.center_crop(image=__snake_case , size=__snake_case) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=__snake_case , scale=__snake_case) for image in images] if do_normalize: SCREAMING_SNAKE_CASE = [self.normalize(image=__snake_case , mean=__snake_case , std=__snake_case) for image in images] SCREAMING_SNAKE_CASE = [to_channel_dimension_format(__snake_case , __snake_case) for image in images] SCREAMING_SNAKE_CASE = {'pixel_values': images} return BatchFeature(data=__snake_case , tensor_type=__snake_case)
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
import sys a_ : int = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCamelCase__ (_UpperCAmelCase = N): SCREAMING_SNAKE_CASE = -sys.maxsize - 1 for i in range(len(_UpperCAmelCase) - 12): SCREAMING_SNAKE_CASE = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: SCREAMING_SNAKE_CASE = product return largest_product if __name__ == "__main__": print(f"""{solution() = }""")
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
import numpy as np from PIL import Image def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = np.array(_UpperCAmelCase) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix') SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape SCREAMING_SNAKE_CASE = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix SCREAMING_SNAKE_CASE = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 return updated_arr def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = np.array(_UpperCAmelCase) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix') SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape SCREAMING_SNAKE_CASE = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix SCREAMING_SNAKE_CASE = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='avgpooling', verbose=True) # Loading the image a_ : Optional[int] = Image.open('path_to_image') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" def lowerCamelCase__ (_UpperCAmelCase): if not grid or not grid[0]: raise TypeError('The grid does not contain the appropriate information') for cell_n in range(1 , len(grid[0])): grid[0][cell_n] += grid[0][cell_n - 1] SCREAMING_SNAKE_CASE = grid[0] for row_n in range(1 , len(_UpperCAmelCase)): SCREAMING_SNAKE_CASE = grid[row_n] SCREAMING_SNAKE_CASE = fill_row(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = grid[row_n] return grid[-1][-1] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): current_row[0] += row_above[0] for cell_n in range(1 , len(_UpperCAmelCase)): current_row[cell_n] += min(current_row[cell_n - 1] , row_above[cell_n]) return current_row if __name__ == "__main__": import doctest doctest.testmod()
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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_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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=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()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: 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_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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample 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_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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import os import pytest from transformers.dynamic_module_utils import get_imports a_ : Optional[Any] = '\nimport os\n' a_ : List[str] = '\ndef foo():\n import os\n return False\n' a_ : Optional[int] = '\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n' a_ : str = '\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n' a_ : Any = '\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n' a_ : List[str] = '\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n' a_ : Union[str, Any] = '\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n' a_ : int = '\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n' a_ : Tuple = '\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n' a_ : Optional[int] = '\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n' a_ : List[str] = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize('case' , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , 'test_file.py') with open(_UpperCAmelCase , 'w') as _tmp_file: _tmp_file.write(_UpperCAmelCase) SCREAMING_SNAKE_CASE = get_imports(_UpperCAmelCase) assert parsed_imports == ["os"]
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging a_ : str = logging.get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase): """simple docstring""" if isinstance(_UpperCAmelCase , np.ndarray): return list(tensor.shape) SCREAMING_SNAKE_CASE = tf.shape(_UpperCAmelCase) if tensor.shape == tf.TensorShape(_UpperCAmelCase): return dynamic SCREAMING_SNAKE_CASE = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(_UpperCAmelCase)] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None): """simple docstring""" return tf.nn.softmax(logits=logits + 1e-9 , axis=_UpperCAmelCase , name=_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=1e-5 , _UpperCAmelCase=-1): """simple docstring""" if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_UpperCAmelCase , _UpperCAmelCase): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.') # Get mean and variance on the axis to be normalized SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tf.nn.moments(_UpperCAmelCase , axes=[axis] , keepdims=_UpperCAmelCase) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis SCREAMING_SNAKE_CASE = [1] * inputs.shape.rank SCREAMING_SNAKE_CASE = shape_list(_UpperCAmelCase)[axis] SCREAMING_SNAKE_CASE = tf.reshape(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = tf.reshape(_UpperCAmelCase , _UpperCAmelCase) # Compute layer normalization using the batch_normalization # function. SCREAMING_SNAKE_CASE = tf.nn.batch_normalization( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , offset=_UpperCAmelCase , scale=_UpperCAmelCase , variance_epsilon=_UpperCAmelCase , ) return outputs def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=0 , _UpperCAmelCase=-1): """simple docstring""" if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input SCREAMING_SNAKE_CASE = tf.shape(_UpperCAmelCase) SCREAMING_SNAKE_CASE = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]) SCREAMING_SNAKE_CASE = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0) return tf.reshape(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): """simple docstring""" if not isinstance(_UpperCAmelCase , tf.Tensor): SCREAMING_SNAKE_CASE = tf.convert_to_tensor(_UpperCAmelCase) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: SCREAMING_SNAKE_CASE = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: SCREAMING_SNAKE_CASE = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) SCREAMING_SNAKE_CASE = ( tf.cast(1 , encoder_attention_mask.dtype) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = "input_ids"): """simple docstring""" tf.debugging.assert_less( _UpperCAmelCase , tf.cast(_UpperCAmelCase , dtype=tensor.dtype) , message=( F'''The maximum value of {tensor_name} ({tf.math.reduce_max(_UpperCAmelCase)}) must be smaller than the embedding ''' F'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = 6_4512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. SCREAMING_SNAKE_CASE = [x for x in data if len(_UpperCAmelCase) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' F'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' F'''bytes: {bad_attributes}''') SCREAMING_SNAKE_CASE = np.asarray(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = np.array_split(_UpperCAmelCase , _UpperCAmelCase) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data): num_chunks += 1 SCREAMING_SNAKE_CASE = np.array_split(_UpperCAmelCase , _UpperCAmelCase) if num_chunks > 1: for chunk_id, chunk_data in enumerate(_UpperCAmelCase): SCREAMING_SNAKE_CASE = chunk_data else: SCREAMING_SNAKE_CASE = data def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): """simple docstring""" if name in group.attrs: SCREAMING_SNAKE_CASE = [n.decode('utf8') if hasattr(_UpperCAmelCase , 'decode') else n for n in group.attrs[name]] else: SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8') if hasattr(_UpperCAmelCase , 'decode') else n for n in group.attrs['%s%d' % (name, chunk_id)]]) chunk_id += 1 return data def lowerCamelCase__ (_UpperCAmelCase): """simple docstring""" def _expand_single_ad_tensor(_UpperCAmelCase): if isinstance(_UpperCAmelCase , tf.Tensor) and t.shape.rank == 1: return tf.expand_dims(_UpperCAmelCase , axis=-1) return t return tf.nest.map_structure(_expand_single_ad_tensor , _UpperCAmelCase)
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(s_dict.keys()) for key in keys: if "transformer_layers" in key: SCREAMING_SNAKE_CASE = s_dict.pop(_UpperCAmelCase) elif "subsample" in key: SCREAMING_SNAKE_CASE = s_dict.pop(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] SCREAMING_SNAKE_CASE = mam_aaa['model'] SCREAMING_SNAKE_CASE = state_dict['decoder.output_projection.weight'] remove_ignore_keys_(_UpperCAmelCase) rename_keys(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = args.share_decoder_input_output_embed SCREAMING_SNAKE_CASE = [int(_UpperCAmelCase) for i in args.conv_kernel_sizes.split(',')] SCREAMING_SNAKE_CASE = SpeechaTextConfig( vocab_size=_UpperCAmelCase , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , num_conv_layers=len(_UpperCAmelCase) , conv_channels=args.conv_channels , conv_kernel_sizes=_UpperCAmelCase , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=_UpperCAmelCase , num_beams=5 , max_length=200 , use_cache=_UpperCAmelCase , decoder_start_token_id=2 , early_stopping=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = SpeechaTextForConditionalGeneration(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) if len(_UpperCAmelCase) > 0 and not set(_UpperCAmelCase) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( 'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,' F''' but all the following weights are missing {missing}''') if tie_embeds: SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.decoder.embed_tokens) else: SCREAMING_SNAKE_CASE = lm_head_weights model.save_pretrained(_UpperCAmelCase) if __name__ == "__main__": a_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : Tuple = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): a_ : Any = 'pt' elif is_tf_available(): a_ : Union[str, Any] = 'tf' else: a_ : Tuple = 'jax' class _snake_case ( A__ , unittest.TestCase ): _lowercase : Any = ByTaTokenizer _lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() SCREAMING_SNAKE_CASE = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname) @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return ByTaTokenizer.from_pretrained('google/byt5-small') def SCREAMING_SNAKE_CASE__ ( self , **a) -> ByTaTokenizer: return self.tokenizer_class.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a=False , a=20 , a=5) -> Tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for ByT5 because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. SCREAMING_SNAKE_CASE = [] for i in range(len(a)): try: SCREAMING_SNAKE_CASE = tokenizer.decode([i] , clean_up_tokenization_spaces=a) except UnicodeDecodeError: pass toks.append((i, tok)) SCREAMING_SNAKE_CASE = list(filter(lambda a: re.match(R'^[ a-zA-Z]+$' , t[1]) , a)) SCREAMING_SNAKE_CASE = list(filter(lambda a: [t[0]] == tokenizer.encode(t[1] , add_special_tokens=a) , a)) if max_length is not None and len(a) > max_length: SCREAMING_SNAKE_CASE = toks[:max_length] if min_length is not None and len(a) < min_length and len(a) > 0: while len(a) < min_length: SCREAMING_SNAKE_CASE = toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE = [t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE = tokenizer.decode(a , clean_up_tokenization_spaces=a) if " " not in output_txt and len(a) > 1: SCREAMING_SNAKE_CASE = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=a) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=a) ) if with_prefix_space: SCREAMING_SNAKE_CASE = ' ' + output_txt SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) return output_txt, output_ids def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.ta_base_tokenizer SCREAMING_SNAKE_CASE = tokenizer(['hi</s>', 'I went to the gym</s>', '</s>']) SCREAMING_SNAKE_CASE = tokenizer(['hi', 'I went to the gym', '']) self.assertListEqual(batch_with_eos_added['input_ids'] , batch_without_eos_added['input_ids']) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.ta_base_tokenizer SCREAMING_SNAKE_CASE = 'Unicode €.' SCREAMING_SNAKE_CASE = tokenizer(a) SCREAMING_SNAKE_CASE = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['input_ids'] , a) # decoding SCREAMING_SNAKE_CASE = tokenizer.decode(a) self.assertEqual(a , 'Unicode €.</s>') SCREAMING_SNAKE_CASE = tokenizer('e è é ê ë') SCREAMING_SNAKE_CASE = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['input_ids'] , a) # decoding SCREAMING_SNAKE_CASE = tokenizer.decode(a) self.assertEqual(a , 'e è é ê ë</s>') # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë')) , 'e è é ê ë</s>') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.ta_base_tokenizer SCREAMING_SNAKE_CASE = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off SCREAMING_SNAKE_CASE = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on SCREAMING_SNAKE_CASE = tokenizer(a , padding=a , return_tensors=a) self.assertIsInstance(a , a) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE = list(batch.input_ids.numpy()[0]) else: SCREAMING_SNAKE_CASE = list(batch.input_ids.tolist()[0]) self.assertListEqual(a , a) self.assertEqual((2, 37) , batch.input_ids.shape) self.assertEqual((2, 37) , batch.attention_mask.shape) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.ta_base_tokenizer SCREAMING_SNAKE_CASE = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] SCREAMING_SNAKE_CASE = tokenizer(a , padding=a , return_tensors=a) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , a) self.assertIn('attention_mask' , a) self.assertNotIn('decoder_input_ids' , a) self.assertNotIn('decoder_attention_mask' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.ta_base_tokenizer SCREAMING_SNAKE_CASE = [ 'Summary of the text.', 'Another summary.', ] SCREAMING_SNAKE_CASE = tokenizer( text_target=a , max_length=32 , padding='max_length' , truncation=a , return_tensors=a) self.assertEqual(32 , targets['input_ids'].shape[1]) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.ta_base_tokenizer SCREAMING_SNAKE_CASE = ['A long paragraph for summarization. </s>'] SCREAMING_SNAKE_CASE = ['Summary of the text. </s>'] # fmt: off SCREAMING_SNAKE_CASE = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] SCREAMING_SNAKE_CASE = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on SCREAMING_SNAKE_CASE = tokenizer(a , text_target=a) self.assertEqual(a , batch['input_ids'][0]) self.assertEqual(a , batch['labels'][0]) def SCREAMING_SNAKE_CASE__ ( self) -> str: # safety check on max_len default value so we are sure the test works SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): self.assertNotEqual(tokenizer.model_max_length , 42) # Now let's start the test SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = ' He is very happy, UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) tokenizer.save_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(a) SCREAMING_SNAKE_CASE = after_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) shutil.rmtree(a) SCREAMING_SNAKE_CASE = self.get_tokenizers(model_max_length=42) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam']) SCREAMING_SNAKE_CASE = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token') tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens}) SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) tokenizer.save_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(a) SCREAMING_SNAKE_CASE = after_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens) self.assertEqual(after_tokenizer.model_max_length , 42) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(a , model_max_length=43) self.assertEqual(tokenizer.model_max_length , 43) shutil.rmtree(a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(a) with open(os.path.join(a , 'special_tokens_map.json') , encoding='utf-8') as json_file: SCREAMING_SNAKE_CASE = json.load(a) with open(os.path.join(a , 'tokenizer_config.json') , encoding='utf-8') as json_file: SCREAMING_SNAKE_CASE = json.load(a) SCREAMING_SNAKE_CASE = [f'''<extra_id_{i}>''' for i in range(125)] SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [ 'an_additional_special_token' ] SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(a , 'special_tokens_map.json') , 'w' , encoding='utf-8') as outfile: json.dump(a , a) with open(os.path.join(a , 'tokenizer_config.json') , 'w' , encoding='utf-8') as outfile: json.dump(a , a) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained( a , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'])) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=a)] SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained( a , additional_special_tokens=a , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'])) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained(a) self.assertTrue(tokenizer.decode([255]) == '') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: pass def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: pass def SCREAMING_SNAKE_CASE__ ( self) -> str: # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings # and special added tokens as tokens SCREAMING_SNAKE_CASE = self.get_tokenizers(fast=a , do_lower_case=a) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): SCREAMING_SNAKE_CASE = ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 'x', 't', '</s>'] SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_string(a) self.assertIsInstance(a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): SCREAMING_SNAKE_CASE = [ 'bos_token', 'eos_token', 'unk_token', 'sep_token', 'pad_token', 'cls_token', 'mask_token', ] SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens( a , skip_special_tokens=a) for attr in attributes_list: setattr(a , attr + '_id' , a) self.assertEqual(getattr(a , a) , a) self.assertEqual(getattr(a , attr + '_id') , a) setattr(a , attr + '_id' , a) self.assertEqual(getattr(a , a) , a) self.assertEqual(getattr(a , attr + '_id') , a) setattr(a , 'additional_special_tokens_ids' , []) self.assertListEqual(getattr(a , 'additional_special_tokens') , []) self.assertListEqual(getattr(a , 'additional_special_tokens_ids') , []) setattr(a , 'additional_special_tokens_ids' , [token_id_to_test_setters]) self.assertListEqual(getattr(a , 'additional_special_tokens') , [token_to_test_setters]) self.assertListEqual(getattr(a , 'additional_special_tokens_ids') , [token_id_to_test_setters])
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return [1] + ([0] * len(a)) + [1] return [1] + ([0] * len(a)) + [1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a_ : Dict = logging.get_logger(__name__) a_ : Tuple = { 'post_extract_proj': 'feature_projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.upsample.0': 'encoder.upsample.projection', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'layer_norm', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for attribute in key.split('.'): SCREAMING_SNAKE_CASE = getattr(_UpperCAmelCase , _UpperCAmelCase) if weight_type is not None: SCREAMING_SNAKE_CASE = getattr(_UpperCAmelCase , _UpperCAmelCase).shape else: SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( 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 else: SCREAMING_SNAKE_CASE = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = fairseq_model.state_dict() SCREAMING_SNAKE_CASE = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , hf_model.config.feat_extract_norm == 'group' , ) SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): SCREAMING_SNAKE_CASE = 'sew.' + mapped_key if (is_finetuned and mapped_key != 'lm_head') 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(_UpperCAmelCase)[0].split('.')[-2] SCREAMING_SNAKE_CASE = mapped_key.replace('*' , _UpperCAmelCase) if "weight_g" in name: SCREAMING_SNAKE_CASE = 'weight_g' elif "weight_v" in name: SCREAMING_SNAKE_CASE = 'weight_v' elif "weight" in name: SCREAMING_SNAKE_CASE = 'weight' elif "bias" in name: SCREAMING_SNAKE_CASE = 'bias' else: SCREAMING_SNAKE_CASE = None set_recursively(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) continue if not is_used: unused_weights.append(_UpperCAmelCase) logger.warning(F'''Unused weights: {unused_weights}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): 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: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( 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: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[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(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = SEWConfig() if is_finetuned: SCREAMING_SNAKE_CASE = model.wav_encoder.wav_model.cfg else: SCREAMING_SNAKE_CASE = model.cfg SCREAMING_SNAKE_CASE = fs_config.conv_bias SCREAMING_SNAKE_CASE = eval(fs_config.conv_feature_layers) SCREAMING_SNAKE_CASE = [x[0] for x in conv_layers] SCREAMING_SNAKE_CASE = [x[1] for x in conv_layers] SCREAMING_SNAKE_CASE = [x[2] for x in conv_layers] SCREAMING_SNAKE_CASE = 'gelu' SCREAMING_SNAKE_CASE = 'layer' if fs_config.extractor_mode == 'layer_norm' else 'group' SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = fs_config.activation_fn.name SCREAMING_SNAKE_CASE = fs_config.encoder_embed_dim SCREAMING_SNAKE_CASE = 0.02 SCREAMING_SNAKE_CASE = fs_config.encoder_ffn_embed_dim SCREAMING_SNAKE_CASE = 1e-5 SCREAMING_SNAKE_CASE = fs_config.encoder_layerdrop SCREAMING_SNAKE_CASE = fs_config.encoder_attention_heads SCREAMING_SNAKE_CASE = fs_config.conv_pos_groups SCREAMING_SNAKE_CASE = fs_config.conv_pos SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = fs_config.encoder_layers SCREAMING_SNAKE_CASE = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: SCREAMING_SNAKE_CASE = model.cfg SCREAMING_SNAKE_CASE = fs_config.final_dropout SCREAMING_SNAKE_CASE = fs_config.layerdrop SCREAMING_SNAKE_CASE = fs_config.activation_dropout SCREAMING_SNAKE_CASE = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 SCREAMING_SNAKE_CASE = fs_config.attention_dropout SCREAMING_SNAKE_CASE = fs_config.dropout_input SCREAMING_SNAKE_CASE = fs_config.dropout SCREAMING_SNAKE_CASE = fs_config.mask_channel_length SCREAMING_SNAKE_CASE = fs_config.mask_channel_prob SCREAMING_SNAKE_CASE = fs_config.mask_length SCREAMING_SNAKE_CASE = fs_config.mask_prob SCREAMING_SNAKE_CASE = 'Wav2Vec2FeatureExtractor' SCREAMING_SNAKE_CASE = 'Wav2Vec2CTCTokenizer' return config @torch.no_grad() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=True): 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 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]) if config_path is not None: SCREAMING_SNAKE_CASE = SEWConfig.from_pretrained(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = convert_config(model[0] , _UpperCAmelCase) SCREAMING_SNAKE_CASE = model[0].eval() SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == 'layer' else False SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=_UpperCAmelCase , return_attention_mask=_UpperCAmelCase , ) if is_finetuned: if dict_path: SCREAMING_SNAKE_CASE = Dictionary.load(_UpperCAmelCase) # 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.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(_UpperCAmelCase , 'vocab.json') if not os.path.isdir(_UpperCAmelCase): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(_UpperCAmelCase)) return os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) with open(_UpperCAmelCase , 'w' , encoding='utf-8') as vocab_handle: json.dump(target_dict.indices , _UpperCAmelCase) SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( _UpperCAmelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=_UpperCAmelCase , ) SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=_UpperCAmelCase , tokenizer=_UpperCAmelCase) processor.save_pretrained(_UpperCAmelCase) SCREAMING_SNAKE_CASE = SEWForCTC(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = SEWModel(_UpperCAmelCase) feature_extractor.save_pretrained(_UpperCAmelCase) recursively_load_weights(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) hf_model.save_pretrained(_UpperCAmelCase) if __name__ == "__main__": a_ : Tuple = 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( '--is_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) a_ : List[str] = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) self.log(a) else: SCREAMING_SNAKE_CASE = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , a) return metrics def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_test_dataloader(a) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , 'predict') SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available a_ : int = {'tokenization_herbert': ['HerbertTokenizer']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['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 a_ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) a_ : List[str] = logging.getLogger(__name__) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = git.Repo(search_parent_directories=_UpperCAmelCase) SCREAMING_SNAKE_CASE = { 'repo_id': str(_UpperCAmelCase), 'repo_sha': str(repo.head.object.hexsha), 'repo_branch': str(repo.active_branch), } with open(os.path.join(_UpperCAmelCase , 'git_log.json') , 'w') as f: json.dump(_UpperCAmelCase , _UpperCAmelCase , indent=4) def lowerCamelCase__ (_UpperCAmelCase): if params.n_gpu <= 0: SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = -1 SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False return assert torch.cuda.is_available() logger.info('Initializing GPUs') if params.n_gpu > 1: assert params.local_rank != -1 SCREAMING_SNAKE_CASE = int(os.environ['WORLD_SIZE']) SCREAMING_SNAKE_CASE = int(os.environ['N_GPU_NODE']) SCREAMING_SNAKE_CASE = int(os.environ['RANK']) # number of nodes / node ID SCREAMING_SNAKE_CASE = params.world_size // params.n_gpu_per_node SCREAMING_SNAKE_CASE = params.global_rank // params.n_gpu_per_node SCREAMING_SNAKE_CASE = True assert params.n_nodes == int(os.environ['N_NODES']) assert params.node_id == int(os.environ['NODE_RANK']) # local job (single GPU) else: assert params.local_rank == -1 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode SCREAMING_SNAKE_CASE = params.node_id == 0 and params.local_rank == 0 SCREAMING_SNAKE_CASE = params.n_nodes > 1 # summary SCREAMING_SNAKE_CASE = F'''--- Global rank: {params.global_rank} - ''' logger.info(PREFIX + 'Number of nodes: %i' % params.n_nodes) logger.info(PREFIX + 'Node ID : %i' % params.node_id) logger.info(PREFIX + 'Local rank : %i' % params.local_rank) logger.info(PREFIX + 'World size : %i' % params.world_size) logger.info(PREFIX + 'GPUs per node : %i' % params.n_gpu_per_node) logger.info(PREFIX + 'Master : %s' % str(params.is_master)) logger.info(PREFIX + 'Multi-node : %s' % str(params.multi_node)) logger.info(PREFIX + 'Multi-GPU : %s' % str(params.multi_gpu)) logger.info(PREFIX + 'Hostname : %s' % socket.gethostname()) # set GPU device torch.cuda.set_device(params.local_rank) # initialize multi-GPU if params.multi_gpu: logger.info('Initializing PyTorch distributed') torch.distributed.init_process_group( init_method='env://' , backend='nccl' , ) def lowerCamelCase__ (_UpperCAmelCase): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed)
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
import math import sys def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' try: with open(_UpperCAmelCase , 'rb') as binary_file: SCREAMING_SNAKE_CASE = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE = F'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = '', '' SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) for i in range(len(_UpperCAmelCase)): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE = last_match_id + '0' if math.loga(_UpperCAmelCase).is_integer(): SCREAMING_SNAKE_CASE = {} for curr_key in list(_UpperCAmelCase): SCREAMING_SNAKE_CASE = lexicon.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = new_lex SCREAMING_SNAKE_CASE = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE = '' return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 8 try: with open(_UpperCAmelCase , 'wb') as opened_file: SCREAMING_SNAKE_CASE = [ to_write[i : i + byte_length] for i in range(0 , len(_UpperCAmelCase) , _UpperCAmelCase) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append('10000000') else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(_UpperCAmelCase , 2).to_bytes(1 , byteorder='big')) except OSError: print('File not accessible') sys.exit() def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE = data_bits[counter:] SCREAMING_SNAKE_CASE = data_bits[counter + 1 :] return data_bits def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = read_file_binary(_UpperCAmelCase) SCREAMING_SNAKE_CASE = remove_prefix(_UpperCAmelCase) SCREAMING_SNAKE_CASE = decompress_data(_UpperCAmelCase) write_file_binary(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
a_ : str = { 'a': 'AAAAA', 'b': 'AAAAB', 'c': 'AAABA', 'd': 'AAABB', 'e': 'AABAA', 'f': 'AABAB', 'g': 'AABBA', 'h': 'AABBB', 'i': 'ABAAA', 'j': 'BBBAA', 'k': 'ABAAB', 'l': 'ABABA', 'm': 'ABABB', 'n': 'ABBAA', 'o': 'ABBAB', 'p': 'ABBBA', 'q': 'ABBBB', 'r': 'BAAAA', 's': 'BAAAB', 't': 'BAABA', 'u': 'BAABB', 'v': 'BBBAB', 'w': 'BABAA', 'x': 'BABAB', 'y': 'BABBA', 'z': 'BABBB', ' ': ' ', } a_ : Union[str, Any] = {value: key for key, value in encode_dict.items()} def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('encode() accepts only letters of the alphabet and spaces') return encoded def lowerCamelCase__ (_UpperCAmelCase): if set(_UpperCAmelCase) - {"A", "B", " "} != set(): raise Exception('decode() accepts only \'A\', \'B\' and spaces') SCREAMING_SNAKE_CASE = '' for word in coded.split(): while len(_UpperCAmelCase) != 0: decoded += decode_dict[word[:5]] SCREAMING_SNAKE_CASE = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : List[Any] = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys a_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=A__ ) class _snake_case ( A__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization _lowercase : str = field(default='''question-answering-extractive''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) _lowercase : ClassVar[Features] = Features({'''question''': Value('''string''' ), '''context''': Value('''string''' )} ) _lowercase : ClassVar[Features] = Features( { '''answers''': Sequence( { '''text''': Value('''string''' ), '''answer_start''': Value('''int32''' ), } ) } ) _lowercase : str = "question" _lowercase : str = "context" _lowercase : str = "answers" @property def SCREAMING_SNAKE_CASE__ ( self) -> Dict[str, str]: return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): assert isinstance(_UpperCAmelCase , _UpperCAmelCase) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE = ParquetDatasetReader(_UpperCAmelCase , cache_dir=_UpperCAmelCase , keep_in_memory=_UpperCAmelCase).read() _check_parquet_dataset(_UpperCAmelCase , _UpperCAmelCase) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} SCREAMING_SNAKE_CASE = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE = ( Features({feature: Value(_UpperCAmelCase) for feature, dtype in features.items()}) if features is not None else None ) SCREAMING_SNAKE_CASE = ParquetDatasetReader(_UpperCAmelCase , features=_UpperCAmelCase , cache_dir=_UpperCAmelCase).read() _check_parquet_dataset(_UpperCAmelCase , _UpperCAmelCase) @pytest.mark.parametrize('split' , [None, NamedSplit('train'), 'train', 'test']) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} SCREAMING_SNAKE_CASE = ParquetDatasetReader(_UpperCAmelCase , cache_dir=_UpperCAmelCase , split=_UpperCAmelCase).read() _check_parquet_dataset(_UpperCAmelCase , _UpperCAmelCase) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if issubclass(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = parquet_path elif issubclass(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [parquet_path] SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} SCREAMING_SNAKE_CASE = ParquetDatasetReader(_UpperCAmelCase , cache_dir=_UpperCAmelCase).read() _check_parquet_dataset(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=("train",)): assert isinstance(_UpperCAmelCase , _UpperCAmelCase) for split in splits: SCREAMING_SNAKE_CASE = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE = ParquetDatasetReader( {'train': parquet_path} , cache_dir=_UpperCAmelCase , keep_in_memory=_UpperCAmelCase).read() _check_parquet_datasetdict(_UpperCAmelCase , _UpperCAmelCase) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} SCREAMING_SNAKE_CASE = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE = ( Features({feature: Value(_UpperCAmelCase) for feature, dtype in features.items()}) if features is not None else None ) SCREAMING_SNAKE_CASE = ParquetDatasetReader({'train': parquet_path} , features=_UpperCAmelCase , cache_dir=_UpperCAmelCase).read() _check_parquet_datasetdict(_UpperCAmelCase , _UpperCAmelCase) @pytest.mark.parametrize('split' , [None, NamedSplit('train'), 'train', 'test']) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if split: SCREAMING_SNAKE_CASE = {split: parquet_path} else: SCREAMING_SNAKE_CASE = 'train' SCREAMING_SNAKE_CASE = {'train': parquet_path, 'test': parquet_path} SCREAMING_SNAKE_CASE = tmp_path / 'cache' SCREAMING_SNAKE_CASE = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} SCREAMING_SNAKE_CASE = ParquetDatasetReader(_UpperCAmelCase , cache_dir=_UpperCAmelCase).read() _check_parquet_datasetdict(_UpperCAmelCase , _UpperCAmelCase , splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = ParquetDatasetWriter(_UpperCAmelCase , tmp_path / 'foo.parquet') assert writer.write() > 0 SCREAMING_SNAKE_CASE = pq.ParquetFile(tmp_path / 'foo.parquet') SCREAMING_SNAKE_CASE = pf.read() assert dataset.data.table == output_table def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = str(shared_datadir / 'test_image_rgb.jpg') SCREAMING_SNAKE_CASE = {'image': [image_path]} SCREAMING_SNAKE_CASE = Features({'image': Image()}) SCREAMING_SNAKE_CASE = Dataset.from_dict(_UpperCAmelCase , features=_UpperCAmelCase) SCREAMING_SNAKE_CASE = ParquetDatasetWriter(_UpperCAmelCase , tmp_path / 'foo.parquet') assert writer.write() > 0 SCREAMING_SNAKE_CASE = Dataset.from_parquet(str(tmp_path / 'foo.parquet')) assert dataset.features == reloaded_dataset.features SCREAMING_SNAKE_CASE = ParquetDatasetReader(str(tmp_path / 'foo.parquet') , streaming=_UpperCAmelCase).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( 'feature, expected' , [ (Features({'foo': Value('int32')}), None), (Features({'image': Image(), 'foo': Value('int32')}), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({'nested': Sequence(Audio())}), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): assert get_writer_batch_size(_UpperCAmelCase) == expected
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on SCREAMING_SNAKE_CASE = dict(zip(a , range(len(a)))) SCREAMING_SNAKE_CASE = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</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: fp.write(json.dumps(a) + '\n') with open(self.merges_file , 'w' , encoding='utf-8') as fp: fp.write('\n'.join(a)) SCREAMING_SNAKE_CASE = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , a) with open(self.image_processor_file , 'w' , encoding='utf-8') as fp: json.dump(a , a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Any: return CLIPTokenizer.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> List[str]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> List[str]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> int: 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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=a , image_processor=a) processor_slow.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=a) SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=a , image_processor=a) processor_fast.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = CLIPSegProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab()) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab()) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab()) self.assertIsInstance(processor_slow.tokenizer , a) self.assertIsInstance(processor_fast.tokenizer , a) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string()) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string()) self.assertIsInstance(processor_slow.image_processor , a) self.assertIsInstance(processor_fast.image_processor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = CLIPSegProcessor(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 = CLIPSegProcessor.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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(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 SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=a , image_processor=a) SCREAMING_SNAKE_CASE = 'lower newer' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(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()) , ['input_ids', 'attention_mask', 'pixel_values']) # test if it raises when no input is passed with pytest.raises(a): processor() def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=a , image_processor=a) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(images=a , visual_prompt=a) self.assertListEqual(list(inputs.keys()) , ['pixel_values', 'conditional_pixel_values']) # test if it raises when no input is passed with pytest.raises(a): processor() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(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)
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a_ : Optional[int] = logging.get_logger(__name__) a_ : List[str] = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class _snake_case ( A__ ): _lowercase : List[str] = '''gptj''' _lowercase : Tuple = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , a=5_0400 , a=2048 , a=4096 , a=28 , a=16 , a=64 , a=None , a="gelu_new" , a=0.0 , a=0.0 , a=0.0 , a=1E-5 , a=0.02 , a=True , a=5_0256 , a=5_0256 , a=False , **a , ) -> str: SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = n_positions SCREAMING_SNAKE_CASE = n_embd SCREAMING_SNAKE_CASE = n_layer SCREAMING_SNAKE_CASE = n_head SCREAMING_SNAKE_CASE = n_inner SCREAMING_SNAKE_CASE = rotary_dim SCREAMING_SNAKE_CASE = activation_function SCREAMING_SNAKE_CASE = resid_pdrop SCREAMING_SNAKE_CASE = embd_pdrop SCREAMING_SNAKE_CASE = attn_pdrop SCREAMING_SNAKE_CASE = layer_norm_epsilon SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = bos_token_id SCREAMING_SNAKE_CASE = eos_token_id super().__init__( bos_token_id=a , eos_token_id=a , tie_word_embeddings=a , **a) class _snake_case ( A__ ): def __init__( self , a , a = "default" , a = None , a = False , ) -> Optional[Any]: super().__init__(a , task=a , patching_specs=a , use_past=a) if not getattr(self._config , 'pad_token_id' , a): # TODO: how to do that better? SCREAMING_SNAKE_CASE = 0 @property def SCREAMING_SNAKE_CASE__ ( self) -> Mapping[str, Mapping[int, str]]: SCREAMING_SNAKE_CASE = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}) if self.use_past: self.fill_with_past_key_values_(a , direction='inputs') SCREAMING_SNAKE_CASE = {0: 'batch', 1: 'past_sequence + sequence'} else: SCREAMING_SNAKE_CASE = {0: 'batch', 1: 'sequence'} return common_inputs @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return self._config.n_layer @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return self._config.n_head def SCREAMING_SNAKE_CASE__ ( self , a , a = -1 , a = -1 , a = False , a = None , ) -> Mapping[str, Any]: SCREAMING_SNAKE_CASE = super(a , self).generate_dummy_inputs( a , batch_size=a , seq_length=a , is_pair=a , framework=a) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE = OrderedDict({'input_ids': common_inputs['input_ids']}) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.') else: import torch SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = common_inputs['input_ids'].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE = seqlen + 2 SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE = [ (torch.zeros(a), torch.zeros(a)) for _ in range(self.num_layers) ] SCREAMING_SNAKE_CASE = common_inputs['attention_mask'] if self.use_past: SCREAMING_SNAKE_CASE = ordered_inputs['attention_mask'].dtype SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs['attention_mask'], torch.ones(a , a , dtype=a)] , dim=1) return ordered_inputs @property def SCREAMING_SNAKE_CASE__ ( self) -> int: return 13
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embeddings_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = len(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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.num_labels) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) SCREAMING_SNAKE_CASE = model(a) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(a) , expected_num_stages + 1) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) 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([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
from __future__ import annotations from collections import namedtuple def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = namedtuple('result' , 'name value') if (voltage, current, power).count(0) != 1: raise ValueError('Only one argument must be 0') elif power < 0: raise ValueError( 'Power cannot be negative in any electrical/electronics system') elif voltage == 0: return result('voltage' , power / current) elif current == 0: return result('current' , power / voltage) elif power == 0: return result('power' , float(round(abs(voltage * current) , 2))) else: raise ValueError('Exactly one argument must be 0') if __name__ == "__main__": import doctest doctest.testmod()
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() a_ : str = logging.get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = 'backbone.' if is_semantic else '' SCREAMING_SNAKE_CASE = [] for i in range(config.num_hidden_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''{prefix}blocks.{i}.norm1.weight''', F'''beit.encoder.layer.{i}.layernorm_before.weight''')) rename_keys.append((F'''{prefix}blocks.{i}.norm1.bias''', F'''beit.encoder.layer.{i}.layernorm_before.bias''')) rename_keys.append( (F'''{prefix}blocks.{i}.attn.proj.weight''', F'''beit.encoder.layer.{i}.attention.output.dense.weight''')) rename_keys.append( (F'''{prefix}blocks.{i}.attn.proj.bias''', F'''beit.encoder.layer.{i}.attention.output.dense.bias''')) rename_keys.append((F'''{prefix}blocks.{i}.norm2.weight''', F'''beit.encoder.layer.{i}.layernorm_after.weight''')) rename_keys.append((F'''{prefix}blocks.{i}.norm2.bias''', F'''beit.encoder.layer.{i}.layernorm_after.bias''')) rename_keys.append((F'''{prefix}blocks.{i}.mlp.fc1.weight''', F'''beit.encoder.layer.{i}.intermediate.dense.weight''')) rename_keys.append((F'''{prefix}blocks.{i}.mlp.fc1.bias''', F'''beit.encoder.layer.{i}.intermediate.dense.bias''')) rename_keys.append((F'''{prefix}blocks.{i}.mlp.fc2.weight''', F'''beit.encoder.layer.{i}.output.dense.weight''')) rename_keys.append((F'''{prefix}blocks.{i}.mlp.fc2.bias''', F'''beit.encoder.layer.{i}.output.dense.bias''')) # projection layer + position embeddings rename_keys.extend( [ (F'''{prefix}cls_token''', 'beit.embeddings.cls_token'), (F'''{prefix}patch_embed.proj.weight''', 'beit.embeddings.patch_embeddings.projection.weight'), (F'''{prefix}patch_embed.proj.bias''', 'beit.embeddings.patch_embeddings.projection.bias'), (F'''{prefix}pos_embed''', 'beit.embeddings.position_embeddings'), ]) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ('mask_token', 'beit.embeddings.mask_token'), ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ]) else: # layernorm + classification head rename_keys.extend( [ ('fc_norm.weight', 'beit.pooler.layernorm.weight'), ('fc_norm.bias', 'beit.pooler.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ]) return rename_keys def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False , _UpperCAmelCase=False): for i in range(config.num_hidden_layers): SCREAMING_SNAKE_CASE = 'backbone.' if is_semantic else '' # queries, keys and values SCREAMING_SNAKE_CASE = state_dict.pop(F'''{prefix}blocks.{i}.attn.qkv.weight''') SCREAMING_SNAKE_CASE = state_dict.pop(F'''{prefix}blocks.{i}.attn.q_bias''') SCREAMING_SNAKE_CASE = state_dict.pop(F'''{prefix}blocks.{i}.attn.v_bias''') SCREAMING_SNAKE_CASE = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE = q_bias SCREAMING_SNAKE_CASE = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained SCREAMING_SNAKE_CASE = state_dict.pop(F'''{prefix}blocks.{i}.gamma_1''') SCREAMING_SNAKE_CASE = state_dict.pop(F'''{prefix}blocks.{i}.gamma_2''') SCREAMING_SNAKE_CASE = gamma_a SCREAMING_SNAKE_CASE = gamma_a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = dct.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase).raw) return im @torch.no_grad() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = False if 'rvlcdip' in checkpoint_url else True SCREAMING_SNAKE_CASE = BeitConfig(use_absolute_position_embeddings=_UpperCAmelCase , use_mask_token=_UpperCAmelCase) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: SCREAMING_SNAKE_CASE = 1024 SCREAMING_SNAKE_CASE = 4096 SCREAMING_SNAKE_CASE = 24 SCREAMING_SNAKE_CASE = 16 # labels if "rvlcdip" in checkpoint_url: SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 'huggingface/label-files' SCREAMING_SNAKE_CASE = 'rvlcdip-id2label.json' SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase , repo_type='dataset') , 'r')) SCREAMING_SNAKE_CASE = {int(_UpperCAmelCase): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(_UpperCAmelCase , map_location='cpu')['model'] SCREAMING_SNAKE_CASE = create_rename_keys(_UpperCAmelCase , has_lm_head=_UpperCAmelCase) for src, dest in rename_keys: rename_key(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) read_in_q_k_v(_UpperCAmelCase , _UpperCAmelCase , has_lm_head=_UpperCAmelCase) # load HuggingFace model SCREAMING_SNAKE_CASE = BeitForMaskedImageModeling(_UpperCAmelCase) if has_lm_head else BeitForImageClassification(_UpperCAmelCase) model.eval() model.load_state_dict(_UpperCAmelCase) # Check outputs on an image SCREAMING_SNAKE_CASE = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=_UpperCAmelCase) SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=_UpperCAmelCase , return_tensors='pt') SCREAMING_SNAKE_CASE = encoding['pixel_values'] SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.logits # verify logits SCREAMING_SNAKE_CASE = [1, 16] if 'rvlcdip' in checkpoint_url else [1, 196, 8192] assert logits.shape == torch.Size(_UpperCAmelCase), "Shape of logits not as expected" Path(_UpperCAmelCase).mkdir(exist_ok=_UpperCAmelCase) print(F'''Saving model to {pytorch_dump_folder_path}''') model.save_pretrained(_UpperCAmelCase) print(F'''Saving image processor to {pytorch_dump_folder_path}''') image_processor.save_pretrained(_UpperCAmelCase) if push_to_hub: if has_lm_head: SCREAMING_SNAKE_CASE = 'dit-base' if 'base' in checkpoint_url else 'dit-large' else: SCREAMING_SNAKE_CASE = 'dit-base-finetuned-rvlcdip' if 'dit-b' in checkpoint_url else 'dit-large-finetuned-rvlcdip' image_processor.push_to_hub( repo_path_or_name=Path(_UpperCAmelCase , _UpperCAmelCase) , organization='nielsr' , commit_message='Add image processor' , use_temp_dir=_UpperCAmelCase , ) model.push_to_hub( repo_path_or_name=Path(_UpperCAmelCase , _UpperCAmelCase) , organization='nielsr' , commit_message='Add model' , use_temp_dir=_UpperCAmelCase , ) if __name__ == "__main__": a_ : Dict = argparse.ArgumentParser() parser.add_argument( '--checkpoint_url', default='https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth', type=str, help='URL to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument( '--push_to_hub', action='store_true', ) a_ : int = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
import math from collections.abc import Iterator from itertools import takewhile def lowerCamelCase__ (_UpperCAmelCase): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase) + 1) , 6): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 2 while True: if is_prime(_UpperCAmelCase): yield num num += 1 def lowerCamelCase__ (_UpperCAmelCase = 200_0000): return sum(takewhile(lambda _UpperCAmelCase: x < n , prime_generator())) if __name__ == "__main__": print(f"""{solution() = }""")
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
import multiprocessing import os from typing import BinaryIO, Optional, Union import fsspec from .. import Dataset, Features, NamedSplit, config from ..formatting import query_table from ..packaged_modules.json.json import Json from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class _snake_case ( A__ ): def __init__( self , a , a = None , a = None , a = None , a = False , a = False , a = None , a = None , **a , ) -> Any: super().__init__( a , split=a , features=a , cache_dir=a , keep_in_memory=a , streaming=a , num_proc=a , **a , ) SCREAMING_SNAKE_CASE = field SCREAMING_SNAKE_CASE = path_or_paths if isinstance(a , a) else {self.split: path_or_paths} SCREAMING_SNAKE_CASE = Json( cache_dir=a , data_files=a , features=a , field=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # 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 = None , **a , ) -> int: if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''') SCREAMING_SNAKE_CASE = dataset SCREAMING_SNAKE_CASE = path_or_buf SCREAMING_SNAKE_CASE = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE = num_proc SCREAMING_SNAKE_CASE = 'utf-8' SCREAMING_SNAKE_CASE = to_json_kwargs def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop('path_or_buf' , a) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop('orient' , 'records') SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop('lines' , True if orient == 'records' else False) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop('index' , False if orient in ['split', 'table'] else True) SCREAMING_SNAKE_CASE = self.to_json_kwargs.pop('compression' , a) if compression not in [None, "infer", "gzip", "bz2", "xz"]: raise NotImplementedError(f'''`datasets` currently does not support {compression} compression''') if isinstance(self.path_or_buf , (str, bytes, os.PathLike)): with fsspec.open(self.path_or_buf , 'wb' , compression=a) as buffer: SCREAMING_SNAKE_CASE = self._write(file_obj=a , orient=a , lines=a , index=a , **self.to_json_kwargs) else: if compression: raise NotImplementedError( f'''The compression parameter is not supported when writing to a buffer, but compression={compression}''' ' was passed. Please provide a local path instead.') SCREAMING_SNAKE_CASE = self._write( file_obj=self.path_or_buf , orient=a , lines=a , index=a , **self.to_json_kwargs) return written def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = args SCREAMING_SNAKE_CASE = query_table( table=self.dataset.data , key=slice(a , offset + self.batch_size) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE = batch.to_pandas().to_json( path_or_buf=a , orient=a , lines=a , index=a , **a) if not json_str.endswith('\n'): json_str += "\n" return json_str.encode(self.encoding) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , **a , ) -> int: SCREAMING_SNAKE_CASE = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset) , self.batch_size) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating json from Arrow format' , ): SCREAMING_SNAKE_CASE = self._batch_json((offset, orient, lines, index, to_json_kwargs)) written += file_obj.write(a) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = len(self.dataset), self.batch_size with multiprocessing.Pool(self.num_proc) as pool: for json_str in logging.tqdm( pool.imap( self._batch_json , [(offset, orient, lines, index, to_json_kwargs) for offset in range(0 , a , a)] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating json from Arrow format' , ): written += file_obj.write(a) return written
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) a_ : List[str] = {'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = ['BeitFeatureExtractor'] a_ : int = ['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = [ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[int] = [ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys a_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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_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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=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()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: 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_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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample 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_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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
from math import ceil, sqrt def lowerCamelCase__ (_UpperCAmelCase = 100_0000): SCREAMING_SNAKE_CASE = 0 for outer_width in range(3 , (limit // 4) + 2): if outer_width**2 > limit: SCREAMING_SNAKE_CASE = max(ceil(sqrt(outer_width**2 - limit)) , 1) else: SCREAMING_SNAKE_CASE = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL a_ : Any = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Union[str, Any] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PIL.Image.BICUBIC , a = True , a = None , a = 1 / 255 , a = True , a = True , a = None , a = None , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 256, 'width': 256} SCREAMING_SNAKE_CASE = get_size_dict(a) SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {'height': 224, 'width': 224} 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_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 IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE__ ( self , a , a , a = PIL.Image.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''') return resize( a , size=(size['height'], size['width']) , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}''') return center_crop(a , size=(size['height'], size['width']) , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> str: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( 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 = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: 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_center_crop if do_center_crop is not None else self.do_center_crop 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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(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 or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.') if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.') # All transformations expect numpy arrays. 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)
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file SCREAMING_SNAKE_CASE = TapasConfig.from_json_file(_UpperCAmelCase) # set absolute/relative position embeddings parameter SCREAMING_SNAKE_CASE = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": SCREAMING_SNAKE_CASE = TapasForQuestionAnswering(config=_UpperCAmelCase) elif task == "WTQ": # run_task_main.py hparams SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = True # hparam_utils.py hparams SCREAMING_SNAKE_CASE = 0.66_46_94 SCREAMING_SNAKE_CASE = 0.20_79_51 SCREAMING_SNAKE_CASE = 0.12_11_94 SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = 0.0_35_25_13 SCREAMING_SNAKE_CASE = TapasForQuestionAnswering(config=_UpperCAmelCase) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = False # hparam_utils.py hparams SCREAMING_SNAKE_CASE = 36.45_19 SCREAMING_SNAKE_CASE = 0.90_34_21 SCREAMING_SNAKE_CASE = 222.088 SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = 0.76_31_41 SCREAMING_SNAKE_CASE = TapasForQuestionAnswering(config=_UpperCAmelCase) elif task == "TABFACT": SCREAMING_SNAKE_CASE = TapasForSequenceClassification(config=_UpperCAmelCase) elif task == "MLM": SCREAMING_SNAKE_CASE = TapasForMaskedLM(config=_UpperCAmelCase) elif task == "INTERMEDIATE_PRETRAINING": SCREAMING_SNAKE_CASE = TapasModel(config=_UpperCAmelCase) else: raise ValueError(F'''Task {task} not supported.''') print(F'''Building PyTorch model from configuration: {config}''') # Load weights from tf checkpoint load_tf_weights_in_tapas(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Save pytorch-model (weights and configuration) print(F'''Save PyTorch model to {pytorch_dump_path}''') model.save_pretrained(_UpperCAmelCase) # Save tokenizer files print(F'''Save tokenizer files to {pytorch_dump_path}''') SCREAMING_SNAKE_CASE = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + 'vocab.txt' , model_max_length=512) tokenizer.save_pretrained(_UpperCAmelCase) print('Used relative position embeddings:' , model.config.reset_position_index_per_cell) if __name__ == "__main__": a_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ : str = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets a_ : Dict = '\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n author = "Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John",\n booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n month = aug # " 8-12",\n year = "2006",\n address = "Cambridge, Massachusetts, USA",\n publisher = "Association for Machine Translation in the Americas",\n url = "https://aclanthology.org/2006.amta-papers.25",\n pages = "223--231",\n}\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' a_ : Optional[Any] = '\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n' a_ : int = '\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n \'num_edits\' (int): The cumulative number of edits\n \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n Example 2:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n Example 3:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n Example 4:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n Example 5:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: if version.parse(scb.__version__) < version.parse('1.4.12'): raise ImportWarning( 'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n' 'You can install it with `pip install "sacrebleu>=1.4.12"`.') return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='http://www.cs.umd.edu/~snover/tercom/' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Sequence(datasets.Value('string' , id='sequence') , id='references'), }) , codebase_urls=['https://github.com/mjpost/sacreBLEU#ter'] , reference_urls=[ 'https://github.com/jhclark/tercom', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = False , a = False , a = False , a = False , ) -> Optional[int]: SCREAMING_SNAKE_CASE = len(references[0]) if any(len(a) != references_per_prediction for refs in references): raise ValueError('Sacrebleu requires the same number of references for each prediction') SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(a)] SCREAMING_SNAKE_CASE = TER( normalized=a , no_punct=a , asian_support=a , case_sensitive=a , ) SCREAMING_SNAKE_CASE = sb_ter.corpus_score(a , a) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return [1] + ([0] * len(a)) + [1] return [1] + ([0] * len(a)) + [1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _snake_case : def __init__( self , a , a=13 , a=30 , a=2 , a=3 , a=True , a=True , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=10 , a=0.02 , a=None , ) -> List[str]: 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 # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE = num_patches + 1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = ViTMSNModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = self.type_sequence_label_size SCREAMING_SNAKE_CASE = ViTMSNForImageClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , labels=a) print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}') print('Labels: {labels}') self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) # test greyscale images SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = ViTMSNForImageClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE__ ( self) -> str: 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_torch class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : Union[str, Any] = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () _lowercase : Any = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) _lowercase : List[str] = False _lowercase : List[str] = False _lowercase : Dict = False _lowercase : Tuple = False def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ViTMSNModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='ViTMSN does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Dict: 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() , (nn.Module)) SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear)) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ['pixel_values'] self.assertListEqual(arg_names[:1] , a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = ViTMSNModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') return image @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> int: return ViTImageProcessor.from_pretrained('facebook/vit-msn-small') if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: torch.manual_seed(2) SCREAMING_SNAKE_CASE = ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small').to(a) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=a , return_tensors='pt').to(a) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = torch.tensor([-0.08_03, -0.44_54, -0.23_75]).to(a) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a , atol=1E-4))
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) self.log(a) else: SCREAMING_SNAKE_CASE = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , a) return metrics def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_test_dataloader(a) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , 'predict') SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : int = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a_ : List[Any] = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } a_ : List[str] = { 'squeezebert/squeezebert-uncased': 5_12, 'squeezebert/squeezebert-mnli': 5_12, 'squeezebert/squeezebert-mnli-headless': 5_12, } a_ : List[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_INIT_CONFIGURATION _lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : List[str] = SqueezeBertTokenizer def __init__( self , a=None , a=None , a=True , a="[UNK]" , a="[SEP]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a=True , a=None , **a , ) -> List[Any]: super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('lowercase' , a) != do_lower_case or normalizer_state.get('strip_accents' , a) != strip_accents or normalizer_state.get('handle_chinese_chars' , a) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE = getattr(a , normalizer_state.pop('type')) SCREAMING_SNAKE_CASE = do_lower_case SCREAMING_SNAKE_CASE = strip_accents SCREAMING_SNAKE_CASE = tokenize_chinese_chars SCREAMING_SNAKE_CASE = normalizer_class(**a) SCREAMING_SNAKE_CASE = do_lower_case def SCREAMING_SNAKE_CASE__ ( self , a , a=None) -> List[str]: SCREAMING_SNAKE_CASE = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig a_ : Dict = logging.get_logger(__name__) # General docstring a_ : Any = 'MobileNetV1Config' # Base docstring a_ : Any = 'google/mobilenet_v1_1.0_224' a_ : Optional[Any] = [1, 10_24, 7, 7] # Image classification docstring a_ : str = 'google/mobilenet_v1_1.0_224' a_ : int = 'tabby, tabby cat' a_ : Any = [ 'google/mobilenet_v1_1.0_224', 'google/mobilenet_v1_0.75_192', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = {} if isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = model.mobilenet_va else: SCREAMING_SNAKE_CASE = model SCREAMING_SNAKE_CASE = 'MobilenetV1/Conv2d_0/' SCREAMING_SNAKE_CASE = backbone.conv_stem.convolution.weight SCREAMING_SNAKE_CASE = backbone.conv_stem.normalization.bias SCREAMING_SNAKE_CASE = backbone.conv_stem.normalization.weight SCREAMING_SNAKE_CASE = backbone.conv_stem.normalization.running_mean SCREAMING_SNAKE_CASE = backbone.conv_stem.normalization.running_var for i in range(13): SCREAMING_SNAKE_CASE = i + 1 SCREAMING_SNAKE_CASE = i * 2 SCREAMING_SNAKE_CASE = backbone.layer[pt_index] SCREAMING_SNAKE_CASE = F'''MobilenetV1/Conv2d_{tf_index}_depthwise/''' SCREAMING_SNAKE_CASE = pointer.convolution.weight SCREAMING_SNAKE_CASE = pointer.normalization.bias SCREAMING_SNAKE_CASE = pointer.normalization.weight SCREAMING_SNAKE_CASE = pointer.normalization.running_mean SCREAMING_SNAKE_CASE = pointer.normalization.running_var SCREAMING_SNAKE_CASE = backbone.layer[pt_index + 1] SCREAMING_SNAKE_CASE = F'''MobilenetV1/Conv2d_{tf_index}_pointwise/''' SCREAMING_SNAKE_CASE = pointer.convolution.weight SCREAMING_SNAKE_CASE = pointer.normalization.bias SCREAMING_SNAKE_CASE = pointer.normalization.weight SCREAMING_SNAKE_CASE = pointer.normalization.running_mean SCREAMING_SNAKE_CASE = pointer.normalization.running_var if isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 'MobilenetV1/Logits/Conv2d_1c_1x1/' SCREAMING_SNAKE_CASE = model.classifier.weight SCREAMING_SNAKE_CASE = model.classifier.bias return tf_to_pt_map def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): try: import numpy as np import tensorflow as tf except ImportError: logger.error( 'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ' 'https://www.tensorflow.org/install/ for installation instructions.') raise # Load weights from TF model SCREAMING_SNAKE_CASE = tf.train.list_variables(_UpperCAmelCase) SCREAMING_SNAKE_CASE = {} for name, shape in init_vars: logger.info(F'''Loading TF weight {name} with shape {shape}''') SCREAMING_SNAKE_CASE = tf.train.load_variable(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = array # Build TF to PyTorch weights loading map SCREAMING_SNAKE_CASE = _build_tf_to_pytorch_map(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) for name, pointer in tf_to_pt_map.items(): logger.info(F'''Importing {name}''') if name not in tf_weights: logger.info(F'''{name} not in tf pre-trained weights, skipping''') continue SCREAMING_SNAKE_CASE = tf_weights[name] if "depthwise_weights" in name: logger.info('Transposing depthwise') SCREAMING_SNAKE_CASE = np.transpose(_UpperCAmelCase , (2, 3, 0, 1)) elif "weights" in name: logger.info('Transposing') if len(pointer.shape) == 2: # copying into linear layer SCREAMING_SNAKE_CASE = array.squeeze().transpose() else: SCREAMING_SNAKE_CASE = np.transpose(_UpperCAmelCase , (3, 2, 0, 1)) if pointer.shape != array.shape: raise ValueError(F'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched''') logger.info(F'''Initialize PyTorch weight {name} {array.shape}''') SCREAMING_SNAKE_CASE = torch.from_numpy(_UpperCAmelCase) tf_weights.pop(_UpperCAmelCase , _UpperCAmelCase) tf_weights.pop(name + '/RMSProp' , _UpperCAmelCase) tf_weights.pop(name + '/RMSProp_1' , _UpperCAmelCase) tf_weights.pop(name + '/ExponentialMovingAverage' , _UpperCAmelCase) logger.info(F'''Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}''') return model def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = features.shape[-2:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = conv_layer.stride SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = conv_layer.kernel_size if in_height % stride_height == 0: SCREAMING_SNAKE_CASE = max(kernel_height - stride_height , 0) else: SCREAMING_SNAKE_CASE = max(kernel_height - (in_height % stride_height) , 0) if in_width % stride_width == 0: SCREAMING_SNAKE_CASE = max(kernel_width - stride_width , 0) else: SCREAMING_SNAKE_CASE = max(kernel_width - (in_width % stride_width) , 0) SCREAMING_SNAKE_CASE = pad_along_width // 2 SCREAMING_SNAKE_CASE = pad_along_width - pad_left SCREAMING_SNAKE_CASE = pad_along_height // 2 SCREAMING_SNAKE_CASE = pad_along_height - pad_top SCREAMING_SNAKE_CASE = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_UpperCAmelCase , _UpperCAmelCase , 'constant' , 0.0) class _snake_case ( nn.Module ): def __init__( self , a , a , a , a , a = 1 , a = 1 , a = False , a = True , a = True , ) -> None: super().__init__() SCREAMING_SNAKE_CASE = config if in_channels % groups != 0: raise ValueError(f'''Input channels ({in_channels}) are not divisible by {groups} groups.''') if out_channels % groups != 0: raise ValueError(f'''Output channels ({out_channels}) are not divisible by {groups} groups.''') SCREAMING_SNAKE_CASE = 0 if config.tf_padding else int((kernel_size - 1) / 2) SCREAMING_SNAKE_CASE = nn.Convad( in_channels=a , out_channels=a , kernel_size=a , stride=a , padding=a , groups=a , bias=a , padding_mode='zeros' , ) if use_normalization: SCREAMING_SNAKE_CASE = nn.BatchNormad( num_features=a , eps=config.layer_norm_eps , momentum=0.99_97 , affine=a , track_running_stats=a , ) else: SCREAMING_SNAKE_CASE = None if use_activation: if isinstance(a , a): SCREAMING_SNAKE_CASE = ACTaFN[use_activation] elif isinstance(config.hidden_act , a): SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE = config.hidden_act else: SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> torch.Tensor: if self.config.tf_padding: SCREAMING_SNAKE_CASE = apply_tf_padding(a , self.convolution) SCREAMING_SNAKE_CASE = self.convolution(a) if self.normalization is not None: SCREAMING_SNAKE_CASE = self.normalization(a) if self.activation is not None: SCREAMING_SNAKE_CASE = self.activation(a) return features class _snake_case ( A__ ): _lowercase : List[str] = MobileNetVaConfig _lowercase : str = load_tf_weights_in_mobilenet_va _lowercase : Any = '''mobilenet_v1''' _lowercase : Optional[Any] = '''pixel_values''' _lowercase : Any = False def SCREAMING_SNAKE_CASE__ ( self , a) -> None: if isinstance(a , (nn.Linear, nn.Convad)): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(a , nn.BatchNormad): module.bias.data.zero_() module.weight.data.fill_(1.0) a_ : Dict = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' a_ : Union[str, Any] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , A__ , ) class _snake_case ( A__ ): def __init__( self , a , a = True) -> Union[str, Any]: super().__init__(a) SCREAMING_SNAKE_CASE = config SCREAMING_SNAKE_CASE = 32 SCREAMING_SNAKE_CASE = max(int(depth * config.depth_multiplier) , config.min_depth) SCREAMING_SNAKE_CASE = MobileNetVaConvLayer( a , in_channels=config.num_channels , out_channels=a , kernel_size=3 , stride=2 , ) SCREAMING_SNAKE_CASE = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] SCREAMING_SNAKE_CASE = nn.ModuleList() for i in range(13): SCREAMING_SNAKE_CASE = out_channels if strides[i] == 2 or i == 0: depth *= 2 SCREAMING_SNAKE_CASE = max(int(depth * config.depth_multiplier) , config.min_depth) self.layer.append( MobileNetVaConvLayer( a , in_channels=a , out_channels=a , kernel_size=3 , stride=strides[i] , groups=a , )) self.layer.append( MobileNetVaConvLayer( a , in_channels=a , out_channels=a , kernel_size=1 , )) SCREAMING_SNAKE_CASE = nn.AdaptiveAvgPoolad((1, 1)) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: raise NotImplementedError @add_start_docstrings_to_model_forward(a) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def SCREAMING_SNAKE_CASE__ ( self , a = None , a = None , a = None , ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]: SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values') SCREAMING_SNAKE_CASE = self.conv_stem(a) SCREAMING_SNAKE_CASE = () if output_hidden_states else None for i, layer_module in enumerate(self.layer): SCREAMING_SNAKE_CASE = layer_module(a) if output_hidden_states: SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) SCREAMING_SNAKE_CASE = hidden_states if self.pooler is not None: SCREAMING_SNAKE_CASE = torch.flatten(self.pooler(a) , start_dim=1) else: SCREAMING_SNAKE_CASE = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a , pooler_output=a , hidden_states=a , ) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , A__ , ) class _snake_case ( A__ ): def __init__( self , a) -> None: super().__init__(a) SCREAMING_SNAKE_CASE = config.num_labels SCREAMING_SNAKE_CASE = MobileNetVaModel(a) SCREAMING_SNAKE_CASE = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head SCREAMING_SNAKE_CASE = nn.Dropout(config.classifier_dropout_prob , inplace=a) SCREAMING_SNAKE_CASE = nn.Linear(a , config.num_labels) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def SCREAMING_SNAKE_CASE__ ( self , a = None , a = None , a = None , a = None , ) -> Union[tuple, ImageClassifierOutputWithNoAttention]: SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE = self.mobilenet_va(a , output_hidden_states=a , return_dict=a) SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE = self.classifier(self.dropout(a)) SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE = 'single_label_classification' else: SCREAMING_SNAKE_CASE = 'multi_label_classification' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() , labels.squeeze()) else: SCREAMING_SNAKE_CASE = loss_fct(a , a) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE = CrossEntropyLoss() SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels) , labels.view(-1)) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE = loss_fct(a , a) if not return_dict: SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=a , logits=a , hidden_states=outputs.hidden_states , )
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): print(F'''Vertex\tShortest Distance from vertex {src}''') for i, d in enumerate(_UpperCAmelCase): print(F'''{i}\t\t{d}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): for j in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = (graph[j][k] for k in ['src', 'dst', 'weight']) if distance[u] != float('inf') and distance[u] + w < distance[v]: return True return False def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [float('inf')] * vertex_count SCREAMING_SNAKE_CASE = 0.0 for _ in range(vertex_count - 1): for j in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = (graph[j][k] for k in ['src', 'dst', 'weight']) if distance[u] != float('inf') and distance[u] + w < distance[v]: SCREAMING_SNAKE_CASE = distance[u] + w SCREAMING_SNAKE_CASE = check_negative_cycle(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if negative_cycle_exists: raise Exception('Negative cycle found') return distance if __name__ == "__main__": import doctest doctest.testmod() a_ : Optional[Any] = int(input('Enter number of vertices: ').strip()) a_ : Tuple = int(input('Enter number of edges: ').strip()) a_ : list[dict[str, int]] = [{} for _ in range(E)] for i in range(E): print('Edge ', i + 1) a_ : Dict = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) a_ : str = {'src': src, 'dst': dest, 'weight': weight} a_ : Optional[Any] = int(input('\nEnter shortest path source:').strip()) a_ : Optional[int] = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
from ..utils import DummyObject, requires_backends class _snake_case ( metaclass=A__ ): _lowercase : Union[str, Any] = ['''transformers''', '''torch''', '''note_seq'''] def __init__( self , *a , **a) -> Union[str, Any]: requires_backends(self , ['transformers', 'torch', 'note_seq']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Any: requires_backends(cls , ['transformers', 'torch', 'note_seq']) @classmethod def SCREAMING_SNAKE_CASE__ ( cls , *a , **a) -> Union[str, Any]: requires_backends(cls , ['transformers', 'torch', 'note_seq'])
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for line in lines: SCREAMING_SNAKE_CASE = re.sub(R'#.*' , '' , _UpperCAmelCase) # remove comments if line: filtered_lines.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE = '\n'.join(_UpperCAmelCase) # Make a hash from all this code SCREAMING_SNAKE_CASE = full_str.encode('utf-8') return shaaaa(_UpperCAmelCase).hexdigest() # get importable module names and hash for caching a_ : int = { 'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), 'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), 'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), 'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), 'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), 'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), 'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), 'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions a_ : List[Any] = { '.csv': ('csv', {}), '.tsv': ('csv', {'sep': '\t'}), '.json': ('json', {}), '.jsonl': ('json', {}), '.parquet': ('parquet', {}), '.arrow': ('arrow', {}), '.txt': ('text', {}), } _EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) a_ : Optional[Any] = {'imagefolder', 'audiofolder'} # Used to filter data files based on extensions given a module name a_ : Dict[str, List[str]] = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append('.zip') _MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
import fire from utils import calculate_rouge, save_json def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , **_UpperCAmelCase): SCREAMING_SNAKE_CASE = [x.strip() for x in open(_UpperCAmelCase).readlines()] SCREAMING_SNAKE_CASE = [x.strip() for x in open(_UpperCAmelCase).readlines()][: len(_UpperCAmelCase)] SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase) if save_path is not None: save_json(_UpperCAmelCase , _UpperCAmelCase , indent=_UpperCAmelCase) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType a_ : str = False, False, False @dataclass class _snake_case : _lowercase : Optional[int] = None _lowercase : bool = True _lowercase : bool = True _lowercase : Optional[str] = None # Automatically constructed _lowercase : ClassVar[str] = "dict" _lowercase : ClassVar[Any] = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) _lowercase : str = field(default='''Audio''' , init=A__ , repr=A__ ) def __call__( self) -> Optional[int]: return self.pa_type def SCREAMING_SNAKE_CASE__ ( self , a) -> dict: try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError('To support encoding audio data, please install \'soundfile\'.') from err if isinstance(a , a): return {"bytes": None, "path": value} elif isinstance(a , a): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes SCREAMING_SNAKE_CASE = BytesIO() sf.write(a , value['array'] , value['sampling_rate'] , format='wav') return {"bytes": buffer.getvalue(), "path": None} elif value.get('path') is not None and os.path.isfile(value['path']): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith('pcm'): # "PCM" only has raw audio bytes if value.get('sampling_rate') is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError('To use PCM files, please specify a \'sampling_rate\' in Audio object') if value.get('bytes'): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) SCREAMING_SNAKE_CASE = np.frombuffer(value['bytes'] , dtype=np.intaa).astype(np.floataa) / 3_2767 else: SCREAMING_SNAKE_CASE = np.memmap(value['path'] , dtype='h' , mode='r').astype(np.floataa) / 3_2767 SCREAMING_SNAKE_CASE = BytesIO(bytes()) sf.write(a , a , value['sampling_rate'] , format='wav') return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get('path')} elif value.get('bytes') is not None or value.get('path') is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get('bytes'), "path": value.get('path')} else: raise ValueError( f'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''') def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> dict: if not self.decode: raise RuntimeError('Decoding is disabled for this feature. Please use Audio(decode=True) instead.') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = (value['path'], BytesIO(value['bytes'])) if value['bytes'] is not None else (value['path'], None) if path is None and file is None: raise ValueError(f'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''') try: import librosa import soundfile as sf except ImportError as err: raise ImportError('To support decoding audio files, please install \'librosa\' and \'soundfile\'.') from err SCREAMING_SNAKE_CASE = xsplitext(a)[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( 'Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, ' 'You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ') elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( 'Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, ' 'You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ') if file is None: SCREAMING_SNAKE_CASE = token_per_repo_id or {} SCREAMING_SNAKE_CASE = path.split('::')[-1] try: SCREAMING_SNAKE_CASE = string_to_dict(a , config.HUB_DATASETS_URL)['repo_id'] SCREAMING_SNAKE_CASE = token_per_repo_id[repo_id] except (ValueError, KeyError): SCREAMING_SNAKE_CASE = None with xopen(a , 'rb' , use_auth_token=a) as f: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = sf.read(a) else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = sf.read(a) SCREAMING_SNAKE_CASE = array.T if self.mono: SCREAMING_SNAKE_CASE = librosa.to_mono(a) if self.sampling_rate and self.sampling_rate != sampling_rate: SCREAMING_SNAKE_CASE = librosa.resample(a , orig_sr=a , target_sr=self.sampling_rate) SCREAMING_SNAKE_CASE = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def SCREAMING_SNAKE_CASE__ ( self) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value if self.decode: raise ValueError('Cannot flatten a decoded Audio feature.') return { "bytes": Value('binary'), "path": Value('string'), } def SCREAMING_SNAKE_CASE__ ( self , a) -> pa.StructArray: if pa.types.is_string(storage.type): SCREAMING_SNAKE_CASE = pa.array([None] * len(a) , type=pa.binary()) SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ['bytes', 'path'] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): SCREAMING_SNAKE_CASE = pa.array([None] * len(a) , type=pa.string()) SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([storage, path_array] , ['bytes', 'path'] , mask=storage.is_null()) elif pa.types.is_struct(storage.type) and storage.type.get_all_field_indices('array'): SCREAMING_SNAKE_CASE = pa.array([Audio().encode_example(a) if x is not None else None for x in storage.to_pylist()]) elif pa.types.is_struct(storage.type): if storage.type.get_field_index('bytes') >= 0: SCREAMING_SNAKE_CASE = storage.field('bytes') else: SCREAMING_SNAKE_CASE = pa.array([None] * len(a) , type=pa.binary()) if storage.type.get_field_index('path') >= 0: SCREAMING_SNAKE_CASE = storage.field('path') else: SCREAMING_SNAKE_CASE = pa.array([None] * len(a) , type=pa.string()) SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=storage.is_null()) return array_cast(a , self.pa_type) def SCREAMING_SNAKE_CASE__ ( self , a) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(a): with xopen(a , 'rb') as f: SCREAMING_SNAKE_CASE = f.read() return bytes_ SCREAMING_SNAKE_CASE = pa.array( [ (path_to_bytes(x['path']) if x['bytes'] is None else x['bytes']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(a) if path is not None else None for path in storage.field('path').to_pylist()] , type=pa.string() , ) SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null()) return array_cast(a , self.pa_type)
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig a_ : Tuple = logging.get_logger(__name__) a_ : Any = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class _snake_case ( A__ ): _lowercase : Union[str, Any] = '''dpt''' def __init__( self , a=768 , a=12 , a=12 , a=3072 , a="gelu" , a=0.0 , a=0.0 , a=0.02 , a=1E-12 , a=384 , a=16 , a=3 , a=False , a=True , a=[2, 5, 8, 11] , a="project" , a=[4, 2, 1, 0.5] , a=[96, 192, 384, 768] , a=256 , a=-1 , a=False , a=True , a=0.4 , a=255 , a=0.1 , a=[1, 1024, 24, 24] , a=[0, 1] , a=None , **a , ) -> Optional[Any]: super().__init__(**a) SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info('Initializing the config with a `BiT` backbone.') SCREAMING_SNAKE_CASE = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, } SCREAMING_SNAKE_CASE = BitConfig(**a) elif isinstance(a , a): logger.info('Initializing the config with a `BiT` backbone.') SCREAMING_SNAKE_CASE = BitConfig(**a) elif isinstance(a , a): SCREAMING_SNAKE_CASE = backbone_config else: raise ValueError( f'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''') SCREAMING_SNAKE_CASE = backbone_featmap_shape SCREAMING_SNAKE_CASE = neck_ignore_stages if readout_type != "project": raise ValueError('Readout type must be \'project\' when using `DPT-hybrid` mode.') else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] 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 = image_size SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = qkv_bias SCREAMING_SNAKE_CASE = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError('Readout_type must be one of [\'ignore\', \'add\', \'project\']') SCREAMING_SNAKE_CASE = readout_type SCREAMING_SNAKE_CASE = reassemble_factors SCREAMING_SNAKE_CASE = neck_hidden_sizes SCREAMING_SNAKE_CASE = fusion_hidden_size SCREAMING_SNAKE_CASE = head_in_index SCREAMING_SNAKE_CASE = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE = use_auxiliary_head SCREAMING_SNAKE_CASE = auxiliary_loss_weight SCREAMING_SNAKE_CASE = semantic_loss_ignore_index SCREAMING_SNAKE_CASE = semantic_classifier_dropout def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE = self.__class__.model_type return output
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = fname.split(os.path.sep)[-1] return re.search(R'^(.*)_\d+\.jpg$' , _UpperCAmelCase).groups()[0] class _snake_case ( A__ ): def __init__( self , a , a=None , a=None) -> Dict: SCREAMING_SNAKE_CASE = file_names SCREAMING_SNAKE_CASE = image_transform SCREAMING_SNAKE_CASE = label_to_id def __len__( self) -> List[str]: return len(self.file_names) def __getitem__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = self.file_names[idx] SCREAMING_SNAKE_CASE = PIL.Image.open(a) SCREAMING_SNAKE_CASE = raw_image.convert('RGB') if self.image_transform is not None: SCREAMING_SNAKE_CASE = self.image_transform(a) SCREAMING_SNAKE_CASE = extract_label(a) if self.label_to_id is not None: SCREAMING_SNAKE_CASE = self.label_to_id[label] return {"image": image, "label": label} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Initialize accelerator if args.with_tracking: SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir) else: 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 = config['image_size'] if not isinstance(_UpperCAmelCase , (list, tuple)): SCREAMING_SNAKE_CASE = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , 'isdigit'): if args.checkpointing_steps == "epoch": SCREAMING_SNAKE_CASE = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): SCREAMING_SNAKE_CASE = int(args.checkpointing_steps) else: raise ValueError( F'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''') else: SCREAMING_SNAKE_CASE = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: SCREAMING_SNAKE_CASE = os.path.split(_UpperCAmelCase)[-1].split('.')[0] accelerator.init_trackers(_UpperCAmelCase , _UpperCAmelCase) # Grab all the image filenames SCREAMING_SNAKE_CASE = [os.path.join(args.data_dir , _UpperCAmelCase) for fname in os.listdir(args.data_dir) if fname.endswith('.jpg')] # Build the label correspondences SCREAMING_SNAKE_CASE = [extract_label(_UpperCAmelCase) for fname in file_names] SCREAMING_SNAKE_CASE = list(set(_UpperCAmelCase)) id_to_label.sort() SCREAMING_SNAKE_CASE = {lbl: i for i, lbl in enumerate(_UpperCAmelCase)} # Set the seed before splitting the data. np.random.seed(_UpperCAmelCase) torch.manual_seed(_UpperCAmelCase) torch.cuda.manual_seed_all(_UpperCAmelCase) # Split our filenames between train and validation SCREAMING_SNAKE_CASE = np.random.permutation(len(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = int(0.8 * len(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = random_perm[:cut] SCREAMING_SNAKE_CASE = random_perm[cut:] # For training we use a simple RandomResizedCrop SCREAMING_SNAKE_CASE = Compose([RandomResizedCrop(_UpperCAmelCase , scale=(0.5, 1.0)), ToTensor()]) SCREAMING_SNAKE_CASE = PetsDataset( [file_names[i] for i in train_split] , image_transform=_UpperCAmelCase , label_to_id=_UpperCAmelCase) # For evaluation, we use a deterministic Resize SCREAMING_SNAKE_CASE = Compose([Resize(_UpperCAmelCase), ToTensor()]) SCREAMING_SNAKE_CASE = PetsDataset([file_names[i] for i in eval_split] , image_transform=_UpperCAmelCase , label_to_id=_UpperCAmelCase) # Instantiate dataloaders. SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , batch_size=_UpperCAmelCase , num_workers=4) SCREAMING_SNAKE_CASE = DataLoader(_UpperCAmelCase , shuffle=_UpperCAmelCase , batch_size=_UpperCAmelCase , num_workers=4) # Instantiate the model (we build the model here so that the seed also control new weights initialization) SCREAMING_SNAKE_CASE = create_model('resnet50d' , pretrained=_UpperCAmelCase , num_classes=len(_UpperCAmelCase)) # 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) # Freezing the base model for param in model.parameters(): SCREAMING_SNAKE_CASE = False for param in model.get_classifier().parameters(): SCREAMING_SNAKE_CASE = True # We normalize the batches of images to be a bit faster. SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg['mean'])[None, :, None, None].to(accelerator.device) SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg['std'])[None, :, None, None].to(accelerator.device) # Instantiate optimizer SCREAMING_SNAKE_CASE = torch.optim.Adam(params=model.parameters() , lr=lr / 25) # Instantiate learning rate scheduler SCREAMING_SNAKE_CASE = OneCycleLR(optimizer=_UpperCAmelCase , max_lr=_UpperCAmelCase , epochs=_UpperCAmelCase , steps_per_epoch=len(_UpperCAmelCase)) # 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( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # We need to keep track of how many total steps we have iterated over SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the starting epoch so files are named properly SCREAMING_SNAKE_CASE = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F'''Resumed from checkpoint: {args.resume_from_checkpoint}''') accelerator.load_state(args.resume_from_checkpoint) SCREAMING_SNAKE_CASE = os.path.basename(args.resume_from_checkpoint) else: # Get the most recent checkpoint SCREAMING_SNAKE_CASE = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] dirs.sort(key=os.path.getctime) SCREAMING_SNAKE_CASE = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` SCREAMING_SNAKE_CASE = os.path.splitext(_UpperCAmelCase)[0] if "epoch" in training_difference: SCREAMING_SNAKE_CASE = int(training_difference.replace('epoch_' , '')) + 1 SCREAMING_SNAKE_CASE = None else: SCREAMING_SNAKE_CASE = int(training_difference.replace('step_' , '')) SCREAMING_SNAKE_CASE = resume_step // len(_UpperCAmelCase) resume_step -= starting_epoch * len(_UpperCAmelCase) # Now we train the model for epoch in range(_UpperCAmelCase , _UpperCAmelCase): model.train() if args.with_tracking: SCREAMING_SNAKE_CASE = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step SCREAMING_SNAKE_CASE = accelerator.skip_first_batches(_UpperCAmelCase , _UpperCAmelCase) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader SCREAMING_SNAKE_CASE = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device) for k, v in batch.items()} SCREAMING_SNAKE_CASE = (batch['image'] - mean) / std SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.nn.functional.cross_entropy(_UpperCAmelCase , batch['label']) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(_UpperCAmelCase) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = F'''step_{overall_step}''' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , _UpperCAmelCase) accelerator.save_state(_UpperCAmelCase) model.eval() SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(_UpperCAmelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device) for k, v in batch.items()} SCREAMING_SNAKE_CASE = (batch['image'] - mean) / std with torch.no_grad(): SCREAMING_SNAKE_CASE = model(_UpperCAmelCase) SCREAMING_SNAKE_CASE = outputs.argmax(dim=-1) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch['label'])) SCREAMING_SNAKE_CASE = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() SCREAMING_SNAKE_CASE = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}: {100 * eval_metric:.2f}''') if args.with_tracking: accelerator.log( { 'accuracy': 100 * eval_metric, 'train_loss': total_loss.item() / len(_UpperCAmelCase), 'epoch': epoch, } , step=_UpperCAmelCase , ) if checkpointing_steps == "epoch": SCREAMING_SNAKE_CASE = F'''epoch_{epoch}''' if args.output_dir is not None: SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , _UpperCAmelCase) accelerator.save_state(_UpperCAmelCase) if args.with_tracking: accelerator.end_training() def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument('--data_dir' , required=_UpperCAmelCase , help='The data folder on disk.') parser.add_argument('--fp16' , action='store_true' , help='If passed, will use FP16 training.') parser.add_argument( '--mixed_precision' , type=_UpperCAmelCase , default=_UpperCAmelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.') parser.add_argument( '--checkpointing_steps' , type=_UpperCAmelCase , default=_UpperCAmelCase , help='Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.' , ) parser.add_argument( '--output_dir' , type=_UpperCAmelCase , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--resume_from_checkpoint' , type=_UpperCAmelCase , default=_UpperCAmelCase , help='If the training should continue from a checkpoint folder.' , ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=_UpperCAmelCase , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) SCREAMING_SNAKE_CASE = parser.parse_args() SCREAMING_SNAKE_CASE = {'lr': 3e-2, 'num_epochs': 3, 'seed': 42, 'batch_size': 64, 'image_size': 224} training_function(_UpperCAmelCase , _UpperCAmelCase) if __name__ == "__main__": main()
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
# limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class _snake_case ( A__ ): def __init__( self , a , a) -> str: super().__init__() self.register_modules(unet=a , scheduler=a) @torch.no_grad() def __call__( self , a = 1 , a = None , a = 50 , a = "pil" , a = True , **a , ) -> Union[ImagePipelineOutput, Tuple]: SCREAMING_SNAKE_CASE = torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=a , ) SCREAMING_SNAKE_CASE = image.to(self.device) # set step values self.scheduler.set_timesteps(a) for t in self.progress_bar(self.scheduler.timesteps): # 1. predict noise model_output SCREAMING_SNAKE_CASE = self.unet(a , a).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 SCREAMING_SNAKE_CASE = self.scheduler.step(a , a , a).prev_sample SCREAMING_SNAKE_CASE = (image / 2 + 0.5).clamp(0 , 1) SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE = self.numpy_to_pil(a) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=a), "This is a local test"
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embeddings_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = len(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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.num_labels) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) SCREAMING_SNAKE_CASE = model(a) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(a) , expected_num_stages + 1) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) 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([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class _snake_case ( A__ ): _lowercase : Optional[torch.FloatTensor] = None _lowercase : torch.FloatTensor = None _lowercase : Optional[Tuple[torch.FloatTensor]] = None _lowercase : Optional[Tuple[torch.FloatTensor]] = None class _snake_case ( A__ ): def __init__( self , a=1 , a=0 , a=2 , a=512 , a="cls" , a=False , a=True , **a , ) -> Dict: super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a) SCREAMING_SNAKE_CASE = project_dim SCREAMING_SNAKE_CASE = pooler_fn SCREAMING_SNAKE_CASE = learn_encoder SCREAMING_SNAKE_CASE = use_attention_mask class _snake_case ( A__ ): _lowercase : Any = [R'''pooler''', R'''logit_scale'''] _lowercase : Any = [R'''position_ids''', R'''predictions.decoder.bias'''] _lowercase : str = '''roberta''' _lowercase : Tuple = RobertaSeriesConfig def __init__( self , a) -> Union[str, Any]: super().__init__(a) SCREAMING_SNAKE_CASE = XLMRobertaModel(a) SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim) SCREAMING_SNAKE_CASE = getattr(a , 'has_pre_transformation' , a) if self.has_pre_transformation: SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim) SCREAMING_SNAKE_CASE = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps) self.post_init() def SCREAMING_SNAKE_CASE__ ( self , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , ) -> Tuple: SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE = self.base_model( input_ids=a , attention_mask=a , token_type_ids=a , position_ids=a , head_mask=a , inputs_embeds=a , encoder_hidden_states=a , encoder_attention_mask=a , output_attentions=a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=a , ) if self.has_pre_transformation: SCREAMING_SNAKE_CASE = outputs['hidden_states'][-2] SCREAMING_SNAKE_CASE = self.pre_LN(a) SCREAMING_SNAKE_CASE = self.transformation_pre(a) return TransformationModelOutput( projection_state=a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: SCREAMING_SNAKE_CASE = self.transformation(outputs.last_hidden_state) return TransformationModelOutput( projection_state=a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
import collections import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Union[str, Any] = '▁' a_ : List[str] = {'vocab_file': 'prophetnet.tokenizer'} a_ : int = { 'vocab_file': { 'microsoft/xprophetnet-large-wiki100-cased': ( 'https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/prophetnet.tokenizer' ), } } a_ : Tuple = { 'microsoft/xprophetnet-large-wiki100-cased': {'do_lower_case': False}, } a_ : Dict = { 'microsoft/xprophetnet-large-wiki100-cased': 5_12, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = collections.OrderedDict() with open(_UpperCAmelCase , 'r' , encoding='utf-8') as reader: SCREAMING_SNAKE_CASE = reader.readlines() for index, token in enumerate(_UpperCAmelCase): SCREAMING_SNAKE_CASE = token.rstrip('\n') SCREAMING_SNAKE_CASE = index return vocab class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : str = PRETRAINED_VOCAB_FILES_MAP _lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : str = ['''input_ids''', '''attention_mask'''] def __init__( self , a , a="[SEP]" , a="[SEP]" , a="[SEP]" , a="[UNK]" , a="[PAD]" , a="[CLS]" , a="[MASK]" , a = None , **a , ) -> None: SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=a , eos_token=a , sep_token=a , unk_token=a , pad_token=a , cls_token=a , mask_token=a , sp_model_kwargs=self.sp_model_kwargs , **a , ) try: import sentencepiece as spm except ImportError: logger.warning( 'You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece' ' pip install sentencepiece') raise SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(a)) SCREAMING_SNAKE_CASE = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # put special tokens and [unused] tokens into the vocab SCREAMING_SNAKE_CASE = {'[PAD]': 0, '[CLS]': 1, '[SEP]': 2, '[UNK]': 3, '[MASK]': 4} for i in range(10): SCREAMING_SNAKE_CASE = f'''[unused{i}]''' SCREAMING_SNAKE_CASE = 5 + i # The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE = 12 SCREAMING_SNAKE_CASE = {v: k for k, v in self.fairseq_tokens_to_ids.items()} for k in self.fairseq_tokens_to_ids.keys(): self.unique_no_split_tokens.append(a) def __getstate__( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.__dict__.copy() SCREAMING_SNAKE_CASE = None return state def __setstate__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = d try: import sentencepiece as spm except ImportError: logger.warning( 'You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece' ' pip install sentencepiece') raise # for backward compatibility if not hasattr(self , 'sp_model_kwargs'): SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return ([0] * len(a)) + [1] return ([0] * len(a)) + [1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return len(token_ids_a + sep) * [0] return len(token_ids_a + sep + sep + token_ids_a + sep) * [0] @property def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return len(self.sp_model) + self.fairseq_offset def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = {self.convert_ids_to_tokens(a): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def SCREAMING_SNAKE_CASE__ ( self , a) -> str: return self.sp_model.encode(a , out_type=a) def SCREAMING_SNAKE_CASE__ ( self , a) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE = self.sp_model.PieceToId(a) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def SCREAMING_SNAKE_CASE__ ( self , a) -> Union[str, Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def SCREAMING_SNAKE_CASE__ ( self , a) -> Dict: SCREAMING_SNAKE_CASE = ''.join(a).replace(a , ' ').strip() return out_string def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: 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']) if os.path.abspath(self.vocab_file) != os.path.abspath(a) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , a) elif not os.path.isfile(self.vocab_file): with open(a , 'wb') as fi: SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(a) return (out_vocab_file,) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: if token_ids_a is None: return token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] return token_ids_a + sep + token_ids_a + sep
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class _snake_case : def __init__( self , a , a , a = True , a = False) -> Tuple: SCREAMING_SNAKE_CASE = scheduler SCREAMING_SNAKE_CASE = optimizers if isinstance(a , (list, tuple)) else [optimizers] SCREAMING_SNAKE_CASE = split_batches SCREAMING_SNAKE_CASE = step_with_optimizer SCREAMING_SNAKE_CASE = GradientState() def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[Any]: if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*a , **a) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*a , **a) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step SCREAMING_SNAKE_CASE = AcceleratorState().num_processes for _ in range(a): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps'): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*a , **a) else: self.scheduler.step(*a , **a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: return self.scheduler.get_last_lr() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: return self.scheduler.state_dict() def SCREAMING_SNAKE_CASE__ ( self , a) -> List[Any]: self.scheduler.load_state_dict(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return self.scheduler.get_lr() def SCREAMING_SNAKE_CASE__ ( self , *a , **a) -> List[Any]: return self.scheduler.print_lr(*a , **a)
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available a_ : List[Any] = { 'configuration_ernie': ['ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieConfig', 'ErnieOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = [ 'ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ErnieForCausalLM', 'ErnieForMaskedLM', 'ErnieForMultipleChoice', 'ErnieForNextSentencePrediction', 'ErnieForPreTraining', 'ErnieForQuestionAnswering', 'ErnieForSequenceClassification', 'ErnieForTokenClassification', 'ErnieModel', 'ErniePreTrainedModel', ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys a_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a_ : str = logging.get_logger(__name__) a_ : Optional[int] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : Tuple = { 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } a_ : Any = { 'gpt-neox-20b': 20_48, } class _snake_case ( A__ ): _lowercase : str = VOCAB_FILES_NAMES _lowercase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _lowercase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : List[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self , a=None , a=None , a=None , a="<|endoftext|>" , a="<|endoftext|>" , a="<|endoftext|>" , a=False , **a , ) -> Tuple: super().__init__( a , a , tokenizer_file=a , unk_token=a , bos_token=a , eos_token=a , add_prefix_space=a , **a , ) SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('add_prefix_space' , a) != add_prefix_space: SCREAMING_SNAKE_CASE = getattr(a , pre_tok_state.pop('type')) SCREAMING_SNAKE_CASE = add_prefix_space SCREAMING_SNAKE_CASE = pre_tok_class(**a) SCREAMING_SNAKE_CASE = add_prefix_space def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a) def SCREAMING_SNAKE_CASE__ ( self , a) -> List[int]: SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a , add_special_tokens=a) + [self.eos_token_id]) if len(a) > self.model_max_length: SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] return input_ids
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ : List[Any] = { 'configuration_groupvit': [ 'GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GroupViTConfig', 'GroupViTOnnxConfig', 'GroupViTTextConfig', 'GroupViTVisionConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = [ 'GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GroupViTModel', 'GroupViTPreTrainedModel', 'GroupViTTextModel', 'GroupViTVisionModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = [ '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 a_ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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_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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=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()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: 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_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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample 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_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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class _snake_case ( A__ ): _lowercase : Any = (DPMSolverSDEScheduler,) _lowercase : Any = 10 def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[int]: SCREAMING_SNAKE_CASE = { 'num_train_timesteps': 1100, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_seed': 0, } config.update(**a) return config def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] , [0.00_02, 0.0_02, 0.02]): self.check_over_configs(beta_start=a , beta_end=a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**a) scheduler.set_timesteps(self.num_inference_steps) SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE = sample.to(a) for i, t in enumerate(scheduler.timesteps): SCREAMING_SNAKE_CASE = scheduler.scale_model_input(a , a) SCREAMING_SNAKE_CASE = model(a , a) SCREAMING_SNAKE_CASE = scheduler.step(a , a , a) SCREAMING_SNAKE_CASE = output.prev_sample SCREAMING_SNAKE_CASE = torch.sum(torch.abs(a)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875) < 1E-2 assert abs(result_mean.item() - 0.21_78_70_59_64_56_52_77) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406) < 1E-2 assert abs(result_mean.item() - 0.2_23_42_90_68_92_29_96_52) < 1E-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562) < 1E-2 assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config(prediction_type='v_prediction') SCREAMING_SNAKE_CASE = scheduler_class(**a) scheduler.set_timesteps(self.num_inference_steps) SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE = sample.to(a) for i, t in enumerate(scheduler.timesteps): SCREAMING_SNAKE_CASE = scheduler.scale_model_input(a , a) SCREAMING_SNAKE_CASE = model(a , a) SCREAMING_SNAKE_CASE = scheduler.step(a , a , a) SCREAMING_SNAKE_CASE = output.prev_sample SCREAMING_SNAKE_CASE = torch.sum(torch.abs(a)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453) < 1E-2 assert abs(result_mean.item() - 0.1_62_26_28_90_14_81_62_84) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703) < 1E-2 assert abs(result_mean.item() - 0.1_66_88_32_60_01_16_72_97) < 1E-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125) < 1E-2 assert abs(result_mean.item() - 0.15_60_53_06_62_53_66_21) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**a) scheduler.set_timesteps(self.num_inference_steps , device=a) SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter.to(a) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE = scheduler.scale_model_input(a , a) SCREAMING_SNAKE_CASE = model(a , a) SCREAMING_SNAKE_CASE = scheduler.step(a , a , a) SCREAMING_SNAKE_CASE = output.prev_sample SCREAMING_SNAKE_CASE = torch.sum(torch.abs(a)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938) < 1E-2 assert abs(result_mean.item() - 0.2_18_05_93_46_07_98_26_35) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312) < 1E-2 assert abs(result_mean.item() - 0.2_23_42_90_83_82_41_57_71) < 1E-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562) < 1E-2 assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26) < 1E-3 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.scheduler_classes[0] SCREAMING_SNAKE_CASE = self.get_scheduler_config() SCREAMING_SNAKE_CASE = scheduler_class(**a , use_karras_sigmas=a) scheduler.set_timesteps(self.num_inference_steps , device=a) SCREAMING_SNAKE_CASE = self.dummy_model() SCREAMING_SNAKE_CASE = self.dummy_sample_deter.to(a) * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE = sample.to(a) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE = scheduler.scale_model_input(a , a) SCREAMING_SNAKE_CASE = model(a , a) SCREAMING_SNAKE_CASE = scheduler.step(a , a , a) SCREAMING_SNAKE_CASE = output.prev_sample SCREAMING_SNAKE_CASE = torch.sum(torch.abs(a)) SCREAMING_SNAKE_CASE = torch.mean(torch.abs(a)) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188) < 1E-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125) < 1E-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11) < 1E-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672) < 1E-2 assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11) < 1E-2
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class _snake_case : def __init__( self , a , a=13 , a=10 , a=3 , a=2 , a=2 , a=2 , a=True , a=True , a=32 , a=5 , a=4 , a=37 , a="gelu" , a=0.1 , a=0.1 , a=10 , a=0.02 , a=0.9 , a=None , ) -> Any: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = patch_size SCREAMING_SNAKE_CASE = tubelet_size SCREAMING_SNAKE_CASE = num_frames 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 = mask_ratio SCREAMING_SNAKE_CASE = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos SCREAMING_SNAKE_CASE = int(mask_ratio * self.seq_length) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = floats_tensor( [self.batch_size, self.num_frames, 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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Tuple: SCREAMING_SNAKE_CASE = VideoMAEModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Tuple: SCREAMING_SNAKE_CASE = VideoMAEForPreTraining(a) model.to(a) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch SCREAMING_SNAKE_CASE = torch.ones((self.num_masks,)) SCREAMING_SNAKE_CASE = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0))]) SCREAMING_SNAKE_CASE = mask.expand(self.batch_size , -1).bool() SCREAMING_SNAKE_CASE = model(a , a) # model only returns predictions for masked patches SCREAMING_SNAKE_CASE = mask.sum().item() SCREAMING_SNAKE_CASE = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> int: 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_torch class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : List[str] = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) _lowercase : str = ( {'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification} if is_torch_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Optional[Any] = False _lowercase : int = False _lowercase : Optional[int] = False def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = VideoMAEModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> List[Any]: SCREAMING_SNAKE_CASE = copy.deepcopy(a) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch SCREAMING_SNAKE_CASE = torch.ones((self.model_tester.num_masks,)) SCREAMING_SNAKE_CASE = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0))]) SCREAMING_SNAKE_CASE = mask.expand(self.model_tester.batch_size , -1).bool() SCREAMING_SNAKE_CASE = bool_masked_pos.to(a) if return_labels: if model_class in [ *get_values(a), ]: SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason='VideoMAE does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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() , (nn.Module)) SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear)) def SCREAMING_SNAKE_CASE__ ( self) -> Any: 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.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ['pixel_values'] self.assertListEqual(arg_names[:1] , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = VideoMAEModel.from_pretrained(a) self.assertIsNotNone(a) def SCREAMING_SNAKE_CASE__ ( self) -> Any: if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = self.model_tester.seq_length - self.model_tester.num_masks SCREAMING_SNAKE_CASE = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.attentions self.assertEqual(len(a) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.attentions self.assertEqual(len(a) , self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) SCREAMING_SNAKE_CASE = len(a) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) self.assertEqual(out_len + 1 , len(a)) SCREAMING_SNAKE_CASE = outputs.attentions self.assertEqual(len(a) , self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def SCREAMING_SNAKE_CASE__ ( self) -> Any: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) model.to(a) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(a) , a) SCREAMING_SNAKE_CASE = self.model_tester.seq_length - self.model_tester.num_masks SCREAMING_SNAKE_CASE = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) 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 = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.') def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: pass def lowerCamelCase__ (): """simple docstring""" SCREAMING_SNAKE_CASE = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset') SCREAMING_SNAKE_CASE = np.load(_UpperCAmelCase) return list(_UpperCAmelCase) @require_torch @require_vision class _snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = VideoMAEForVideoClassification.from_pretrained('MCG-NJU/videomae-base-finetuned-kinetics').to( a) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_video() SCREAMING_SNAKE_CASE = image_processor(a , return_tensors='pt').to(a) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 400)) self.assertEqual(outputs.logits.shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.36_69, -0.06_88, -0.24_21]).to(a) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a , atol=1E-4)) @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short').to(a) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_video() SCREAMING_SNAKE_CASE = image_processor(a , return_tensors='pt').to(a) # add boolean mask, indicating which patches to mask SCREAMING_SNAKE_CASE = hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos' , filename='bool_masked_pos.pt') SCREAMING_SNAKE_CASE = torch.load(a) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**a) # verify the logits SCREAMING_SNAKE_CASE = torch.Size([1, 1408, 1536]) SCREAMING_SNAKE_CASE = torch.tensor( [[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]] , device=a) self.assertEqual(outputs.logits.shape , a) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , a , atol=1E-4)) # verify the loss (`config.norm_pix_loss` = `True`) SCREAMING_SNAKE_CASE = torch.tensor([0.51_42] , device=a) self.assertTrue(torch.allclose(outputs.loss , a , atol=1E-4)) # verify the loss (`config.norm_pix_loss` = `False`) SCREAMING_SNAKE_CASE = VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short' , norm_pix_loss=a).to( a) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**a) SCREAMING_SNAKE_CASE = torch.tensor(torch.tensor([0.64_69]) , device=a) self.assertTrue(torch.allclose(outputs.loss , a , atol=1E-4))
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = None if token is not None: SCREAMING_SNAKE_CASE = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} SCREAMING_SNAKE_CASE = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' SCREAMING_SNAKE_CASE = requests.get(_UpperCAmelCase , headers=_UpperCAmelCase).json() SCREAMING_SNAKE_CASE = {} try: job_links.update({job['name']: job['html_url'] for job in result['jobs']}) SCREAMING_SNAKE_CASE = math.ceil((result['total_count'] - 100) / 100) for i in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE = requests.get(url + F'''&page={i + 2}''' , headers=_UpperCAmelCase).json() job_links.update({job['name']: job['html_url'] for job in result['jobs']}) return job_links except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''') return {} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = None if token is not None: SCREAMING_SNAKE_CASE = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} SCREAMING_SNAKE_CASE = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' SCREAMING_SNAKE_CASE = requests.get(_UpperCAmelCase , headers=_UpperCAmelCase).json() SCREAMING_SNAKE_CASE = {} try: artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']}) SCREAMING_SNAKE_CASE = math.ceil((result['total_count'] - 100) / 100) for i in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE = requests.get(url + F'''&page={i + 2}''' , headers=_UpperCAmelCase).json() artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']}) return artifacts except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''') return {} def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = None if token is not None: SCREAMING_SNAKE_CASE = {'Accept': 'application/vnd.github+json', 'Authorization': F'''Bearer {token}'''} SCREAMING_SNAKE_CASE = requests.get(_UpperCAmelCase , headers=_UpperCAmelCase , allow_redirects=_UpperCAmelCase) SCREAMING_SNAKE_CASE = result.headers['Location'] SCREAMING_SNAKE_CASE = requests.get(_UpperCAmelCase , allow_redirects=_UpperCAmelCase) SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , F'''{artifact_name}.zip''') with open(_UpperCAmelCase , 'wb') as fp: fp.write(response.content) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = None with zipfile.ZipFile(_UpperCAmelCase) as z: for filename in z.namelist(): if not os.path.isdir(_UpperCAmelCase): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(_UpperCAmelCase) as f: for line in f: SCREAMING_SNAKE_CASE = line.decode('UTF-8').strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs SCREAMING_SNAKE_CASE = line[: line.index(': ')] SCREAMING_SNAKE_CASE = line[line.index(': ') + len(': ') :] errors.append([error_line, error]) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith('FAILED '): # `test` is the test method that failed SCREAMING_SNAKE_CASE = line[len('FAILED ') :] failed_tests.append(_UpperCAmelCase) elif filename == "job_name.txt": SCREAMING_SNAKE_CASE = line if len(_UpperCAmelCase) != len(_UpperCAmelCase): raise ValueError( F'''`errors` and `failed_tests` should have the same number of elements. Got {len(_UpperCAmelCase)} for `errors` ''' F'''and {len(_UpperCAmelCase)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' ' problem.') SCREAMING_SNAKE_CASE = None if job_name and job_links: SCREAMING_SNAKE_CASE = job_links.get(_UpperCAmelCase , _UpperCAmelCase) # A list with elements of the form (line of error, error, failed test) SCREAMING_SNAKE_CASE = [x + [y] + [job_link] for x, y in zip(_UpperCAmelCase , _UpperCAmelCase)] return result def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [os.path.join(_UpperCAmelCase , _UpperCAmelCase) for p in os.listdir(_UpperCAmelCase) if p.endswith('.zip')] for p in paths: errors.extend(get_errors_from_single_artifact(_UpperCAmelCase , job_links=_UpperCAmelCase)) return errors def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = Counter() counter.update([x[1] for x in logs]) SCREAMING_SNAKE_CASE = counter.most_common() SCREAMING_SNAKE_CASE = {} for error, count in counts: if error_filter is None or error not in error_filter: SCREAMING_SNAKE_CASE = {'count': count, 'failed_tests': [(x[2], x[0]) for x in logs if x[1] == error]} SCREAMING_SNAKE_CASE = dict(sorted(r.items() , key=lambda _UpperCAmelCase: item[1]["count"] , reverse=_UpperCAmelCase)) return r def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = test.split('::')[0] if test.startswith('tests/models/'): SCREAMING_SNAKE_CASE = test.split('/')[2] else: SCREAMING_SNAKE_CASE = None return test def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None): SCREAMING_SNAKE_CASE = [(x[0], x[1], get_model(x[2])) for x in logs] SCREAMING_SNAKE_CASE = [x for x in logs if x[2] is not None] SCREAMING_SNAKE_CASE = {x[2] for x in logs} SCREAMING_SNAKE_CASE = {} for test in tests: SCREAMING_SNAKE_CASE = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test]) SCREAMING_SNAKE_CASE = counter.most_common() SCREAMING_SNAKE_CASE = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} SCREAMING_SNAKE_CASE = sum(error_counts.values()) if n_errors > 0: SCREAMING_SNAKE_CASE = {'count': n_errors, 'errors': error_counts} SCREAMING_SNAKE_CASE = dict(sorted(r.items() , key=lambda _UpperCAmelCase: item[1]["count"] , reverse=_UpperCAmelCase)) return r def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '| no. | error | status |' SCREAMING_SNAKE_CASE = '|-:|:-|:-|' SCREAMING_SNAKE_CASE = [header, sep] for error in reduced_by_error: SCREAMING_SNAKE_CASE = reduced_by_error[error]['count'] SCREAMING_SNAKE_CASE = F'''| {count} | {error[:100]} | |''' lines.append(_UpperCAmelCase) return "\n".join(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = '| model | no. of errors | major error | count |' SCREAMING_SNAKE_CASE = '|-:|-:|-:|-:|' SCREAMING_SNAKE_CASE = [header, sep] for model in reduced_by_model: SCREAMING_SNAKE_CASE = reduced_by_model[model]['count'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = list(reduced_by_model[model]['errors'].items())[0] SCREAMING_SNAKE_CASE = F'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(_UpperCAmelCase) return "\n".join(_UpperCAmelCase) if __name__ == "__main__": a_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') a_ : int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) a_ : Optional[int] = get_job_links(args.workflow_run_id, token=args.token) a_ : List[Any] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: a_ : int = k.find(' / ') a_ : List[Any] = k[index + len(' / ') :] a_ : str = v with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) a_ : Any = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) a_ : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error a_ : List[Any] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors a_ : List[Any] = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) a_ : Union[str, Any] = reduce_by_error(errors) a_ : List[str] = reduce_by_model(errors) a_ : List[Any] = make_github_table(reduced_by_error) a_ : Any = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa) with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa)
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef a_ : List[Any] = ( 'This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ' 'library. You can have a look at this example script for pointers: ' 'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py' ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): warnings.warn(_UpperCAmelCase , _UpperCAmelCase) requires_backends(_UpperCAmelCase , 'sklearn') return (preds == labels).mean() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): warnings.warn(_UpperCAmelCase , _UpperCAmelCase) requires_backends(_UpperCAmelCase , 'sklearn') SCREAMING_SNAKE_CASE = simple_accuracy(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = fa_score(y_true=_UpperCAmelCase , y_pred=_UpperCAmelCase) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): warnings.warn(_UpperCAmelCase , _UpperCAmelCase) requires_backends(_UpperCAmelCase , 'sklearn') SCREAMING_SNAKE_CASE = pearsonr(_UpperCAmelCase , _UpperCAmelCase)[0] SCREAMING_SNAKE_CASE = spearmanr(_UpperCAmelCase , _UpperCAmelCase)[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): warnings.warn(_UpperCAmelCase , _UpperCAmelCase) requires_backends(_UpperCAmelCase , 'sklearn') assert len(_UpperCAmelCase) == len(_UpperCAmelCase), F'''Predictions and labels have mismatched lengths {len(_UpperCAmelCase)} and {len(_UpperCAmelCase)}''' if task_name == "cola": return {"mcc": matthews_corrcoef(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "sst-2": return {"acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "mrpc": return acc_and_fa(_UpperCAmelCase , _UpperCAmelCase) elif task_name == "sts-b": return pearson_and_spearman(_UpperCAmelCase , _UpperCAmelCase) elif task_name == "qqp": return acc_and_fa(_UpperCAmelCase , _UpperCAmelCase) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "qnli": return {"acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "rte": return {"acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "wnli": return {"acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} elif task_name == "hans": return {"acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} else: raise KeyError(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): warnings.warn(_UpperCAmelCase , _UpperCAmelCase) requires_backends(_UpperCAmelCase , 'sklearn') if len(_UpperCAmelCase) != len(_UpperCAmelCase): raise ValueError(F'''Predictions and labels have mismatched lengths {len(_UpperCAmelCase)} and {len(_UpperCAmelCase)}''') if task_name == "xnli": return {"acc": simple_accuracy(_UpperCAmelCase , _UpperCAmelCase)} else: raise KeyError(_UpperCAmelCase)
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
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 a_ : str = get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=0): os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) with FSDP.state_dict_type( _UpperCAmelCase , 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(_UpperCAmelCase , _UpperCAmelCase) if accelerator.process_index == 0: logger.info(F'''Saving model to {output_model_file}''') torch.save(_UpperCAmelCase , _UpperCAmelCase) 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(_UpperCAmelCase , _UpperCAmelCase) logger.info(F'''Saving model to {output_model_file}''') torch.save(_UpperCAmelCase , _UpperCAmelCase) 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(_UpperCAmelCase , F'''{MODEL_NAME}_{model_index}''') os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) logger.info(F'''Saving model to {ckpt_dir}''') SCREAMING_SNAKE_CASE = {'model': state_dict} dist_cp.save_state_dict( state_dict=_UpperCAmelCase , storage_writer=dist_cp.FileSystemWriter(_UpperCAmelCase) , planner=DefaultSavePlanner() , ) logger.info(F'''Model saved to {ckpt_dir}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=0): accelerator.wait_for_everyone() with FSDP.state_dict_type( _UpperCAmelCase , 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(_UpperCAmelCase) != 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(_UpperCAmelCase , _UpperCAmelCase) logger.info(F'''Loading model from {input_model_file}''') SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase) 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(_UpperCAmelCase , _UpperCAmelCase) logger.info(F'''Loading model from {input_model_file}''') SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase) 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(_UpperCAmelCase , 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=_UpperCAmelCase , storage_reader=dist_cp.FileSystemReader(_UpperCAmelCase) , planner=DefaultLoadPlanner() , ) SCREAMING_SNAKE_CASE = state_dict['model'] logger.info(F'''Model loaded from {ckpt_dir}''') model.load_state_dict(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=0): os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) with FSDP.state_dict_type( _UpperCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config): SCREAMING_SNAKE_CASE = FSDP.optim_state_dict(_UpperCAmelCase , _UpperCAmelCase) 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(_UpperCAmelCase , _UpperCAmelCase) logger.info(F'''Saving Optimizer state to {output_optimizer_file}''') torch.save(_UpperCAmelCase , _UpperCAmelCase) logger.info(F'''Optimizer state saved in {output_optimizer_file}''') else: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , F'''{OPTIMIZER_NAME}_{optimizer_index}''') os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) logger.info(F'''Saving Optimizer state to {ckpt_dir}''') dist_cp.save_state_dict( state_dict={'optimizer': optim_state} , storage_writer=dist_cp.FileSystemWriter(_UpperCAmelCase) , planner=DefaultSavePlanner() , ) logger.info(F'''Optimizer state saved in {ckpt_dir}''') def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=0): accelerator.wait_for_everyone() with FSDP.state_dict_type( _UpperCAmelCase , 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(_UpperCAmelCase , _UpperCAmelCase) logger.info(F'''Loading Optimizer state from {input_optimizer_file}''') SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase) logger.info(F'''Optimizer state loaded from {input_optimizer_file}''') else: SCREAMING_SNAKE_CASE = ( os.path.join(_UpperCAmelCase , 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(_UpperCAmelCase) , ) SCREAMING_SNAKE_CASE = optim_state['optimizer'] logger.info(F'''Optimizer loaded from {ckpt_dir}''') SCREAMING_SNAKE_CASE = FSDP.optim_state_dict_to_load(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) optimizer.load_state_dict(_UpperCAmelCase)
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return [1] + ([0] * len(a)) + [1] return [1] + ([0] * len(a)) + [1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
import re from filelock import FileLock try: import nltk a_ : Union[str, Any] = True except (ImportError, ModuleNotFoundError): a_ : Optional[int] = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def lowerCamelCase__ (_UpperCAmelCase): re.sub('<n>' , '' , _UpperCAmelCase) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_UpperCAmelCase))
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) self.log(a) else: SCREAMING_SNAKE_CASE = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , a) return metrics def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_test_dataloader(a) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , 'predict') SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class _snake_case ( A__ ): def __init__( self , a , a=13 , a=7 , a=True , a=True , a=False , a=True , a=99 , a=32 , a=5 , a=4 , a=64 , a="gelu" , a=0.1 , a=0.1 , a=512 , a=16 , a=2 , a=0.02 , a=3 , a=4 , a=None , a=2 , a=2 , a=2 , a=2 , a=4 , a=1 , ) -> Tuple: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = use_token_type_ids SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = type_sequence_label_size SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = num_choices SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = q_groups SCREAMING_SNAKE_CASE = k_groups SCREAMING_SNAKE_CASE = v_groups SCREAMING_SNAKE_CASE = post_attention_groups SCREAMING_SNAKE_CASE = intermediate_groups SCREAMING_SNAKE_CASE = output_groups def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length]) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a) -> Tuple: SCREAMING_SNAKE_CASE = SqueezeBertModel(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , a) SCREAMING_SNAKE_CASE = model(a) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = SqueezeBertForMaskedLM(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a) -> Tuple: SCREAMING_SNAKE_CASE = SqueezeBertForQuestionAnswering(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , start_positions=a , end_positions=a) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a) -> List[str]: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = SqueezeBertForSequenceClassification(a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = SqueezeBertForTokenClassification(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = model(a , attention_mask=a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a) -> Dict: SCREAMING_SNAKE_CASE = self.num_choices SCREAMING_SNAKE_CASE = SqueezeBertForMultipleChoice(config=a) model.to(a) model.eval() SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() SCREAMING_SNAKE_CASE = model( a , attention_mask=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE) , (SCREAMING_SNAKE_CASE)) = config_and_inputs SCREAMING_SNAKE_CASE = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _snake_case ( A__ , A__ , unittest.TestCase ): _lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) _lowercase : List[str] = ( { '''feature-extraction''': SqueezeBertModel, '''fill-mask''': SqueezeBertForMaskedLM, '''question-answering''': SqueezeBertForQuestionAnswering, '''text-classification''': SqueezeBertForSequenceClassification, '''token-classification''': SqueezeBertForTokenClassification, '''zero-shot''': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) _lowercase : Any = False _lowercase : Dict = True _lowercase : Dict = False def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = SqueezeBertModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , dim=37) def SCREAMING_SNAKE_CASE__ ( self) -> Any: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = SqueezeBertModel.from_pretrained(a) self.assertIsNotNone(a) @require_sentencepiece @require_tokenizers @require_torch class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli') SCREAMING_SNAKE_CASE = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]]) SCREAMING_SNAKE_CASE = model(a)[0] SCREAMING_SNAKE_CASE = torch.Size((1, 3)) self.assertEqual(output.shape , a) SCREAMING_SNAKE_CASE = torch.tensor([[0.64_01, -0.03_49, -0.60_41]]) self.assertTrue(torch.allclose(a , a , atol=1E-4))
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available a_ : str = logging.getLogger(__name__) @dataclass class _snake_case : _lowercase : str _lowercase : List[str] _lowercase : Optional[List[str]] @dataclass class _snake_case : _lowercase : List[int] _lowercase : List[int] _lowercase : Optional[List[int]] = None _lowercase : Optional[List[int]] = None class _snake_case ( A__ ): _lowercase : List[Any] = '''train''' _lowercase : Dict = '''dev''' _lowercase : Union[str, Any] = '''test''' class _snake_case : @staticmethod def SCREAMING_SNAKE_CASE__ ( a , a) -> List[InputExample]: raise NotImplementedError @staticmethod def SCREAMING_SNAKE_CASE__ ( a) -> List[str]: raise NotImplementedError @staticmethod def SCREAMING_SNAKE_CASE__ ( a , a , a , a , a=False , a="[CLS]" , a=1 , a="[SEP]" , a=False , a=False , a=0 , a=0 , a=-100 , a=0 , a=True , ) -> List[InputFeatures]: SCREAMING_SNAKE_CASE = {label: i for i, label in enumerate(a)} SCREAMING_SNAKE_CASE = [] for ex_index, example in enumerate(a): if ex_index % 1_0000 == 0: logger.info('Writing example %d of %d' , a , len(a)) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for word, label in zip(example.words , example.labels): SCREAMING_SNAKE_CASE = tokenizer.tokenize(a) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(a) > 0: tokens.extend(a) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(a) - 1)) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. SCREAMING_SNAKE_CASE = tokenizer.num_special_tokens_to_add() if len(a) > max_seq_length - special_tokens_count: SCREAMING_SNAKE_CASE = tokens[: (max_seq_length - special_tokens_count)] SCREAMING_SNAKE_CASE = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] SCREAMING_SNAKE_CASE = [sequence_a_segment_id] * len(a) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: SCREAMING_SNAKE_CASE = [cls_token] + tokens SCREAMING_SNAKE_CASE = [pad_token_label_id] + label_ids SCREAMING_SNAKE_CASE = [cls_token_segment_id] + segment_ids SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(a) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. SCREAMING_SNAKE_CASE = [1 if mask_padding_with_zero else 0] * len(a) # Zero-pad up to the sequence length. SCREAMING_SNAKE_CASE = max_seq_length - len(a) if pad_on_left: SCREAMING_SNAKE_CASE = ([pad_token] * padding_length) + input_ids SCREAMING_SNAKE_CASE = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask SCREAMING_SNAKE_CASE = ([pad_token_segment_id] * padding_length) + segment_ids SCREAMING_SNAKE_CASE = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(a) == max_seq_length assert len(a) == max_seq_length assert len(a) == max_seq_length assert len(a) == max_seq_length if ex_index < 5: logger.info('*** Example ***') logger.info('guid: %s' , example.guid) logger.info('tokens: %s' , ' '.join([str(a) for x in tokens])) logger.info('input_ids: %s' , ' '.join([str(a) for x in input_ids])) logger.info('input_mask: %s' , ' '.join([str(a) for x in input_mask])) logger.info('segment_ids: %s' , ' '.join([str(a) for x in segment_ids])) logger.info('label_ids: %s' , ' '.join([str(a) for x in label_ids])) if "token_type_ids" not in tokenizer.model_input_names: SCREAMING_SNAKE_CASE = None features.append( InputFeatures( input_ids=a , attention_mask=a , token_type_ids=a , label_ids=a)) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class _snake_case ( A__ ): _lowercase : List[InputFeatures] _lowercase : int = nn.CrossEntropyLoss().ignore_index def __init__( self , a , a , a , a , a , a = None , a=False , a = Split.train , ) -> List[str]: # Load data features from cache or dataset file SCREAMING_SNAKE_CASE = os.path.join( a , 'cached_{}_{}_{}'.format(mode.value , tokenizer.__class__.__name__ , str(a)) , ) # 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 overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''') SCREAMING_SNAKE_CASE = torch.load(a) else: logger.info(f'''Creating features from dataset file at {data_dir}''') SCREAMING_SNAKE_CASE = token_classification_task.read_examples_from_file(a , a) # TODO clean up all this to leverage built-in features of tokenizers SCREAMING_SNAKE_CASE = token_classification_task.convert_examples_to_features( a , a , a , a , cls_token_at_end=bool(model_type in ['xlnet']) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['xlnet'] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=a , pad_on_left=bool(tokenizer.padding_side == 'left') , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''') torch.save(self.features , a) def __len__( self) -> Dict: return len(self.features) def __getitem__( self , a) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class _snake_case : _lowercase : List[InputFeatures] _lowercase : int = -1_00 def __init__( self , a , a , a , a , a , a = None , a=False , a = Split.train , ) -> Dict: SCREAMING_SNAKE_CASE = token_classification_task.read_examples_from_file(a , a) # TODO clean up all this to leverage built-in features of tokenizers SCREAMING_SNAKE_CASE = token_classification_task.convert_examples_to_features( a , a , a , a , cls_token_at_end=bool(model_type in ['xlnet']) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['xlnet'] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=a , pad_on_left=bool(tokenizer.padding_side == 'left') , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: SCREAMING_SNAKE_CASE = tf.data.Dataset.from_generator( a , ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa) , ( {'input_ids': tf.TensorShape([None]), 'attention_mask': tf.TensorShape([None])}, tf.TensorShape([None]), ) , ) else: SCREAMING_SNAKE_CASE = tf.data.Dataset.from_generator( a , ({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa) , ( { 'input_ids': tf.TensorShape([None]), 'attention_mask': tf.TensorShape([None]), 'token_type_ids': tf.TensorShape([None]), }, tf.TensorShape([None]), ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features))) return self.dataset def __len__( self) -> int: return len(self.features) def __getitem__( self , a) -> InputFeatures: return self.features[i]
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(matrix[0]) SCREAMING_SNAKE_CASE = min(_UpperCAmelCase , _UpperCAmelCase) for row in range(_UpperCAmelCase): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , _UpperCAmelCase): SCREAMING_SNAKE_CASE = matrix[col][row] / matrix[row][row] for i in range(_UpperCAmelCase , _UpperCAmelCase): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows SCREAMING_SNAKE_CASE = True for i in range(row + 1 , _UpperCAmelCase): if matrix[i][row] != 0: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = matrix[i], matrix[row] SCREAMING_SNAKE_CASE = False break if reduce: rank -= 1 for i in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 'https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png' SCREAMING_SNAKE_CASE = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase).raw).convert('RGB') return image def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [] # fmt: off # vision encoder rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding')) rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding')) rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight')) rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias')) rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight')) rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias')) for i in range(config.vision_config.num_hidden_layers): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''')) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''')) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''')) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''')) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''')) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',)) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''')) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''')) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''')) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''')) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''')) # QFormer rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.layernorm.weight')) rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.layernorm.bias')) # fmt: on return rename_keys def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = dct.pop(_UpperCAmelCase) SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for i in range(config.vision_config.num_hidden_layers): # read in original q and v biases SCREAMING_SNAKE_CASE = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''') SCREAMING_SNAKE_CASE = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''') # next, set bias in the state dict SCREAMING_SNAKE_CASE = torch.cat((q_bias, torch.zeros_like(_UpperCAmelCase , requires_grad=_UpperCAmelCase), v_bias)) SCREAMING_SNAKE_CASE = qkv_bias def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 364 if 'coco' in model_name else 224 SCREAMING_SNAKE_CASE = BlipaVisionConfig(image_size=_UpperCAmelCase).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: SCREAMING_SNAKE_CASE = OPTConfig.from_pretrained('facebook/opt-2.7b' , eos_token_id=_UpperCAmelCase).to_dict() elif "opt-6.7b" in model_name: SCREAMING_SNAKE_CASE = OPTConfig.from_pretrained('facebook/opt-6.7b' , eos_token_id=_UpperCAmelCase).to_dict() elif "t5-xl" in model_name: SCREAMING_SNAKE_CASE = TaConfig.from_pretrained('google/flan-t5-xl' , dense_act_fn='gelu' , bos_token_id=1).to_dict() elif "t5-xxl" in model_name: SCREAMING_SNAKE_CASE = TaConfig.from_pretrained('google/flan-t5-xxl' , dense_act_fn='gelu' , bos_token_id=1).to_dict() SCREAMING_SNAKE_CASE = BlipaConfig(vision_config=_UpperCAmelCase , text_config=_UpperCAmelCase) return config, image_size @torch.no_grad() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = ( AutoTokenizer.from_pretrained('facebook/opt-2.7b') if 'opt' in model_name else AutoTokenizer.from_pretrained('google/flan-t5-xl') ) SCREAMING_SNAKE_CASE = tokenizer('\n' , add_special_tokens=_UpperCAmelCase).input_ids[0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_blipa_config(_UpperCAmelCase , eos_token_id=_UpperCAmelCase) SCREAMING_SNAKE_CASE = BlipaForConditionalGeneration(_UpperCAmelCase).eval() SCREAMING_SNAKE_CASE = { 'blip2-opt-2.7b': ('blip2_opt', 'pretrain_opt2.7b'), 'blip2-opt-6.7b': ('blip2_opt', 'pretrain_opt6.7b'), 'blip2-opt-2.7b-coco': ('blip2_opt', 'caption_coco_opt2.7b'), 'blip2-opt-6.7b-coco': ('blip2_opt', 'caption_coco_opt6.7b'), 'blip2-flan-t5-xl': ('blip2_t5', 'pretrain_flant5xl'), 'blip2-flan-t5-xl-coco': ('blip2_t5', 'caption_coco_flant5xl'), 'blip2-flan-t5-xxl': ('blip2_t5', 'pretrain_flant5xxl'), } SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model_name_to_original[model_name] # load original model print('Loading original model...') SCREAMING_SNAKE_CASE = 'cuda' if torch.cuda.is_available() else 'cpu' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = load_model_and_preprocess( name=_UpperCAmelCase , model_type=_UpperCAmelCase , is_eval=_UpperCAmelCase , device=_UpperCAmelCase) original_model.eval() print('Done!') # update state dict keys SCREAMING_SNAKE_CASE = original_model.state_dict() SCREAMING_SNAKE_CASE = create_rename_keys(_UpperCAmelCase) for src, dest in rename_keys: rename_key(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) if key.startswith('Qformer.bert'): SCREAMING_SNAKE_CASE = key.replace('Qformer.bert' , 'qformer') if "attention.self" in key: SCREAMING_SNAKE_CASE = key.replace('self' , 'attention') if "opt_proj" in key: SCREAMING_SNAKE_CASE = key.replace('opt_proj' , 'language_projection') if "t5_proj" in key: SCREAMING_SNAKE_CASE = key.replace('t5_proj' , 'language_projection') if key.startswith('opt'): SCREAMING_SNAKE_CASE = key.replace('opt' , 'language') if key.startswith('t5'): SCREAMING_SNAKE_CASE = key.replace('t5' , 'language') SCREAMING_SNAKE_CASE = val # read in qv biases read_in_q_v_bias(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = hf_model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) assert len(_UpperCAmelCase) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] SCREAMING_SNAKE_CASE = load_demo_image() SCREAMING_SNAKE_CASE = vis_processors['eval'](_UpperCAmelCase).unsqueeze(0).to(_UpperCAmelCase) SCREAMING_SNAKE_CASE = tokenizer(['\n'] , return_tensors='pt').input_ids.to(_UpperCAmelCase) # create processor SCREAMING_SNAKE_CASE = BlipImageProcessor( size={'height': image_size, 'width': image_size} , image_mean=_UpperCAmelCase , image_std=_UpperCAmelCase) SCREAMING_SNAKE_CASE = BlipaProcessor(image_processor=_UpperCAmelCase , tokenizer=_UpperCAmelCase) SCREAMING_SNAKE_CASE = processor(images=_UpperCAmelCase , return_tensors='pt').pixel_values.to(_UpperCAmelCase) # make sure processor creates exact same pixel values assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase) original_model.to(_UpperCAmelCase) hf_model.to(_UpperCAmelCase) with torch.no_grad(): if "opt" in model_name: SCREAMING_SNAKE_CASE = original_model({'image': original_pixel_values, 'text_input': ['']}).logits SCREAMING_SNAKE_CASE = hf_model(_UpperCAmelCase , _UpperCAmelCase).logits else: SCREAMING_SNAKE_CASE = original_model( {'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']}).logits SCREAMING_SNAKE_CASE = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100) SCREAMING_SNAKE_CASE = hf_model(_UpperCAmelCase , _UpperCAmelCase , labels=_UpperCAmelCase).logits assert original_logits.shape == logits.shape print('First values of original logits:' , original_logits[0, :3, :3]) print('First values of HF logits:' , logits[0, :3, :3]) # assert values if model_name == "blip2-flan-t5-xl": SCREAMING_SNAKE_CASE = torch.tensor( [[-41.58_50, -4.44_40, -8.99_22], [-47.43_22, -5.91_43, -1.73_40]] , device=_UpperCAmelCase) assert torch.allclose(logits[0, :3, :3] , _UpperCAmelCase , atol=1e-4) elif model_name == "blip2-flan-t5-xl-coco": SCREAMING_SNAKE_CASE = torch.tensor( [[-57.01_09, -9.89_67, -12.62_80], [-68.65_78, -12.71_91, -10.50_65]] , device=_UpperCAmelCase) else: # cast to same type SCREAMING_SNAKE_CASE = logits.dtype assert torch.allclose(original_logits.to(_UpperCAmelCase) , _UpperCAmelCase , atol=1e-2) print('Looks ok!') print('Generating a caption...') SCREAMING_SNAKE_CASE = '' SCREAMING_SNAKE_CASE = tokenizer(_UpperCAmelCase , return_tensors='pt').input_ids.to(_UpperCAmelCase) SCREAMING_SNAKE_CASE = original_model.generate({'image': original_pixel_values}) SCREAMING_SNAKE_CASE = hf_model.generate( _UpperCAmelCase , _UpperCAmelCase , do_sample=_UpperCAmelCase , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('Original generation:' , _UpperCAmelCase) SCREAMING_SNAKE_CASE = input_ids.shape[1] SCREAMING_SNAKE_CASE = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=_UpperCAmelCase) SCREAMING_SNAKE_CASE = [text.strip() for text in output_text] print('HF generation:' , _UpperCAmelCase) if pytorch_dump_folder_path is not None: processor.save_pretrained(_UpperCAmelCase) hf_model.save_pretrained(_UpperCAmelCase) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''') hf_model.push_to_hub(F'''nielsr/{model_name}''') if __name__ == "__main__": a_ : Optional[Any] = argparse.ArgumentParser() a_ : str = [ 'blip2-opt-2.7b', 'blip2-opt-6.7b', 'blip2-opt-2.7b-coco', 'blip2-opt-6.7b-coco', 'blip2-flan-t5-xl', 'blip2-flan-t5-xl-coco', 'blip2-flan-t5-xxl', ] parser.add_argument( '--model_name', default='blip2-opt-2.7b', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) a_ : Optional[int] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): a_ : Any = 'pt' elif is_tf_available(): a_ : Dict = 'tf' else: a_ : Tuple = 'jax' class _snake_case ( A__ , unittest.TestCase ): _lowercase : List[str] = PerceiverTokenizer _lowercase : Dict = False def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() SCREAMING_SNAKE_CASE = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname) @cached_property def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: return PerceiverTokenizer.from_pretrained('deepmind/language-perceiver') def SCREAMING_SNAKE_CASE__ ( self , **a) -> PerceiverTokenizer: return self.tokenizer_class.from_pretrained(self.tmpdirname , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a=False , a=20 , a=5) -> Tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. SCREAMING_SNAKE_CASE = [] for i in range(len(a)): try: SCREAMING_SNAKE_CASE = tokenizer.decode([i] , clean_up_tokenization_spaces=a) except UnicodeDecodeError: pass toks.append((i, tok)) SCREAMING_SNAKE_CASE = list(filter(lambda a: re.match(R'^[ a-zA-Z]+$' , t[1]) , a)) SCREAMING_SNAKE_CASE = list(filter(lambda a: [t[0]] == tokenizer.encode(t[1] , add_special_tokens=a) , a)) if max_length is not None and len(a) > max_length: SCREAMING_SNAKE_CASE = toks[:max_length] if min_length is not None and len(a) < min_length and len(a) > 0: while len(a) < min_length: SCREAMING_SNAKE_CASE = toks + toks # toks_str = [t[1] for t in toks] SCREAMING_SNAKE_CASE = [t[0] for t in toks] # Ensure consistency SCREAMING_SNAKE_CASE = tokenizer.decode(a , clean_up_tokenization_spaces=a) if " " not in output_txt and len(a) > 1: SCREAMING_SNAKE_CASE = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=a) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=a) ) if with_prefix_space: SCREAMING_SNAKE_CASE = ' ' + output_txt SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) return output_txt, output_ids def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = 'Unicode €.' SCREAMING_SNAKE_CASE = tokenizer(a) SCREAMING_SNAKE_CASE = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded['input_ids'] , a) # decoding SCREAMING_SNAKE_CASE = tokenizer.decode(a) self.assertEqual(a , '[CLS]Unicode €.[SEP]') SCREAMING_SNAKE_CASE = tokenizer('e è é ê ë') SCREAMING_SNAKE_CASE = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded['input_ids'] , a) # decoding SCREAMING_SNAKE_CASE = tokenizer.decode(a) self.assertEqual(a , '[CLS]e è é ê ë[SEP]') # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë')) , '[CLS]e è é ê ë[SEP]') def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off SCREAMING_SNAKE_CASE = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on SCREAMING_SNAKE_CASE = tokenizer(a , padding=a , return_tensors=a) self.assertIsInstance(a , a) if FRAMEWORK != "jax": SCREAMING_SNAKE_CASE = list(batch.input_ids.numpy()[0]) else: SCREAMING_SNAKE_CASE = list(batch.input_ids.tolist()[0]) self.assertListEqual(a , a) self.assertEqual((2, 38) , batch.input_ids.shape) self.assertEqual((2, 38) , batch.attention_mask.shape) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] SCREAMING_SNAKE_CASE = tokenizer(a , padding=a , return_tensors=a) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , a) self.assertIn('attention_mask' , a) self.assertNotIn('decoder_input_ids' , a) self.assertNotIn('decoder_attention_mask' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer SCREAMING_SNAKE_CASE = [ 'Summary of the text.', 'Another summary.', ] SCREAMING_SNAKE_CASE = tokenizer( text_target=a , max_length=32 , padding='max_length' , truncation=a , return_tensors=a) self.assertEqual(32 , targets['input_ids'].shape[1]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: # safety check on max_len default value so we are sure the test works SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): self.assertNotEqual(tokenizer.model_max_length , 42) # Now let's start the test SCREAMING_SNAKE_CASE = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = ' He is very happy, UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) tokenizer.save_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(a) SCREAMING_SNAKE_CASE = after_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) shutil.rmtree(a) SCREAMING_SNAKE_CASE = self.get_tokenizers(model_max_length=42) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): # Isolate this from the other tests because we save additional tokens/etc SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = ' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam']) SCREAMING_SNAKE_CASE = tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token') tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens}) SCREAMING_SNAKE_CASE = tokenizer.encode(a , add_special_tokens=a) tokenizer.save_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(a) SCREAMING_SNAKE_CASE = after_tokenizer.encode(a , add_special_tokens=a) self.assertListEqual(a , a) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens) self.assertEqual(after_tokenizer.model_max_length , 42) SCREAMING_SNAKE_CASE = tokenizer.__class__.from_pretrained(a , model_max_length=43) self.assertEqual(tokenizer.model_max_length , 43) shutil.rmtree(a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(a) with open(os.path.join(a , 'special_tokens_map.json') , encoding='utf-8') as json_file: SCREAMING_SNAKE_CASE = json.load(a) with open(os.path.join(a , 'tokenizer_config.json') , encoding='utf-8') as json_file: SCREAMING_SNAKE_CASE = json.load(a) SCREAMING_SNAKE_CASE = [f'''<extra_id_{i}>''' for i in range(125)] SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [ 'an_additional_special_token' ] SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(a , 'special_tokens_map.json') , 'w' , encoding='utf-8') as outfile: json.dump(a , a) with open(os.path.join(a , 'tokenizer_config.json') , 'w' , encoding='utf-8') as outfile: json.dump(a , a) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained( a , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens) self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'])) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained SCREAMING_SNAKE_CASE = added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=a)] SCREAMING_SNAKE_CASE = tokenizer_class.from_pretrained( a , additional_special_tokens=a , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'])) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178]) , '�') def SCREAMING_SNAKE_CASE__ ( self) -> Any: pass def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Any: # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens SCREAMING_SNAKE_CASE = self.get_tokenizers(fast=a , do_lower_case=a) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}'''): SCREAMING_SNAKE_CASE = ['[CLS]', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '[SEP]'] SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_string(a) self.assertIsInstance(a , a)
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = F'''{sampling_rate}''' SCREAMING_SNAKE_CASE = '1' SCREAMING_SNAKE_CASE = 'f32le' SCREAMING_SNAKE_CASE = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(_UpperCAmelCase , stdin=subprocess.PIPE , stdout=subprocess.PIPE) as ffmpeg_process: SCREAMING_SNAKE_CASE = ffmpeg_process.communicate(_UpperCAmelCase) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename') from error SCREAMING_SNAKE_CASE = output_stream[0] SCREAMING_SNAKE_CASE = np.frombuffer(_UpperCAmelCase , np.floataa) if audio.shape[0] == 0: raise ValueError('Malformed soundfile') return audio def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = "f32le" , ): SCREAMING_SNAKE_CASE = F'''{sampling_rate}''' SCREAMING_SNAKE_CASE = '1' if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE = 4 else: raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''') SCREAMING_SNAKE_CASE = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE = 'alsa' SCREAMING_SNAKE_CASE = 'default' elif system == "Darwin": SCREAMING_SNAKE_CASE = 'avfoundation' SCREAMING_SNAKE_CASE = ':0' elif system == "Windows": SCREAMING_SNAKE_CASE = 'dshow' SCREAMING_SNAKE_CASE = 'default' SCREAMING_SNAKE_CASE = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] SCREAMING_SNAKE_CASE = int(round(sampling_rate * chunk_length_s)) * size_of_sample SCREAMING_SNAKE_CASE = _ffmpeg_stream(_UpperCAmelCase , _UpperCAmelCase) for item in iterator: yield item def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase = "f32le" , ): if stream_chunk_s is not None: SCREAMING_SNAKE_CASE = stream_chunk_s else: SCREAMING_SNAKE_CASE = chunk_length_s SCREAMING_SNAKE_CASE = ffmpeg_microphone(_UpperCAmelCase , _UpperCAmelCase , format_for_conversion=_UpperCAmelCase) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE = np.intaa SCREAMING_SNAKE_CASE = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE = np.floataa SCREAMING_SNAKE_CASE = 4 else: raise ValueError(F'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''') if stride_length_s is None: SCREAMING_SNAKE_CASE = chunk_length_s / 6 SCREAMING_SNAKE_CASE = int(round(sampling_rate * chunk_length_s)) * size_of_sample if isinstance(_UpperCAmelCase , (int, float)): SCREAMING_SNAKE_CASE = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE = int(round(sampling_rate * stride_length_s[0])) * size_of_sample SCREAMING_SNAKE_CASE = int(round(sampling_rate * stride_length_s[1])) * size_of_sample SCREAMING_SNAKE_CASE = datetime.datetime.now() SCREAMING_SNAKE_CASE = datetime.timedelta(seconds=_UpperCAmelCase) for item in chunk_bytes_iter(_UpperCAmelCase , _UpperCAmelCase , stride=(stride_left, stride_right) , stream=_UpperCAmelCase): # Put everything back in numpy scale SCREAMING_SNAKE_CASE = np.frombuffer(item['raw'] , dtype=_UpperCAmelCase) SCREAMING_SNAKE_CASE = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) SCREAMING_SNAKE_CASE = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = B'' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = stride if stride_left + stride_right >= chunk_len: raise ValueError( F'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}''') SCREAMING_SNAKE_CASE = 0 for raw in iterator: acc += raw if stream and len(_UpperCAmelCase) < chunk_len: SCREAMING_SNAKE_CASE = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(_UpperCAmelCase) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE = (_stride_left, stride_right) SCREAMING_SNAKE_CASE = {'raw': acc[:chunk_len], 'stride': stride} if stream: SCREAMING_SNAKE_CASE = False yield item SCREAMING_SNAKE_CASE = stride_left SCREAMING_SNAKE_CASE = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(_UpperCAmelCase) > stride_left: SCREAMING_SNAKE_CASE = {'raw': acc, 'stride': (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE = False yield item def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 2**24 # 16Mo try: with subprocess.Popen(_UpperCAmelCase , stdout=subprocess.PIPE , bufsize=_UpperCAmelCase) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE = ffmpeg_process.stdout.read(_UpperCAmelCase) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename') from error
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : List[str] = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = ['PoolFormerFeatureExtractor'] a_ : Optional[Any] = ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys a_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ('weight',) SCREAMING_SNAKE_CASE = torch.permute(_UpperCAmelCase , (0, 2, 1)) elif flax_key_tuple[-1] == "kernel" and ".".join(_UpperCAmelCase): # linear layer SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ('weight',) SCREAMING_SNAKE_CASE = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ('weight',) return flax_key_tuple, flax_tensor def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "metadata" in layer: SCREAMING_SNAKE_CASE = layer.split('metadata') SCREAMING_SNAKE_CASE = ''.join(split_layer[0])[:-1] SCREAMING_SNAKE_CASE = [tuple(('metadata' + split_layer[1]).split('/'))] elif "kvstore" in layer: SCREAMING_SNAKE_CASE = layer.split('kvstore') SCREAMING_SNAKE_CASE = ''.join(split_layer[0])[:-1] SCREAMING_SNAKE_CASE = [tuple(('kvstore' + split_layer[1]).split('/'))] else: SCREAMING_SNAKE_CASE = layer.split('/') SCREAMING_SNAKE_CASE = '/'.join(split_layer[:-1]) SCREAMING_SNAKE_CASE = (split_layer[-1],) if "kvstore/path" in layer: SCREAMING_SNAKE_CASE = F'''{switch_checkpoint_path}/{checkpoint_info[layer]}''' elif "kvstore/driver" in layer: SCREAMING_SNAKE_CASE = 'file' else: SCREAMING_SNAKE_CASE = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = rename_keys(_UpperCAmelCase) SCREAMING_SNAKE_CASE = {} for k, v in current_block.items(): SCREAMING_SNAKE_CASE = v SCREAMING_SNAKE_CASE = new_current_block torch.save(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = WEIGHTS_NAME): SCREAMING_SNAKE_CASE = convert_file_size_to_int(_UpperCAmelCase) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase) with gfile.GFile(switch_checkpoint_path + '/checkpoint' , 'rb') as fp: SCREAMING_SNAKE_CASE = serialization.msgpack_restore(fp.read())['optimizer']['target'] SCREAMING_SNAKE_CASE = flatten_dict(_UpperCAmelCase , sep='/') SCREAMING_SNAKE_CASE = {} for layer in checkpoint_info.keys(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_key_and_tensorstore_dict( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) if curr_real_layer_name in all_layers: SCREAMING_SNAKE_CASE = content else: SCREAMING_SNAKE_CASE = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file SCREAMING_SNAKE_CASE = ts.open(unflatten_dict(all_layers[key])).result().read().result() SCREAMING_SNAKE_CASE = torch.tensor(_UpperCAmelCase) SCREAMING_SNAKE_CASE = raw_weights.numel() * dtype_byte_size(raw_weights.dtype) # use the renaming pattern from the small conversion scripts SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = rename_base_flax_keys(tuple(key.split('/')) , _UpperCAmelCase) SCREAMING_SNAKE_CASE = '/'.join(_UpperCAmelCase) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: SCREAMING_SNAKE_CASE = os.path.join( _UpperCAmelCase , weights_name.replace('.bin' , F'''-{len(_UpperCAmelCase)+1:05d}-of-???.bin''')) rename_and_save_block(_UpperCAmelCase , _UpperCAmelCase) sharded_state_dicts.append(current_block.keys()) del current_block SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = raw_weights.to(getattr(_UpperCAmelCase , _UpperCAmelCase)) current_block_size += weight_size total_size += weight_size # Add the last block SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , weights_name.replace('.bin' , F'''-{len(_UpperCAmelCase)+1:05d}-of-???.bin''')) rename_and_save_block(_UpperCAmelCase , _UpperCAmelCase) sharded_state_dicts.append(current_block.keys()) # If we only have one shard, we return it if len(_UpperCAmelCase) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index SCREAMING_SNAKE_CASE = {} SCREAMING_SNAKE_CASE = {} for idx, shard in enumerate(_UpperCAmelCase): SCREAMING_SNAKE_CASE = weights_name.replace( '.bin' , F'''-{idx+1:05d}-of-{len(_UpperCAmelCase):05d}.bin''') # len(sharded_state_dicts):05d} SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , weights_name.replace('.bin' , F'''-{idx+1:05d}-of-???.bin''')) os.rename(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) SCREAMING_SNAKE_CASE = shard for key in shard: SCREAMING_SNAKE_CASE = shard_file # Add the metadata SCREAMING_SNAKE_CASE = {'total_size': total_size} SCREAMING_SNAKE_CASE = {'metadata': metadata, 'weight_map': weight_map} with open(os.path.join(_UpperCAmelCase , _UpperCAmelCase) , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) return metadata, index if __name__ == "__main__": a_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600', type=str, required=False, help='Path to a directory containing a folder per layer. Follows the original Google format.', ) parser.add_argument('--max_shard_size', default='10GB', required=False, help='Max shard size') parser.add_argument('--dtype', default='bfloat16', type=str, required=False, help='dtype of the saved model') parser.add_argument( '--pytorch_dump_folder_path', default='/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted', type=str, required=False, help='Path to the output pytorch model.', ) a_ : int = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def lowerCamelCase__ (): from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer SCREAMING_SNAKE_CASE = SwitchTransformersConfig.from_pretrained('google/switch-base-8') config.save_pretrained('/home/arthur_huggingface_co/transformers/switch_converted') SCREAMING_SNAKE_CASE = SwitchTransformersForConditionalGeneration.from_pretrained( '/home/arthur_huggingface_co/transformers/switch_converted' , device_map='auto') SCREAMING_SNAKE_CASE = TaTokenizer.from_pretrained('t5-small') SCREAMING_SNAKE_CASE = 'A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.' SCREAMING_SNAKE_CASE = tokenizer(_UpperCAmelCase , return_tensors='pt').input_ids SCREAMING_SNAKE_CASE = model.generate(_UpperCAmelCase , decoder_start_token_id=0) print(tokenizer.decode(out[0]))
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embeddings_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = len(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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.num_labels) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) SCREAMING_SNAKE_CASE = model(a) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(a) , expected_num_stages + 1) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) 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([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _snake_case ( A__ , unittest.TestCase ): _lowercase : List[Any] = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def SCREAMING_SNAKE_CASE__ ( self , a=0) -> Optional[Any]: SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 128, 128) , rng=random.Random(a)) SCREAMING_SNAKE_CASE = np.random.RandomState(a) SCREAMING_SNAKE_CASE = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider') pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs() SCREAMING_SNAKE_CASE = pipe(**a).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87]) assert np.abs(image_slice - expected_slice).max() < 1E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider') SCREAMING_SNAKE_CASE = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=a) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs() SCREAMING_SNAKE_CASE = pipe(**a).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider') SCREAMING_SNAKE_CASE = LMSDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=a) # warmup pass to apply optimizations SCREAMING_SNAKE_CASE = pipe(**self.get_dummy_inputs()) SCREAMING_SNAKE_CASE = self.get_dummy_inputs() SCREAMING_SNAKE_CASE = pipe(**a).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1 def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider') SCREAMING_SNAKE_CASE = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs() SCREAMING_SNAKE_CASE = pipe(**a).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider') SCREAMING_SNAKE_CASE = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs() SCREAMING_SNAKE_CASE = pipe(**a).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider') SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = self.get_dummy_inputs() SCREAMING_SNAKE_CASE = pipe(**a).images SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) SCREAMING_SNAKE_CASE = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class _snake_case ( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE__ ( self) -> Dict: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = ort.SessionOptions() SCREAMING_SNAKE_CASE = False return options def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg') SCREAMING_SNAKE_CASE = init_image.resize((768, 512)) # using the PNDM scheduler by default SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=a , feature_extractor=a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'A fantasy landscape, trending on artstation' SCREAMING_SNAKE_CASE = np.random.RandomState(0) SCREAMING_SNAKE_CASE = pipe( prompt=a , image=a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=a , output_type='np' , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) SCREAMING_SNAKE_CASE = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2E-2 def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg') SCREAMING_SNAKE_CASE = init_image.resize((768, 512)) SCREAMING_SNAKE_CASE = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx') SCREAMING_SNAKE_CASE = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=a , safety_checker=a , feature_extractor=a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=a) SCREAMING_SNAKE_CASE = 'A fantasy landscape, trending on artstation' SCREAMING_SNAKE_CASE = np.random.RandomState(0) SCREAMING_SNAKE_CASE = pipe( prompt=a , image=a , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=a , output_type='np' , ) SCREAMING_SNAKE_CASE = output.images SCREAMING_SNAKE_CASE = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) SCREAMING_SNAKE_CASE = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2E-2
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = None , _UpperCAmelCase = None): if start is None: SCREAMING_SNAKE_CASE = 0 if end is None: SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 if start >= end: return SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) slowsort(_UpperCAmelCase , mid + 1 , _UpperCAmelCase) if sequence[end] < sequence[mid]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(_UpperCAmelCase , _UpperCAmelCase , end - 1) if __name__ == "__main__": from doctest import testmod testmod()
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
import argparse import copy def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {} with open(_UpperCAmelCase) as f: for line in f: if line.split()[0] not in dict_of_neighbours: SCREAMING_SNAKE_CASE = [] _list.append([line.split()[1], line.split()[2]]) SCREAMING_SNAKE_CASE = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]]) if line.split()[1] not in dict_of_neighbours: SCREAMING_SNAKE_CASE = [] _list.append([line.split()[0], line.split()[2]]) SCREAMING_SNAKE_CASE = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]]) return dict_of_neighbours def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): with open(_UpperCAmelCase) as f: SCREAMING_SNAKE_CASE = f.read(1) SCREAMING_SNAKE_CASE = start_node SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = start_node SCREAMING_SNAKE_CASE = 0 while visiting not in first_solution: SCREAMING_SNAKE_CASE = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1]) < int(_UpperCAmelCase) and k[0] not in first_solution: SCREAMING_SNAKE_CASE = k[1] SCREAMING_SNAKE_CASE = k[0] first_solution.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE = distance_of_first_solution + int(_UpperCAmelCase) SCREAMING_SNAKE_CASE = best_node first_solution.append(_UpperCAmelCase) SCREAMING_SNAKE_CASE = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 SCREAMING_SNAKE_CASE = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1]) - 1_0000 ) return first_solution, distance_of_first_solution def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for n in solution[1:-1]: SCREAMING_SNAKE_CASE = solution.index(_UpperCAmelCase) for kn in solution[1:-1]: SCREAMING_SNAKE_CASE = solution.index(_UpperCAmelCase) if n == kn: continue SCREAMING_SNAKE_CASE = copy.deepcopy(_UpperCAmelCase) SCREAMING_SNAKE_CASE = kn SCREAMING_SNAKE_CASE = n SCREAMING_SNAKE_CASE = 0 for k in _tmp[:-1]: SCREAMING_SNAKE_CASE = _tmp[_tmp.index(_UpperCAmelCase) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: SCREAMING_SNAKE_CASE = distance + int(i[1]) _tmp.append(_UpperCAmelCase) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp) SCREAMING_SNAKE_CASE = len(neighborhood_of_solution[0]) - 1 neighborhood_of_solution.sort(key=lambda _UpperCAmelCase: x[index_of_last_item_in_the_list]) return neighborhood_of_solution def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = 1 SCREAMING_SNAKE_CASE = first_solution SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = distance_of_first_solution SCREAMING_SNAKE_CASE = solution while count <= iters: SCREAMING_SNAKE_CASE = find_neighborhood(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = neighborhood[index_of_best_solution] SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 SCREAMING_SNAKE_CASE = False while not found: SCREAMING_SNAKE_CASE = 0 while i < len(_UpperCAmelCase): if best_solution[i] != solution[i]: SCREAMING_SNAKE_CASE = best_solution[i] SCREAMING_SNAKE_CASE = solution[i] break SCREAMING_SNAKE_CASE = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node]) SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = best_solution[:-1] SCREAMING_SNAKE_CASE = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: SCREAMING_SNAKE_CASE = cost SCREAMING_SNAKE_CASE = solution else: SCREAMING_SNAKE_CASE = index_of_best_solution + 1 SCREAMING_SNAKE_CASE = neighborhood[index_of_best_solution] if len(_UpperCAmelCase) >= size: tabu_list.pop(0) SCREAMING_SNAKE_CASE = count + 1 return best_solution_ever, best_cost def lowerCamelCase__ (_UpperCAmelCase=None): SCREAMING_SNAKE_CASE = generate_neighbours(args.File) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_first_solution( args.File , _UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tabu_search( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , args.Iterations , args.Size , ) print(F'''Best solution: {best_sol}, with total distance: {best_cost}.''') if __name__ == "__main__": a_ : Optional[Any] = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , a , a=13 , a=3 , a=224 , a=30 , a=400 , a=True , a=None , a=True , a=[0.5, 0.5, 0.5] , a=[0.5, 0.5, 0.5] , ) -> Any: SCREAMING_SNAKE_CASE = size if 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_normalize SCREAMING_SNAKE_CASE = image_mean SCREAMING_SNAKE_CASE = image_std def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _snake_case ( A__ , unittest.TestCase ): _lowercase : Optional[Any] = ViTImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = EfficientFormerImageProcessorTester(self) @property def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return self.image_proc_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(a , 'image_mean')) self.assertTrue(hasattr(a , 'image_std')) self.assertTrue(hasattr(a , 'do_normalize')) self.assertTrue(hasattr(a , 'do_resize')) self.assertTrue(hasattr(a , 'size')) def SCREAMING_SNAKE_CASE__ ( self) -> str: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: # Initialize image_processor SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random PIL images SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_proc_tester , equal_resolution=a) for image in image_inputs: self.assertIsInstance(a , Image.Image) # Test not batched input SCREAMING_SNAKE_CASE = image_processor(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE = image_processor(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: # Initialize image_processor SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a) for image in image_inputs: self.assertIsInstance(a , np.ndarray) # Test not batched input SCREAMING_SNAKE_CASE = image_processor(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE = image_processor(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: # Initialize image_processor SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a) for image in image_inputs: self.assertIsInstance(a , torch.Tensor) # Test not batched input SCREAMING_SNAKE_CASE = image_processor(image_inputs[0] , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , ) # Test batched SCREAMING_SNAKE_CASE = image_processor(a , return_tensors='pt').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ) , )
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=False): try: SCREAMING_SNAKE_CASE = os.environ[key] except KeyError: # KEY isn't set, default to `default`. SCREAMING_SNAKE_CASE = default else: # KEY is set, convert it to True or False. try: SCREAMING_SNAKE_CASE = strtobool(_UpperCAmelCase) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'''If set, {key} must be yes or no.''') return _value a_ : str = parse_flag_from_env('RUN_SLOW', default=False) a_ : Optional[int] = parse_flag_from_env('RUN_REMOTE', default=False) a_ : Optional[int] = parse_flag_from_env('RUN_LOCAL', default=True) a_ : Union[str, Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a_ : Union[str, Any] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a_ : Dict = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a_ : Union[str, Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a_ : int = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a_ : Dict = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a_ : Optional[Any] = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a_ : List[str] = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def lowerCamelCase__ (_UpperCAmelCase): try: import faiss # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires faiss')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import regex # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires regex')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import elasticsearch # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires elasticsearch')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import sqlalchemy # noqa except ImportError: SCREAMING_SNAKE_CASE = unittest.skip('test requires sqlalchemy')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.TORCH_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires PyTorch')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.TF_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires TensorFlow')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.JAX_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires JAX')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not config.PIL_AVAILABLE: SCREAMING_SNAKE_CASE = unittest.skip('test requires Pillow')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import transformers # noqa F401 except ImportError: return unittest.skip('test requires transformers')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import tiktoken # noqa F401 except ImportError: return unittest.skip('test requires tiktoken')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import spacy # noqa F401 except ImportError: return unittest.skip('test requires spacy')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): def _require_spacy_model(_UpperCAmelCase): try: import spacy # noqa F401 spacy.load(_UpperCAmelCase) except ImportError: return unittest.skip('test requires spacy')(_UpperCAmelCase) except OSError: return unittest.skip('test requires spacy model \'{}\''.format(_UpperCAmelCase))(_UpperCAmelCase) else: return test_case return _require_spacy_model def lowerCamelCase__ (_UpperCAmelCase): try: import pyspark # noqa F401 except ImportError: return unittest.skip('test requires pyspark')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): try: import joblibspark # noqa F401 except ImportError: return unittest.skip('test requires joblibspark')(_UpperCAmelCase) else: return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_slow_tests or _run_slow_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test is slow')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_local_tests or _run_local_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test is local')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_packaged_tests or _run_packaged_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test is packaged')(_UpperCAmelCase) return test_case def lowerCamelCase__ (_UpperCAmelCase): if not _run_remote_tests or _run_remote_tests == 0: SCREAMING_SNAKE_CASE = unittest.skip('test requires remote')(_UpperCAmelCase) return test_case def lowerCamelCase__ (*_UpperCAmelCase): def decorate(cls): for name, fn in cls.__dict__.items(): if callable(_UpperCAmelCase) and name.startswith('test'): for decorator in decorators: SCREAMING_SNAKE_CASE = decorator(_UpperCAmelCase) setattr(cls , _UpperCAmelCase , _UpperCAmelCase) return cls return decorate class _snake_case ( A__ ): pass class _snake_case ( A__ ): _lowercase : Union[str, Any] = 0 _lowercase : List[Any] = 1 _lowercase : Optional[Any] = 2 @contextmanager def lowerCamelCase__ (_UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS , _UpperCAmelCase=1e-16): SCREAMING_SNAKE_CASE = requests.Session().request def timeout_request(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): # Change the url to an invalid url so that the connection hangs SCREAMING_SNAKE_CASE = 'https://10.255.255.1' if kwargs.get('timeout') is None: raise RequestWouldHangIndefinitelyError( F'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.''') SCREAMING_SNAKE_CASE = timeout try: return online_request(_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier SCREAMING_SNAKE_CASE = url SCREAMING_SNAKE_CASE = e.args[0] SCREAMING_SNAKE_CASE = (max_retry_error.args[0].replace('10.255.255.1' , F'''OfflineMock[{url}]'''),) SCREAMING_SNAKE_CASE = (max_retry_error,) raise def raise_connection_error(_UpperCAmelCase , _UpperCAmelCase , **_UpperCAmelCase): raise requests.ConnectionError('Offline mode is enabled.' , request=_UpperCAmelCase) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch('requests.Session.send' , _UpperCAmelCase): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch('requests.Session.request' , _UpperCAmelCase): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch('datasets.config.HF_DATASETS_OFFLINE' , _UpperCAmelCase): yield else: raise ValueError('Please use a value from the OfflineSimulationMode enum.') @contextmanager def lowerCamelCase__ (*_UpperCAmelCase , **_UpperCAmelCase): SCREAMING_SNAKE_CASE = str(Path().resolve()) with tempfile.TemporaryDirectory(*_UpperCAmelCase , **_UpperCAmelCase) as tmp_dir: try: os.chdir(_UpperCAmelCase) yield finally: os.chdir(_UpperCAmelCase) @contextmanager def lowerCamelCase__ (): import gc gc.collect() SCREAMING_SNAKE_CASE = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def lowerCamelCase__ (): import gc gc.collect() SCREAMING_SNAKE_CASE = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): return deepcopy(_UpperCAmelCase).integers(0 , 100 , 10).tolist() == deepcopy(_UpperCAmelCase).integers(0 , 100 , 10).tolist() def lowerCamelCase__ (_UpperCAmelCase): import decorator from requests.exceptions import HTTPError def _wrapper(_UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase): try: return func(*_UpperCAmelCase , **_UpperCAmelCase) except HTTPError as err: if str(_UpperCAmelCase).startswith('500') or str(_UpperCAmelCase).startswith('502'): pytest.xfail(str(_UpperCAmelCase)) raise err return decorator.decorator(_wrapper , _UpperCAmelCase) class _snake_case : def __init__( self , a , a , a) -> str: SCREAMING_SNAKE_CASE = returncode SCREAMING_SNAKE_CASE = stdout SCREAMING_SNAKE_CASE = stderr async def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): while True: SCREAMING_SNAKE_CASE = await stream.readline() if line: callback(_UpperCAmelCase) else: break async def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=False): if echo: print('\nRunning: ' , ' '.join(_UpperCAmelCase)) SCREAMING_SNAKE_CASE = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=_UpperCAmelCase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=_UpperCAmelCase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] def tee(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=""): SCREAMING_SNAKE_CASE = line.decode('utf-8').rstrip() sink.append(_UpperCAmelCase) if not quiet: print(_UpperCAmelCase , _UpperCAmelCase , file=_UpperCAmelCase) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout , lambda _UpperCAmelCase: tee(_UpperCAmelCase , _UpperCAmelCase , sys.stdout , label='stdout:')), _read_stream(p.stderr , lambda _UpperCAmelCase: tee(_UpperCAmelCase , _UpperCAmelCase , sys.stderr , label='stderr:')), ] , timeout=_UpperCAmelCase , ) return _RunOutput(await p.wait() , _UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=180 , _UpperCAmelCase=False , _UpperCAmelCase=True): SCREAMING_SNAKE_CASE = asyncio.get_event_loop() SCREAMING_SNAKE_CASE = loop.run_until_complete( _stream_subprocess(_UpperCAmelCase , env=_UpperCAmelCase , stdin=_UpperCAmelCase , timeout=_UpperCAmelCase , quiet=_UpperCAmelCase , echo=_UpperCAmelCase)) SCREAMING_SNAKE_CASE = ' '.join(_UpperCAmelCase) if result.returncode > 0: SCREAMING_SNAKE_CASE = '\n'.join(result.stderr) raise RuntimeError( F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' F'''The combined stderr from workers follows:\n{stderr}''') # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(F'''\'{cmd_str}\' produced no output.''') return result def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = os.environ.get('PYTEST_XDIST_WORKER' , 'gw0') SCREAMING_SNAKE_CASE = re.sub(R'^gw' , '' , _UpperCAmelCase , 0 , re.M) return int(_UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 2_9500 SCREAMING_SNAKE_CASE = pytest_xdist_worker_id() return port + uniq_delta
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): if density <= 0: raise ValueError('Impossible fluid density') if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus') return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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_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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=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()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: 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_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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample 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_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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = 'hf-internal-testing/tiny-random-t5' SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(a) SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(a) SCREAMING_SNAKE_CASE = tokenizer('This is me' , return_tensors='pt') SCREAMING_SNAKE_CASE = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules())) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules())) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a) SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(a) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules())) SCREAMING_SNAKE_CASE = model_reloaded.generate(**a) self.assertTrue(torch.allclose(a , a)) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = 'hf-internal-testing/tiny-random-t5' SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(a) SCREAMING_SNAKE_CASE = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(a): model.save_pretrained(a) SCREAMING_SNAKE_CASE = model.reverse_bettertransformer() model.save_pretrained(a)
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging a_ : Union[str, Any] = logging.get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): """simple docstring""" SCREAMING_SNAKE_CASE = nn.ModuleList([src_layers[i] for i in layers_to_copy]) assert len(_UpperCAmelCase) == len(_UpperCAmelCase), F'''{len(_UpperCAmelCase)} != {len(_UpperCAmelCase)}''' dest_layers.load_state_dict(layers_to_copy.state_dict()) a_ : Union[str, Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } a_ : Optional[Any] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): """simple docstring""" try: SCREAMING_SNAKE_CASE = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F'''no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first''' F''' {n_student}''') return list(range(_UpperCAmelCase)) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): """simple docstring""" if n_student > n_teacher: raise ValueError(F'''Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}''') elif n_teacher == n_student: return list(range(_UpperCAmelCase)) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = "student" , _UpperCAmelCase = None , _UpperCAmelCase = None , _UpperCAmelCase=False , _UpperCAmelCase=None , _UpperCAmelCase=None , **_UpperCAmelCase , ): """simple docstring""" SCREAMING_SNAKE_CASE = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(_UpperCAmelCase , _UpperCAmelCase): AutoTokenizer.from_pretrained(_UpperCAmelCase).save_pretrained(_UpperCAmelCase) # purely for convenience SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(_UpperCAmelCase).eval() else: assert isinstance(_UpperCAmelCase , _UpperCAmelCase), F'''teacher must be a model or string got type {type(_UpperCAmelCase)}''' SCREAMING_SNAKE_CASE = teacher.config.to_diff_dict() try: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: SCREAMING_SNAKE_CASE = teacher_e if d is None: SCREAMING_SNAKE_CASE = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d}) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers'): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: SCREAMING_SNAKE_CASE = teacher_e if d is None: SCREAMING_SNAKE_CASE = teacher_d if hasattr(teacher.config , 'num_encoder_layers'): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d}) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d}) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(_UpperCAmelCase) # Copy weights SCREAMING_SNAKE_CASE = teacher.config_class(**_UpperCAmelCase) SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_config(_UpperCAmelCase) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. SCREAMING_SNAKE_CASE = student.load_state_dict(teacher.state_dict() , strict=_UpperCAmelCase) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = list(range(_UpperCAmelCase)), list(range(_UpperCAmelCase)) logger.info( F'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to''' F''' {save_path}''') student.save_pretrained(_UpperCAmelCase) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: SCREAMING_SNAKE_CASE = pick_layers_to_copy(_UpperCAmelCase , _UpperCAmelCase) if d_layers_to_copy is None: SCREAMING_SNAKE_CASE = pick_layers_to_copy(_UpperCAmelCase , _UpperCAmelCase) try: if hasattr( _UpperCAmelCase , 'prophetnet'): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , _UpperCAmelCase) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , _UpperCAmelCase) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , _UpperCAmelCase) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , _UpperCAmelCase) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , _UpperCAmelCase) copy_layers(teacher.decoder.block , student.decoder.block , _UpperCAmelCase) logger.info( F'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}''') SCREAMING_SNAKE_CASE = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(_UpperCAmelCase) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import argparse import torch from transformers import GPTaLMHeadModel, RobertaForMaskedLM if __name__ == "__main__": a_ : Dict = argparse.ArgumentParser( description=( 'Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='roberta', choices=['roberta', 'gpt2']) parser.add_argument('--model_name', default='roberta-large', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_roberta_048131723.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') a_ : str = parser.parse_args() if args.model_type == "roberta": a_ : int = RobertaForMaskedLM.from_pretrained(args.model_name) a_ : Optional[int] = 'roberta' elif args.model_type == "gpt2": a_ : List[str] = GPTaLMHeadModel.from_pretrained(args.model_name) a_ : int = 'transformer' a_ : Tuple = model.state_dict() a_ : Tuple = {} # Embeddings # if args.model_type == "gpt2": for param_name in ["wte.weight", "wpe.weight"]: a_ : Optional[int] = state_dict[f"""{prefix}.{param_name}"""] else: for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]: a_ : Tuple = f"""{prefix}.embeddings.{w}.weight""" a_ : Optional[Any] = state_dict[param_name] for w in ["weight", "bias"]: a_ : int = f"""{prefix}.embeddings.LayerNorm.{w}""" a_ : Optional[Any] = state_dict[param_name] # Transformer Blocks # a_ : Optional[Any] = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: if args.model_type == "gpt2": for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]: for w in ["weight", "bias"]: a_ : str = state_dict[ f"""{prefix}.h.{teacher_idx}.{layer}.{w}""" ] a_ : Optional[Any] = state_dict[f"""{prefix}.h.{teacher_idx}.attn.bias"""] else: for layer in [ "attention.self.query", "attention.self.key", "attention.self.value", "attention.output.dense", "attention.output.LayerNorm", "intermediate.dense", "output.dense", "output.LayerNorm", ]: for w in ["weight", "bias"]: a_ : str = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}""" ] std_idx += 1 # Language Modeling Head ###s if args.model_type == "roberta": for layer in ["lm_head.decoder.weight", "lm_head.bias"]: a_ : List[str] = state_dict[f"""{layer}"""] if args.vocab_transform: for w in ["weight", "bias"]: a_ : Optional[int] = state_dict[f"""lm_head.dense.{w}"""] a_ : Dict = state_dict[f"""lm_head.layer_norm.{w}"""] elif args.model_type == "gpt2": for w in ["weight", "bias"]: a_ : Optional[int] = state_dict[f"""{prefix}.ln_f.{w}"""] a_ : Union[str, Any] = state_dict['lm_head.weight'] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = XCLIPTextConfig() # derive patch size from model name SCREAMING_SNAKE_CASE = model_name.find('patch') SCREAMING_SNAKE_CASE = int(model_name[start_idx + len('patch') : start_idx + len('patch') + 2]) SCREAMING_SNAKE_CASE = XCLIPVisionConfig(patch_size=_UpperCAmelCase , num_frames=_UpperCAmelCase) if "large" in model_name: SCREAMING_SNAKE_CASE = 768 SCREAMING_SNAKE_CASE = 3072 SCREAMING_SNAKE_CASE = 12 SCREAMING_SNAKE_CASE = 1024 SCREAMING_SNAKE_CASE = 4096 SCREAMING_SNAKE_CASE = 16 SCREAMING_SNAKE_CASE = 24 SCREAMING_SNAKE_CASE = 768 SCREAMING_SNAKE_CASE = 3072 if model_name == "xclip-large-patch14-16-frames": SCREAMING_SNAKE_CASE = 336 SCREAMING_SNAKE_CASE = XCLIPConfig.from_text_vision_configs(_UpperCAmelCase , _UpperCAmelCase) if "large" in model_name: SCREAMING_SNAKE_CASE = 768 return config def lowerCamelCase__ (_UpperCAmelCase): # text encoder if name == "token_embedding.weight": SCREAMING_SNAKE_CASE = name.replace('token_embedding.weight' , 'text_model.embeddings.token_embedding.weight') if name == "positional_embedding": SCREAMING_SNAKE_CASE = name.replace('positional_embedding' , 'text_model.embeddings.position_embedding.weight') if "ln_1" in name: SCREAMING_SNAKE_CASE = name.replace('ln_1' , 'layer_norm1') if "ln_2" in name: SCREAMING_SNAKE_CASE = name.replace('ln_2' , 'layer_norm2') if "c_fc" in name: SCREAMING_SNAKE_CASE = name.replace('c_fc' , 'fc1') if "c_proj" in name: SCREAMING_SNAKE_CASE = name.replace('c_proj' , 'fc2') if name.startswith('transformer.resblocks'): SCREAMING_SNAKE_CASE = name.replace('transformer.resblocks' , 'text_model.encoder.layers') if "attn.out_proj" in name and "message" not in name: SCREAMING_SNAKE_CASE = name.replace('attn.out_proj' , 'self_attn.out_proj') if "ln_final" in name: SCREAMING_SNAKE_CASE = name.replace('ln_final' , 'text_model.final_layer_norm') # visual encoder if name == "visual.class_embedding": SCREAMING_SNAKE_CASE = name.replace('visual.class_embedding' , 'vision_model.embeddings.class_embedding') if name == "visual.positional_embedding": SCREAMING_SNAKE_CASE = name.replace('visual.positional_embedding' , 'vision_model.embeddings.position_embedding.weight') if name.startswith('visual.transformer.resblocks'): SCREAMING_SNAKE_CASE = name.replace('visual.transformer.resblocks' , 'vision_model.encoder.layers') if "visual.conv1" in name: SCREAMING_SNAKE_CASE = name.replace('visual.conv1' , 'vision_model.embeddings.patch_embedding') if "visual.ln_pre" in name: SCREAMING_SNAKE_CASE = name.replace('visual.ln_pre' , 'vision_model.pre_layernorm') if "visual.ln_post" in name: SCREAMING_SNAKE_CASE = name.replace('visual.ln_post' , 'vision_model.post_layernorm') if "visual.proj" in name: SCREAMING_SNAKE_CASE = name.replace('visual.proj' , 'visual_projection.weight') if "text_projection" in name: SCREAMING_SNAKE_CASE = name.replace('text_projection' , 'text_projection.weight') # things on top if "prompts_visual_proj" in name: SCREAMING_SNAKE_CASE = name.replace('prompts_visual_proj' , 'prompts_visual_projection') if "prompts_visual_ln" in name: SCREAMING_SNAKE_CASE = name.replace('prompts_visual_ln' , 'prompts_visual_layernorm') # mit if name == "mit.positional_embedding": SCREAMING_SNAKE_CASE = name.replace('positional' , 'position') if name.startswith('mit.resblocks'): SCREAMING_SNAKE_CASE = name.replace('mit.resblocks' , 'mit.encoder.layers') # prompts generator if name.startswith('prompts_generator.norm'): SCREAMING_SNAKE_CASE = name.replace('prompts_generator.norm' , 'prompts_generator.layernorm') return name def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_UpperCAmelCase) if "attn.in_proj" in key: SCREAMING_SNAKE_CASE = key.split('.') if key.startswith('visual'): SCREAMING_SNAKE_CASE = key_split[3] SCREAMING_SNAKE_CASE = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: SCREAMING_SNAKE_CASE = val[ :dim, : ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[ -dim:, : ] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: if "weight" in key: SCREAMING_SNAKE_CASE = val[ :dim, : ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[ -dim:, : ] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[-dim:] elif key.startswith('mit'): SCREAMING_SNAKE_CASE = key_split[2] SCREAMING_SNAKE_CASE = config.vision_config.mit_hidden_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[dim : dim * 2] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = key_split[2] SCREAMING_SNAKE_CASE = config.text_config.hidden_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[:dim] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[-dim:] else: SCREAMING_SNAKE_CASE = rename_key(_UpperCAmelCase) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: SCREAMING_SNAKE_CASE = val.T SCREAMING_SNAKE_CASE = val return orig_state_dict def lowerCamelCase__ (_UpperCAmelCase): if num_frames == 8: SCREAMING_SNAKE_CASE = 'eating_spaghetti_8_frames.npy' elif num_frames == 16: SCREAMING_SNAKE_CASE = 'eating_spaghetti.npy' elif num_frames == 32: SCREAMING_SNAKE_CASE = 'eating_spaghetti_32_frames.npy' SCREAMING_SNAKE_CASE = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename=_UpperCAmelCase , repo_type='dataset' , ) SCREAMING_SNAKE_CASE = np.load(_UpperCAmelCase) return list(_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=False): SCREAMING_SNAKE_CASE = { # fully supervised kinetics-400 checkpoints 'xclip-base-patch32': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth', 'xclip-base-patch32-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth' ), 'xclip-base-patch16': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth', 'xclip-base-patch16-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth' ), 'xclip-large-patch14': 'https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb', 'xclip-large-patch14-16-frames': 'https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f', # fully supervised kinetics-600 checkpoints 'xclip-base-patch16-kinetics-600': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth' ), 'xclip-base-patch16-kinetics-600-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth' ), 'xclip-large-patch14-kinetics-600': 'https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be', # few shot 'xclip-base-patch16-hmdb-2-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth' ), 'xclip-base-patch16-hmdb-4-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth' ), 'xclip-base-patch16-hmdb-8-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth' ), 'xclip-base-patch16-hmdb-16-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth' ), 'xclip-base-patch16-ucf-2-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth' ), 'xclip-base-patch16-ucf-4-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth' ), 'xclip-base-patch16-ucf-8-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth' ), 'xclip-base-patch16-ucf-16-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth' ), # zero shot 'xclip-base-patch16-zero-shot': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth', } SCREAMING_SNAKE_CASE = model_to_url[model_name] SCREAMING_SNAKE_CASE = 8 if "16-frames" in model_name: SCREAMING_SNAKE_CASE = 16 elif "shot" in model_name: SCREAMING_SNAKE_CASE = 32 SCREAMING_SNAKE_CASE = get_xclip_config(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = XCLIPModel(_UpperCAmelCase) model.eval() if "drive" in checkpoint_url: SCREAMING_SNAKE_CASE = 'pytorch_model.bin' gdown.cached_download(_UpperCAmelCase , _UpperCAmelCase , quiet=_UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu')['model'] else: SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(_UpperCAmelCase)['model'] SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = XCLIPModel(_UpperCAmelCase) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() SCREAMING_SNAKE_CASE = 336 if model_name == 'xclip-large-patch14-16-frames' else 224 SCREAMING_SNAKE_CASE = VideoMAEImageProcessor(size=_UpperCAmelCase) SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32') SCREAMING_SNAKE_CASE = CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32') SCREAMING_SNAKE_CASE = XCLIPProcessor(image_processor=_UpperCAmelCase , tokenizer=_UpperCAmelCase) SCREAMING_SNAKE_CASE = prepare_video(_UpperCAmelCase) SCREAMING_SNAKE_CASE = processor( text=['playing sports', 'eating spaghetti', 'go shopping'] , videos=_UpperCAmelCase , return_tensors='pt' , padding=_UpperCAmelCase) print('Shape of pixel values:' , inputs.pixel_values.shape) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase) # Verify outputs SCREAMING_SNAKE_CASE = outputs.logits_per_video SCREAMING_SNAKE_CASE = logits_per_video.softmax(dim=1) print('Probs:' , _UpperCAmelCase) # kinetics-400 if model_name == "xclip-base-patch32": SCREAMING_SNAKE_CASE = torch.tensor([[0.00_19, 0.99_51, 0.00_30]]) elif model_name == "xclip-base-patch32-16-frames": SCREAMING_SNAKE_CASE = torch.tensor([[7.0999e-04, 9.9883e-01, 4.5580e-04]]) elif model_name == "xclip-base-patch16": SCREAMING_SNAKE_CASE = torch.tensor([[0.00_83, 0.96_81, 0.02_36]]) elif model_name == "xclip-base-patch16-16-frames": SCREAMING_SNAKE_CASE = torch.tensor([[7.6937e-04, 9.9728e-01, 1.9473e-03]]) elif model_name == "xclip-large-patch14": SCREAMING_SNAKE_CASE = torch.tensor([[0.00_62, 0.98_64, 0.00_75]]) elif model_name == "xclip-large-patch14-16-frames": SCREAMING_SNAKE_CASE = torch.tensor([[3.3877e-04, 9.9937e-01, 2.8888e-04]]) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": SCREAMING_SNAKE_CASE = torch.tensor([[0.05_55, 0.89_14, 0.05_31]]) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": SCREAMING_SNAKE_CASE = torch.tensor([[3.8554e-04, 9.9929e-01, 3.2754e-04]]) elif model_name == "xclip-large-patch14-kinetics-600": SCREAMING_SNAKE_CASE = torch.tensor([[0.00_36, 0.99_20, 0.00_45]]) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": SCREAMING_SNAKE_CASE = torch.tensor([[7.1890e-06, 9.9994e-01, 5.6559e-05]]) elif model_name == "xclip-base-patch16-hmdb-4-shot": SCREAMING_SNAKE_CASE = torch.tensor([[1.0320e-05, 9.9993e-01, 6.2435e-05]]) elif model_name == "xclip-base-patch16-hmdb-8-shot": SCREAMING_SNAKE_CASE = torch.tensor([[4.1377e-06, 9.9990e-01, 9.8386e-05]]) elif model_name == "xclip-base-patch16-hmdb-16-shot": SCREAMING_SNAKE_CASE = torch.tensor([[4.1347e-05, 9.9962e-01, 3.3411e-04]]) elif model_name == "xclip-base-patch16-ucf-2-shot": SCREAMING_SNAKE_CASE = torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]) elif model_name == "xclip-base-patch16-ucf-4-shot": SCREAMING_SNAKE_CASE = torch.tensor([[8.5857e-05, 9.9928e-01, 6.3291e-04]]) elif model_name == "xclip-base-patch16-ucf-8-shot": SCREAMING_SNAKE_CASE = torch.tensor([[0.00_27, 0.99_04, 0.00_70]]) elif model_name == "xclip-base-patch16-ucf-16-shot": SCREAMING_SNAKE_CASE = torch.tensor([[9.8219e-04, 9.9593e-01, 3.0863e-03]]) # zero shot elif model_name == "xclip-base-patch16-zero-shot": SCREAMING_SNAKE_CASE = torch.tensor([[3.5082e-04, 9.9785e-01, 1.7966e-03]]) else: raise ValueError(F'''Model name {model_name} not supported''') assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase , atol=1e-3) print('Looks ok!') if pytorch_dump_folder_path is not None: print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''') model.save_pretrained(_UpperCAmelCase) if push_to_hub: print('Pushing model, processor and slow tokenizer files to the hub...') model.push_to_hub(_UpperCAmelCase , organization='nielsr') processor.push_to_hub(_UpperCAmelCase , organization='nielsr') slow_tokenizer.push_to_hub(_UpperCAmelCase , organization='nielsr') if __name__ == "__main__": a_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='xclip-base-patch32', type=str, help='Name of the model.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a_ : Dict = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return [1] + ([0] * len(a)) + [1] return [1] + ([0] * len(a)) + [1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
from __future__ import annotations def lowerCamelCase__ (_UpperCAmelCase): if not nums: raise ValueError('List is empty') return sum(_UpperCAmelCase) / len(_UpperCAmelCase) if __name__ == "__main__": import doctest doctest.testmod()
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) self.log(a) else: SCREAMING_SNAKE_CASE = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , a) return metrics def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_test_dataloader(a) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , 'predict') SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0
def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = 0 for ch in input_str: SCREAMING_SNAKE_CASE = ord(_UpperCAmelCase) SCREAMING_SNAKE_CASE = pow(2 , _UpperCAmelCase) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
361
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = TFCamembertModel.from_pretrained('jplu/tf-camembert-base') SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE = model(a)['last_hidden_state'] SCREAMING_SNAKE_CASE = tf.TensorShape((1, 10, 768)) self.assertEqual(output.shape , a) # compare the actual values for a slice. SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[[-0.02_54, 0.02_35, 0.10_27], [0.06_06, -0.18_11, -0.04_18], [-0.15_61, -0.11_27, 0.26_87]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4))
327
0
from __future__ import annotations from functools import lru_cache from math import ceil a_ : Tuple = 1_00 a_ : Dict = set(range(3, NUM_PRIMES, 2)) primes.add(2) a_ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=100) def lowerCamelCase__ (_UpperCAmelCase): if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} SCREAMING_SNAKE_CASE = set() SCREAMING_SNAKE_CASE = 42 SCREAMING_SNAKE_CASE = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime): ret.add(sub * prime) return ret def lowerCamelCase__ (_UpperCAmelCase = 5000): for number_to_partition in range(1 , _UpperCAmelCase): if len(partition(_UpperCAmelCase)) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
362
from scipy.stats import pearsonr import datasets a_ : Optional[int] = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' a_ : Optional[int] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' a_ : Any = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=False) -> Optional[Any]: if return_pvalue: SCREAMING_SNAKE_CASE = pearsonr(a , a) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(a , a)[0])}
327
0
from __future__ import annotations class _snake_case : def __init__( self , a = 0) -> Optional[Any]: SCREAMING_SNAKE_CASE = key def SCREAMING_SNAKE_CASE__ ( self , a , a) -> list[str]: assert isinstance(a , a) and isinstance(a , a) SCREAMING_SNAKE_CASE = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(a) ^ key) for ch in content] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> list[str]: assert isinstance(a , a) and isinstance(a , a) SCREAMING_SNAKE_CASE = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(a) ^ key) for ch in content] def SCREAMING_SNAKE_CASE__ ( self , a , a = 0) -> str: assert isinstance(a , a) and isinstance(a , a) SCREAMING_SNAKE_CASE = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE = '' for ch in content: ans += chr(ord(a) ^ key) return ans def SCREAMING_SNAKE_CASE__ ( self , a , a = 0) -> str: assert isinstance(a , a) and isinstance(a , a) SCREAMING_SNAKE_CASE = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE = '' for ch in content: ans += chr(ord(a) ^ key) return ans def SCREAMING_SNAKE_CASE__ ( self , a , a = 0) -> bool: assert isinstance(a , a) and isinstance(a , a) try: with open(a) as fin, open('encrypt.out' , 'w+') as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(a , a)) except OSError: return False return True def SCREAMING_SNAKE_CASE__ ( self , a , a) -> bool: assert isinstance(a , a) and isinstance(a , a) try: with open(a) as fin, open('decrypt.out' , 'w+') as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(a , a)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
363
import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _snake_case ( unittest.TestCase ): _lowercase : List[Any] = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowercase : int = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TextaTextGenerationPipeline(model=a , tokenizer=a) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Any: SCREAMING_SNAKE_CASE = generator('Something there') self.assertEqual(a , [{'generated_text': ANY(a)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there')) SCREAMING_SNAKE_CASE = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) SCREAMING_SNAKE_CASE = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=a) self.assertEqual( a , [ [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], [{'generated_text': ANY(a)}, {'generated_text': ANY(a)}], ] , ) with self.assertRaises(a): generator(4) @require_torch def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}]) SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = generator( 'Something there' , num_return_sequences=a , num_beams=a , ) SCREAMING_SNAKE_CASE = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(a , a) SCREAMING_SNAKE_CASE = generator('This is a test' , do_sample=a , num_return_sequences=2 , return_tensors=a) self.assertEqual( a , [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ] , ) SCREAMING_SNAKE_CASE = generator.model.config.eos_token_id SCREAMING_SNAKE_CASE = '<pad>' SCREAMING_SNAKE_CASE = generator( ['This is a test', 'This is a second test'] , do_sample=a , num_return_sequences=2 , batch_size=2 , return_tensors=a , ) self.assertEqual( a , [ [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], [ {'generated_token_ids': ANY(torch.Tensor)}, {'generated_token_ids': ANY(torch.Tensor)}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf') # do_sample=False necessary for reproducibility SCREAMING_SNAKE_CASE = generator('Something there' , do_sample=a) self.assertEqual(a , [{'generated_text': ''}])
327
0
from statistics import mean, stdev def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 3): SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) SCREAMING_SNAKE_CASE = max(_UpperCAmelCase) # normalize data return [round((x - x_min) / (x_max - x_min) , _UpperCAmelCase) for x in data] def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = 3): SCREAMING_SNAKE_CASE = mean(_UpperCAmelCase) SCREAMING_SNAKE_CASE = stdev(_UpperCAmelCase) # standardize data return [round((x - mu) / (sigma) , _UpperCAmelCase) for x in data]
364
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights SCREAMING_SNAKE_CASE = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a , cache_dir=a) SCREAMING_SNAKE_CASE = [t[-1] for t in os.walk(os.path.join(a , os.listdir(a)[0] , 'snapshots'))] SCREAMING_SNAKE_CASE = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin') for f in files) @slow @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0) SCREAMING_SNAKE_CASE = 4 SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 4.1_51_47_45) < 1E-3 assert np.abs(np.abs(a , dtype=np.floataa).sum() - 4_99_47.8_75) < 5E-1 SCREAMING_SNAKE_CASE = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]))) assert len(a) == num_samples def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.05_65_24_01)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_38_38_08.2)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa) SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.04_00_39_06)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_37_35_16.75)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='scaled_linear' , set_alpha_to_one=a , steps_offset=1 , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=a , safety_checker=a , ) SCREAMING_SNAKE_CASE = scheduler.create_state() SCREAMING_SNAKE_CASE = scheduler_state SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) 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 = pipeline.prepare_inputs(a) # shard inputs and rng SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = jax.random.split(a , a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa).sum() - 0.0_45_04_39_45)) < 1E-3 assert np.abs((np.abs(a , dtype=np.floataa).sum() - 2_34_76_93.5)) < 5E-1 def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) SCREAMING_SNAKE_CASE = jax.device_count() SCREAMING_SNAKE_CASE = num_samples * [prompt] SCREAMING_SNAKE_CASE = jax.random.split(jax.random.PRNGKey(0) , a) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # With memory efficient attention SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=a , use_memory_efficient_attention=a , ) SCREAMING_SNAKE_CASE = replicate(a) SCREAMING_SNAKE_CASE = pipeline.prepare_inputs(a) SCREAMING_SNAKE_CASE = shard(a) SCREAMING_SNAKE_CASE = pipeline(a , a , a , jit=a).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) SCREAMING_SNAKE_CASE = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice).max() < 1E-2
327
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowerCamelCase__ (): print(sum_of_series(1 , 1 , 10)) if __name__ == "__main__": import doctest doctest.testmod()
365
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ : Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ : List[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ : List[str] = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a=True , a=False) -> Optional[Any]: if rouge_types is None: SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a) if use_aggregator: SCREAMING_SNAKE_CASE = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE = [] for ref, pred in zip(a , a): SCREAMING_SNAKE_CASE = scorer.score(a , a) if use_aggregator: aggregator.add_scores(a) else: scores.append(a) if use_aggregator: SCREAMING_SNAKE_CASE = aggregator.aggregate() else: SCREAMING_SNAKE_CASE = {} for key in scores[0]: SCREAMING_SNAKE_CASE = [score[key] for score in scores] return result
327
0
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
366
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCamelCase__ (_UpperCAmelCase): if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class _snake_case ( nn.Module ): def __init__( self , a , a) -> Union[str, Any]: super().__init__() SCREAMING_SNAKE_CASE = module SCREAMING_SNAKE_CASE = nn.Sequential( nn.Linear(module.in_features , a , bias=a) , nn.Linear(a , module.out_features , bias=a) , ) SCREAMING_SNAKE_CASE = (2.0 / (5 * min(module.in_features , module.out_features))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=a) nn.init.zeros_(self.adapter[1].weight) self.adapter.to(module.weight.device) def SCREAMING_SNAKE_CASE__ ( self , a , *a , **a) -> Any: return self.module(a , *a , **a) + self.adapter(a) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module _lowercase : Union[str, Any] = '''bigscience/bloom-1b7''' # Constant values _lowercase : str = 2.109_6595_5269_2574 _lowercase : Any = '''Hello my name is''' _lowercase : Any = set() EXPECTED_OUTPUTS.add('''Hello my name is John and I am a professional photographer. I''' ) EXPECTED_OUTPUTS.add('''Hello my name is John.\nI am a friend of your father.\n''' ) EXPECTED_OUTPUTS.add('''Hello my name is John Doe, I am a student at the University''' ) _lowercase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE__ ( self) -> Any: # Models and tokenizer SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(self.model_name) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: super().setUp() # Models and tokenizer SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map='auto') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.model_abit.config self.assertTrue(hasattr(a , 'quantization_config')) SCREAMING_SNAKE_CASE = config.to_dict() SCREAMING_SNAKE_CASE = config.to_diff_dict() SCREAMING_SNAKE_CASE = config.to_json_string() def SCREAMING_SNAKE_CASE__ ( self) -> Any: from bitsandbytes.nn import Paramsabit SCREAMING_SNAKE_CASE = self.model_fpaa.get_memory_footprint() SCREAMING_SNAKE_CASE = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE) SCREAMING_SNAKE_CASE = get_some_linear_layer(self.model_abit) self.assertTrue(linear.weight.__class__ == Paramsabit) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(a , torch.nn.Linear): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_abit.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = model_abit_from_config.generate( input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) def SCREAMING_SNAKE_CASE__ ( self) -> str: with self.assertRaises(a), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = BitsAndBytesConfig() with self.assertRaises(a): SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=a , load_in_abit=a , device_map='auto' , bnb_abit_quant_type='nf4' , ) def SCREAMING_SNAKE_CASE__ ( self) -> int: with self.assertRaises(a): # Tries with `str` self.model_abit.to('cpu') with self.assertRaises(a): # Tries with a `dtype`` self.model_abit.to(torch.floataa) with self.assertRaises(a): # Tries with a `device` self.model_abit.to(torch.device('cuda:0')) with self.assertRaises(a): # Tries with a `device` self.model_abit.float() with self.assertRaises(a): # Tries with a `device` self.model_abit.half() # Test if we did not break anything SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') SCREAMING_SNAKE_CASE = self.model_fpaa.to(torch.floataa) SCREAMING_SNAKE_CASE = self.model_fpaa.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.to('cpu') # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.half() # Check this does not throw an error SCREAMING_SNAKE_CASE = self.model_fpaa.float() def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained('t5-small' , load_in_abit=a , device_map='auto') self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Tuple: SCREAMING_SNAKE_CASE = 't5-small' SCREAMING_SNAKE_CASE = 'google/flan-t5-small' # flan-t5 uses dense-act instead of dense-relu-dense SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(cls.model_name) SCREAMING_SNAKE_CASE = 'Translate in German: Hello, my dog is cute' def SCREAMING_SNAKE_CASE__ ( self) -> Dict: gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: from transformers import TaForConditionalGeneration SCREAMING_SNAKE_CASE = TaForConditionalGeneration._keep_in_fpaa_modules SCREAMING_SNAKE_CASE = None # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) SCREAMING_SNAKE_CASE = modules def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit)) SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) # test with `flan-t5-small` SCREAMING_SNAKE_CASE = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=a , device_map='auto') SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt').to(0) SCREAMING_SNAKE_CASE = model.generate(**a) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> str: super().setUp() # model_name SCREAMING_SNAKE_CASE = 'bigscience/bloom-560m' SCREAMING_SNAKE_CASE = 't5-small' # Different types of model SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Sequence classification model SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=a , device_map='auto') # CausalLM model SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a , device_map='auto') # Seq2seq model SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=a , device_map='auto') def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Dict: del self.pipe gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = pipeline( 'text-generation' , model=self.model_name , model_kwargs={'device_map': 'auto', 'load_in_4bit': True, 'torch_dtype': torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass SCREAMING_SNAKE_CASE = self.pipe(self.input_text) self.assertIn(pipeline_output[0]['generated_text'] , self.EXPECTED_OUTPUTS) @require_torch_multi_gpu class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> int: super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=a , device_map='balanced') # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values()) , {0, 1}) # Check that inference pass works on the model SCREAMING_SNAKE_CASE = self.tokenizer(self.input_text , return_tensors='pt') # Second real batch SCREAMING_SNAKE_CASE = model_parallel.generate(input_ids=encoded_input['input_ids'].to(0) , max_new_tokens=10) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=a) , self.EXPECTED_OUTPUTS) class _snake_case ( A__ ): def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = 'facebook/opt-350m' super().setUp() def SCREAMING_SNAKE_CASE__ ( self) -> Any: if version.parse(importlib.metadata.version('bitsandbytes')) < version.parse('0.37.0'): return # Step 1: freeze all parameters SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=a) self.assertEqual(set(model.hf_device_map.values()) , {torch.cuda.current_device()}) for param in model.parameters(): SCREAMING_SNAKE_CASE = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability SCREAMING_SNAKE_CASE = param.data.to(torch.floataa) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(a)): SCREAMING_SNAKE_CASE = LoRALayer(module.q_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.k_proj , rank=16) SCREAMING_SNAKE_CASE = LoRALayer(module.v_proj , rank=16) # Step 3: dummy batch SCREAMING_SNAKE_CASE = self.tokenizer('Test batch ' , return_tensors='pt').to(0) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): SCREAMING_SNAKE_CASE = model.forward(**a) out.logits.norm().backward() for module in model.modules(): if isinstance(a , a): self.assertTrue(module.adapter[1].weight.grad is not None) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) elif isinstance(a , nn.Embedding): self.assertTrue(module.weight.grad is None) class _snake_case ( A__ ): _lowercase : str = '''gpt2-xl''' _lowercase : Union[str, Any] = 3.3191_8548_5415_2187
327
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : Optional[Any] = { 'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Any = [ 'SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Swinv2ForImageClassification', 'Swinv2ForMaskedImageModeling', 'Swinv2Model', 'Swinv2PreTrainedModel', ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys a_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
367
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ : Optional[Any] = { 'configuration_efficientnet': [ 'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'EfficientNetConfig', 'EfficientNetOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ['EfficientNetImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = [ 'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'EfficientNetForImageClassification', 'EfficientNetModel', 'EfficientNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_efficientnet import ( EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig, EfficientNetOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientnet import EfficientNetImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure)
327
0
a_ : Any = 'Alexander Joslin' import operator as op from .stack import Stack def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = {'*': op.mul, '/': op.truediv, '+': op.add, '-': op.sub} SCREAMING_SNAKE_CASE = Stack() SCREAMING_SNAKE_CASE = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(_UpperCAmelCase)) elif i in operators: # RULE 2 operator_stack.push(_UpperCAmelCase) elif i == ")": # RULE 4 SCREAMING_SNAKE_CASE = operator_stack.peek() operator_stack.pop() SCREAMING_SNAKE_CASE = operand_stack.peek() operand_stack.pop() SCREAMING_SNAKE_CASE = operand_stack.peek() operand_stack.pop() SCREAMING_SNAKE_CASE = operators[opr](_UpperCAmelCase , _UpperCAmelCase) operand_stack.push(_UpperCAmelCase) # RULE 5 return operand_stack.peek() if __name__ == "__main__": a_ : Tuple = '(5 + ((4 * 2) * (2 + 3)))' # answer = 45 print(f"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
368
import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a_ : Dict = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , a = None) -> Optional[int]: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'by_feature')) SCREAMING_SNAKE_CASE = os.path.abspath('examples') for item in os.listdir(a): if item not in EXCLUDE_EXAMPLES: SCREAMING_SNAKE_CASE = os.path.join(a , a) if os.path.isfile(a) and ".py" in item_path: with self.subTest( tested_script=a , feature_script=a , tested_section='main()' if parser_only else 'training_function()' , ): SCREAMING_SNAKE_CASE = compare_against_test( os.path.join(a , a) , a , a , a) SCREAMING_SNAKE_CASE = '\n'.join(a) if special_strings is not None: for string in special_strings: SCREAMING_SNAKE_CASE = diff.replace(a , '') self.assertEqual(a , '') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: self.one_complete_example('complete_nlp_example.py' , a) self.one_complete_example('complete_nlp_example.py' , a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = os.path.abspath(os.path.join('examples' , 'cv_example.py')) SCREAMING_SNAKE_CASE = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , a , a , a) self.one_complete_example('complete_cv_example.py' , a , a , a) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class _snake_case ( A__ ): _lowercase : int = False @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Union[str, Any]: super().setUpClass() SCREAMING_SNAKE_CASE = tempfile.mkdtemp() SCREAMING_SNAKE_CASE = os.path.join(cls._tmpdir , 'default_config.yml') write_basic_config(save_location=cls.configPath) SCREAMING_SNAKE_CASE = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> Dict: super().tearDownClass() shutil.rmtree(cls._tmpdir) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0'))) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2'))) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2')} '''.split() SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) if torch.cuda.is_available(): SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: SCREAMING_SNAKE_CASE = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) else: self.assertIn('epoch 0:' , a) self.assertIn('epoch 1:' , a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'}): SCREAMING_SNAKE_CASE = run_command(self._launch_args + testargs , return_stdout=a) SCREAMING_SNAKE_CASE = re.findall('({.+})' , a) SCREAMING_SNAKE_CASE = [r for r in results if 'accuracy' in r][-1] SCREAMING_SNAKE_CASE = ast.literal_eval(a) self.assertGreaterEqual(results['accuracy'] , 0.75) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'}) def SCREAMING_SNAKE_CASE__ ( self) -> Any: with tempfile.TemporaryDirectory() as tmpdir: SCREAMING_SNAKE_CASE = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs) self.assertTrue(os.path.exists(os.path.join(a , 'tracking'))) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: SCREAMING_SNAKE_CASE = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs)
327
0
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, 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 ( A__ , unittest.TestCase ): _lowercase : Optional[int] = MobileBertTokenizer _lowercase : Optional[Any] = MobileBertTokenizerFast _lowercase : Dict = True _lowercase : Dict = True _lowercase : List[Any] = filter_non_english _lowercase : int = '''google/mobilebert-uncased''' def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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])) SCREAMING_SNAKE_CASE = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[int]: SCREAMING_SNAKE_CASE = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE = 'unwanted, running' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> str: 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 SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz') , ['ah', '\u535A', '\u63A8', 'zz']) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Dict: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=a) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ') , ['HeLLo', '!', 'how', 'Are', 'yoU', '?']) def SCREAMING_SNAKE_CASE__ ( self) -> str: 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 SCREAMING_SNAKE_CASE__ ( self) -> int: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: self.assertTrue(_is_whitespace(' ')) self.assertTrue(_is_whitespace('\t')) self.assertTrue(_is_whitespace('\r')) self.assertTrue(_is_whitespace('\n')) self.assertTrue(_is_whitespace('\u00A0')) self.assertFalse(_is_whitespace('A')) self.assertFalse(_is_whitespace('-')) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: self.assertTrue(_is_control('\u0005')) self.assertFalse(_is_control('A')) self.assertFalse(_is_control(' ')) self.assertFalse(_is_control('\t')) self.assertFalse(_is_control('\r')) def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: self.assertTrue(_is_punctuation('-')) self.assertTrue(_is_punctuation('$')) self.assertTrue(_is_punctuation('`')) self.assertTrue(_is_punctuation('.')) self.assertFalse(_is_punctuation('A')) self.assertFalse(_is_punctuation(' ')) def SCREAMING_SNAKE_CASE__ ( self) -> Any: 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 SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained('google/mobilebert-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 SCREAMING_SNAKE_CASE__ ( self) -> str: 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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: 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)
369
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _snake_case : def __init__( self , a , a=3 , a=32 , a=3 , a=10 , a=[10, 20, 30, 40] , a=[1, 1, 2, 1] , a=True , a=True , a="relu" , a=3 , a=None , ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = embeddings_size SCREAMING_SNAKE_CASE = hidden_sizes SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = scope SCREAMING_SNAKE_CASE = len(a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: 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.num_labels) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> Any: SCREAMING_SNAKE_CASE = TFResNetModel(config=a) SCREAMING_SNAKE_CASE = model(a) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a) -> int: SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = TFResNetForImageClassification(a) SCREAMING_SNAKE_CASE = model(a , labels=a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: 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 ( A__ , A__ , unittest.TestCase ): _lowercase : List[Any] = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase : Dict = ( {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase : Union[str, Any] = False _lowercase : Any = False _lowercase : List[str] = False _lowercase : str = False _lowercase : int = False def SCREAMING_SNAKE_CASE__ ( self) -> Dict: SCREAMING_SNAKE_CASE = TFResNetModelTester(self) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=a , has_text_modality=a) def SCREAMING_SNAKE_CASE__ ( self) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return @unittest.skip(reason='ResNet does not use inputs_embeds') def SCREAMING_SNAKE_CASE__ ( self) -> int: pass @unittest.skip(reason='ResNet does not support input and output embeddings') def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: 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 SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: def check_hidden_states_output(a , a , a): SCREAMING_SNAKE_CASE = model_class(a) SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(a , a)) SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(a) , expected_num_stages + 1) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE = layer_type SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(a , a , a) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a) @slow def SCREAMING_SNAKE_CASE__ ( self) -> str: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(a) self.assertIsNotNone(a) def lowerCamelCase__ (): 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 SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) 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([-11.10_69, -9.78_77, -8.37_77]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4))
327
0
def lowerCamelCase__ (_UpperCAmelCase): if not isinstance(_UpperCAmelCase , _UpperCAmelCase): raise ValueError('multiplicative_persistence() only accepts integral values') if num < 0: raise ValueError('multiplicative_persistence() does not accept negative values') SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = str(_UpperCAmelCase) while len(_UpperCAmelCase) != 1: SCREAMING_SNAKE_CASE = [int(_UpperCAmelCase) for i in num_string] SCREAMING_SNAKE_CASE = 1 for i in range(0 , len(_UpperCAmelCase)): total *= numbers[i] SCREAMING_SNAKE_CASE = str(_UpperCAmelCase) steps += 1 return steps def lowerCamelCase__ (_UpperCAmelCase): if not isinstance(_UpperCAmelCase , _UpperCAmelCase): raise ValueError('additive_persistence() only accepts integral values') if num < 0: raise ValueError('additive_persistence() does not accept negative values') SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = str(_UpperCAmelCase) while len(_UpperCAmelCase) != 1: SCREAMING_SNAKE_CASE = [int(_UpperCAmelCase) for i in num_string] SCREAMING_SNAKE_CASE = 0 for i in range(0 , len(_UpperCAmelCase)): total += numbers[i] SCREAMING_SNAKE_CASE = str(_UpperCAmelCase) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
370
from math import isqrt def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [True] * max_number for i in range(2 , isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2 , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = False return [i for i in range(2 , _UpperCAmelCase) if is_prime[i]] def lowerCamelCase__ (_UpperCAmelCase = 10**8): SCREAMING_SNAKE_CASE = calculate_prime_numbers(max_number // 2) SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"""{solution() = }""")
327
0
def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase = False): if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_3170_4406_4679_8873_8596_1981 and not allow_probable: raise ValueError( 'Warning: upper bound of deterministic test is exceeded. ' 'Pass allow_probable=True to allow probabilistic test. ' 'A return value of True indicates a probable prime.') # array bounds provided by analysis SCREAMING_SNAKE_CASE = [ 2047, 137_3653, 2532_6001, 32_1503_1751, 2_1523_0289_8747, 3_4747_4966_0383, 341_5500_7172_8321, 1, 382_5123_0565_4641_3051, 1, 1, 3186_6585_7834_0311_5116_7461, 3_3170_4406_4679_8873_8596_1981, ] SCREAMING_SNAKE_CASE = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(_UpperCAmelCase , 1): if n < _p: # then we have our last prime to check SCREAMING_SNAKE_CASE = primes[:idx] break SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: SCREAMING_SNAKE_CASE = False for r in range(_UpperCAmelCase): SCREAMING_SNAKE_CASE = pow(_UpperCAmelCase , d * 2**r , _UpperCAmelCase) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): SCREAMING_SNAKE_CASE = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def lowerCamelCase__ (): assert not miller_rabin(561) assert miller_rabin(563) # 2047 assert not miller_rabin(83_8201) assert miller_rabin(83_8207) # 1_373_653 assert not miller_rabin(1731_6001) assert miller_rabin(1731_6017) # 25_326_001 assert not miller_rabin(30_7838_6641) assert miller_rabin(30_7838_6653) # 3_215_031_751 assert not miller_rabin(1_7130_4557_4801) assert miller_rabin(1_7130_4557_4819) # 2_152_302_898_747 assert not miller_rabin(2_7797_9972_8307) assert miller_rabin(2_7797_9972_8327) # 3_474_749_660_383 assert not miller_rabin(113_8500_2390_9441) assert miller_rabin(113_8500_2390_9527) # 341_550_071_728_321 assert not miller_rabin(127_5041_0188_4880_4351) assert miller_rabin(127_5041_0188_4880_4391) # 3_825_123_056_546_413_051 assert not miller_rabin(796_6646_4458_5077_8779_1867) assert miller_rabin(796_6646_4458_5077_8779_1951) # 318_665_857_834_031_151_167_461 assert not miller_rabin(5528_4067_7446_6478_9766_0333) assert miller_rabin(5528_4067_7446_6478_9766_0359) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
371
import baseaa def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaaencode(string.encode('utf-8')) def lowerCamelCase__ (_UpperCAmelCase): return baseaa.aaadecode(_UpperCAmelCase).decode('utf-8') if __name__ == "__main__": import doctest doctest.testmod()
327
0
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase="attention"): SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False): if split_mlp_wi: SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] SCREAMING_SNAKE_CASE = (wi_a, wi_a) else: SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/mlp/wi/kernel'''] SCREAMING_SNAKE_CASE = params[F'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): return params[F'''{prefix}/layers_{i}/{layer_name}/scale'''] def lowerCamelCase__ (_UpperCAmelCase , *, _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = traverse_util.flatten_dict(variables['target']) SCREAMING_SNAKE_CASE = {'/'.join(_UpperCAmelCase): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi SCREAMING_SNAKE_CASE = 'encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:' , _UpperCAmelCase) SCREAMING_SNAKE_CASE = collections.OrderedDict() # Shared embeddings. SCREAMING_SNAKE_CASE = old['token_embedder/embedding'] # Encoder. for i in range(_UpperCAmelCase): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , 'encoder' , 'pre_attention_layer_norm') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_attention_lookup(_UpperCAmelCase , _UpperCAmelCase , 'encoder' , 'attention') SCREAMING_SNAKE_CASE = layer_norm SCREAMING_SNAKE_CASE = k.T SCREAMING_SNAKE_CASE = o.T SCREAMING_SNAKE_CASE = q.T SCREAMING_SNAKE_CASE = v.T # Block i, layer 1 (MLP). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , 'encoder' , 'pre_mlp_layer_norm') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_mlp_lookup(_UpperCAmelCase , _UpperCAmelCase , 'encoder' , _UpperCAmelCase) SCREAMING_SNAKE_CASE = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE = wi[0].T SCREAMING_SNAKE_CASE = wi[1].T else: SCREAMING_SNAKE_CASE = wi.T SCREAMING_SNAKE_CASE = wo.T SCREAMING_SNAKE_CASE = old[ 'encoder/relpos_bias/rel_embedding' ].T SCREAMING_SNAKE_CASE = old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(_UpperCAmelCase): # Block i, layer 0 (Self Attention). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , 'decoder' , 'pre_self_attention_layer_norm') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_attention_lookup(_UpperCAmelCase , _UpperCAmelCase , 'decoder' , 'self_attention') SCREAMING_SNAKE_CASE = layer_norm SCREAMING_SNAKE_CASE = k.T SCREAMING_SNAKE_CASE = o.T SCREAMING_SNAKE_CASE = q.T SCREAMING_SNAKE_CASE = v.T # Block i, layer 1 (Cross Attention). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , 'decoder' , 'pre_cross_attention_layer_norm') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_attention_lookup(_UpperCAmelCase , _UpperCAmelCase , 'decoder' , 'encoder_decoder_attention') SCREAMING_SNAKE_CASE = layer_norm SCREAMING_SNAKE_CASE = k.T SCREAMING_SNAKE_CASE = o.T SCREAMING_SNAKE_CASE = q.T SCREAMING_SNAKE_CASE = v.T # Block i, layer 2 (MLP). SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(_UpperCAmelCase , _UpperCAmelCase , 'decoder' , 'pre_mlp_layer_norm') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = tax_mlp_lookup(_UpperCAmelCase , _UpperCAmelCase , 'decoder' , _UpperCAmelCase) SCREAMING_SNAKE_CASE = layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE = wi[0].T SCREAMING_SNAKE_CASE = wi[1].T else: SCREAMING_SNAKE_CASE = wi.T SCREAMING_SNAKE_CASE = wo.T SCREAMING_SNAKE_CASE = old['decoder/decoder_norm/scale'] SCREAMING_SNAKE_CASE = old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: SCREAMING_SNAKE_CASE = old['decoder/logits_dense/kernel'].T return new def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = collections.OrderedDict([(k, torch.from_numpy(v.copy())) for (k, v) in converted_params.items()]) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: SCREAMING_SNAKE_CASE = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.') SCREAMING_SNAKE_CASE = state_dict['shared.weight'] return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(_UpperCAmelCase) SCREAMING_SNAKE_CASE = convert_tax_to_pytorch(_UpperCAmelCase , num_layers=config.num_layers , is_encoder_only=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_state_dict(_UpperCAmelCase , _UpperCAmelCase) model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = False): SCREAMING_SNAKE_CASE = TaConfig.from_json_file(_UpperCAmelCase) print(F'''Building PyTorch model from configuration: {config}''') # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: SCREAMING_SNAKE_CASE = TaEncoderModel(_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = TaForConditionalGeneration(_UpperCAmelCase) # Load weights from tf checkpoint load_tax_weights_in_ta(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''') model.save_pretrained(_UpperCAmelCase) # Verify that we can load the checkpoint. model.from_pretrained(_UpperCAmelCase) print('Done') if __name__ == "__main__": a_ : Optional[Any] = argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.') # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False ) a_ : Tuple = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
350
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(_UpperCAmelCase , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = emb.weight.shape SCREAMING_SNAKE_CASE = nn.Linear(_UpperCAmelCase , _UpperCAmelCase , bias=_UpperCAmelCase) SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE = mam_aaa['model'] remove_ignore_keys_(_UpperCAmelCase) SCREAMING_SNAKE_CASE = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE = MaMaaaConfig( vocab_size=_UpperCAmelCase , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE = MaMaaaForConditionalGeneration(_UpperCAmelCase) model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase) SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared) return model if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') a_ : List[str] = parser.parse_args() a_ : Dict = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
327
0
from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge a_ : List[str] = [ 'Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the' ' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe' ' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.', 'The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal' ' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s' ' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the' ' body.', 'Amnesty International releases its annual report on the death penalty. The report catalogs the use of' ' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the' ' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital' ' punishment.', ] a_ : List[str] = [ 'Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .' ' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz' ' had informed his Lufthansa training school of an episode of severe depression, airline says .', 'Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .' ' Israel and the United States opposed the move, which could open the door to war crimes investigations against' ' Israelis .', 'Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to' ' death . Organization claims that governments around the world are using the threat of terrorism to advance' ' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death' ' sentences up by 28% .', ] def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , bootstrap_aggregation=_UpperCAmelCase , rouge_keys=['rouge2', 'rougeL']) assert isinstance(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , bootstrap_aggregation=_UpperCAmelCase , rouge_keys=['rouge2']) assert ( pd.DataFrame(no_aggregation['rouge2']).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra['rouge2']).fmeasure.mean() ) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = 'rougeLsum' SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , newline_sep=_UpperCAmelCase , rouge_keys=[k])[k] SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , newline_sep=_UpperCAmelCase , rouge_keys=[k])[k] assert score > score_no_sep def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = ['rouge1', 'rouge2', 'rougeL'] SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , newline_sep=_UpperCAmelCase , rouge_keys=_UpperCAmelCase) SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , newline_sep=_UpperCAmelCase , rouge_keys=_UpperCAmelCase) assert score_sep == score_no_sep def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = [ 'Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.', 'Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .', ] SCREAMING_SNAKE_CASE = [ 'Margot Frank, died in 1945, a month earlier than previously thought.', 'Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of' ' the final seconds on board Flight 9525.', ] assert calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , newline_sep=_UpperCAmelCase) == calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , newline_sep=_UpperCAmelCase) def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = [ '" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" ' ] SCREAMING_SNAKE_CASE = [ ' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .' ] SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , rouge_keys=['rougeLsum'] , newline_sep=_UpperCAmelCase)['rougeLsum'] SCREAMING_SNAKE_CASE = calculate_rouge(_UpperCAmelCase , _UpperCAmelCase , rouge_keys=['rougeLsum'])['rougeLsum'] assert new_score > prev_score def lowerCamelCase__ (): SCREAMING_SNAKE_CASE = Path('examples/seq2seq/test_data/wmt_en_ro') SCREAMING_SNAKE_CASE = calculate_rouge_path(data_dir.joinpath('test.source') , data_dir.joinpath('test.target')) assert isinstance(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = calculate_rouge_path( data_dir.joinpath('test.source') , data_dir.joinpath('test.target') , bootstrap_aggregation=_UpperCAmelCase) assert isinstance(_UpperCAmelCase , _UpperCAmelCase)
351
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = 'laion/clap-htsat-unfused' SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self , **a) -> Optional[Any]: return RobertaTokenizer.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self , **a) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **a) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer , a) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)') SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=a , padding_value=1.0) SCREAMING_SNAKE_CASE = ClapProcessor.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.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor , a) def SCREAMING_SNAKE_CASE__ ( self) -> int: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = floats_list((3, 1000)) SCREAMING_SNAKE_CASE = feature_extractor(a , return_tensors='np') SCREAMING_SNAKE_CASE = processor(audios=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 SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) SCREAMING_SNAKE_CASE = 'This is a test string' SCREAMING_SNAKE_CASE = processor(text=a) SCREAMING_SNAKE_CASE = tokenizer(a) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key]) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=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 SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: SCREAMING_SNAKE_CASE = self.get_feature_extractor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=a , feature_extractor=a) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
327
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
352
import argparse import datetime def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = { '0': 'Sunday', '1': 'Monday', '2': 'Tuesday', '3': 'Wednesday', '4': 'Thursday', '5': 'Friday', '6': 'Saturday', } SCREAMING_SNAKE_CASE = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_UpperCAmelCase) < 11: raise ValueError('Must be 10 characters long') # Get month SCREAMING_SNAKE_CASE = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError('Month must be between 1 - 12') SCREAMING_SNAKE_CASE = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get day SCREAMING_SNAKE_CASE = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError('Date must be between 1 - 31') # Get second separator SCREAMING_SNAKE_CASE = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError('Date separator must be \'-\' or \'/\'') # Get year SCREAMING_SNAKE_CASE = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( 'Year out of range. There has to be some sort of limit...right?') # Get datetime obj for validation SCREAMING_SNAKE_CASE = datetime.date(int(_UpperCAmelCase) , int(_UpperCAmelCase) , int(_UpperCAmelCase)) # Start math if m <= 2: SCREAMING_SNAKE_CASE = y - 1 SCREAMING_SNAKE_CASE = m + 12 # maths var SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[:2]) SCREAMING_SNAKE_CASE = int(str(_UpperCAmelCase)[2:]) SCREAMING_SNAKE_CASE = int(2.6 * m - 5.39) SCREAMING_SNAKE_CASE = int(c / 4) SCREAMING_SNAKE_CASE = int(k / 4) SCREAMING_SNAKE_CASE = int(d + k) SCREAMING_SNAKE_CASE = int(t + u + v + x) SCREAMING_SNAKE_CASE = int(z - (2 * c)) SCREAMING_SNAKE_CASE = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError('The date was evaluated incorrectly. Contact developer.') # Response SCREAMING_SNAKE_CASE = F'''Your date {date_input}, is a {days[str(_UpperCAmelCase)]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() a_ : Tuple = argparse.ArgumentParser( description=( 'Find out what day of the week nearly any date is or was. Enter ' 'date as a string in the mm-dd-yyyy or mm/dd/yyyy format' ) ) parser.add_argument( 'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)' ) a_ : Any = parser.parse_args() zeller(args.date_input)
327
0
"""simple docstring""" from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _snake_case ( A__ ): def __init__( self , a , a = None , a = None , a = True , a = None , a = False , a = None , a = True , a = "arrow" , **a , ) -> Optional[int]: super().__init__( split=a , features=a , cache_dir=a , keep_in_memory=a , streaming=a , **a , ) SCREAMING_SNAKE_CASE = load_from_cache_file SCREAMING_SNAKE_CASE = file_format SCREAMING_SNAKE_CASE = Spark( df=a , features=a , cache_dir=a , working_dir=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: if self.streaming: return self.builder.as_streaming_dataset(split=self.split) SCREAMING_SNAKE_CASE = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=a , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split)
353
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 convert_to_rgb, 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 if is_vision_available(): import PIL a_ : Optional[Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : Optional[int] = ['''pixel_values'''] def __init__( self , a = True , a = None , a = PILImageResampling.BICUBIC , a = True , a = 1 / 255 , a = True , a = None , a = None , a = True , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = size if size is not None else {'height': 384, 'width': 384} SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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_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 SCREAMING_SNAKE_CASE__ ( self , a , a , a = PILImageResampling.BICUBIC , a = None , **a , ) -> np.ndarray: SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=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()}''') SCREAMING_SNAKE_CASE = (size['height'], size['width']) return resize(a , size=a , resample=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a , ) -> Optional[Any]: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a = None , **a , ) -> np.ndarray: return normalize(a , mean=a , std=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image: 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_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 = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(a , default_to_square=a) 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 or resample is None: raise ValueError('Size and resample 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_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_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 = BatchFeature(data={'pixel_values': images} , tensor_type=a) return encoded_outputs
327
0
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() a_ : int = logging.get_logger(__name__) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = UniSpeechSatForSequenceClassification.from_pretrained(_UpperCAmelCase , config=_UpperCAmelCase) 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 lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = UniSpeechSatForAudioFrameClassification.from_pretrained(_UpperCAmelCase , config=_UpperCAmelCase) SCREAMING_SNAKE_CASE = downstream_dict['model.linear.weight'] SCREAMING_SNAKE_CASE = downstream_dict['model.linear.bias'] return model def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = UniSpeechSatForXVector.from_pretrained(_UpperCAmelCase , config=_UpperCAmelCase) 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 lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = checkpoint['Downstream'] SCREAMING_SNAKE_CASE = UniSpeechSatConfig.from_pretrained(_UpperCAmelCase) SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained( _UpperCAmelCase , return_attention_mask=_UpperCAmelCase , do_normalize=_UpperCAmelCase) SCREAMING_SNAKE_CASE = hf_config.architectures[0] if arch.endswith('ForSequenceClassification'): SCREAMING_SNAKE_CASE = convert_classification(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) elif arch.endswith('ForAudioFrameClassification'): SCREAMING_SNAKE_CASE = convert_diarization(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) elif arch.endswith('ForXVector'): SCREAMING_SNAKE_CASE = convert_xvector(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase) 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(_UpperCAmelCase) hf_model.save_pretrained(_UpperCAmelCase) if __name__ == "__main__": a_ : List[Any] = 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.') a_ : Tuple = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
354
class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self , a) -> str: if self.val: if val < self.val: if self.left is None: SCREAMING_SNAKE_CASE = Node(a) else: self.left.insert(a) elif val > self.val: if self.right is None: SCREAMING_SNAKE_CASE = Node(a) else: self.right.insert(a) else: SCREAMING_SNAKE_CASE = val def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): # Recursive traversal if root: inorder(root.left , _UpperCAmelCase) res.append(root.val) inorder(root.right , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase): # Build BST if len(_UpperCAmelCase) == 0: return arr SCREAMING_SNAKE_CASE = Node(arr[0]) for i in range(1 , len(_UpperCAmelCase)): root.insert(arr[i]) # Traverse BST in order. SCREAMING_SNAKE_CASE = [] inorder(_UpperCAmelCase , _UpperCAmelCase) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
327
0
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class _snake_case ( A__ ): _lowercase : Tuple = '''''' _lowercase : Optional[int] = '''hf-legacy''' # "hf://"" is reserved for hffs def __init__( self , a = None , a = None , **a , ) -> Any: super().__init__(self , **a) SCREAMING_SNAKE_CASE = repo_info SCREAMING_SNAKE_CASE = token SCREAMING_SNAKE_CASE = None def SCREAMING_SNAKE_CASE__ ( self) -> Dict: if self.dir_cache is None: SCREAMING_SNAKE_CASE = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes SCREAMING_SNAKE_CASE = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(a): {'name': str(a), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename).parents)[:-1] }) def SCREAMING_SNAKE_CASE__ ( self , a , a = "rb" , **a , ) -> Tuple: if not isinstance(self.repo_info , a): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''') SCREAMING_SNAKE_CASE = hf_hub_url(self.repo_info.id , a , revision=self.repo_info.sha) return fsspec.open( a , mode=a , headers=get_authentication_headers_for_url(a , use_auth_token=self.token) , client_kwargs={'trust_env': True} , ).open() def SCREAMING_SNAKE_CASE__ ( self , a , **a) -> List[Any]: self._get_dirs() SCREAMING_SNAKE_CASE = self._strip_protocol(a) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(a) def SCREAMING_SNAKE_CASE__ ( self , a , a=False , **a) -> List[str]: self._get_dirs() SCREAMING_SNAKE_CASE = PurePosixPath(path.strip('/')) SCREAMING_SNAKE_CASE = {} for p, f in self.dir_cache.items(): SCREAMING_SNAKE_CASE = PurePosixPath(p.strip('/')) SCREAMING_SNAKE_CASE = p.parent if root == path: SCREAMING_SNAKE_CASE = f SCREAMING_SNAKE_CASE = list(paths.values()) if detail: return out else: return sorted(f['name'] for f in out)
355
import argparse import gc import json import os import re import torch from huggingface_hub import hf_hub_download from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint a_ : Optional[int] = { '169M': 12, '430M': 24, '1B5': 24, '3B': 32, '7B': 32, '14B': 40, } a_ : Optional[int] = { '169M': 7_68, '430M': 10_24, '1B5': 20_48, '3B': 25_60, '7B': 40_96, '14B': 51_20, } def lowerCamelCase__ (_UpperCAmelCase): SCREAMING_SNAKE_CASE = list(state_dict.keys()) for name in state_dict_keys: SCREAMING_SNAKE_CASE = state_dict.pop(_UpperCAmelCase) # emb -> embedding if name.startswith('emb.'): SCREAMING_SNAKE_CASE = name.replace('emb.' , 'embeddings.') # ln_0 -> pre_ln (only present at block 0) if name.startswith('blocks.0.ln0'): SCREAMING_SNAKE_CASE = name.replace('blocks.0.ln0' , 'blocks.0.pre_ln') # att -> attention SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.att' , R'blocks.\1.attention' , _UpperCAmelCase) # ffn -> feed_forward SCREAMING_SNAKE_CASE = re.sub(R'blocks\.(\d+)\.ffn' , R'blocks.\1.feed_forward' , _UpperCAmelCase) # time_mix_k -> time_mix_key and reshape if name.endswith('.time_mix_k'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_k' , '.time_mix_key') # time_mix_v -> time_mix_value and reshape if name.endswith('.time_mix_v'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_v' , '.time_mix_value') # time_mix_r -> time_mix_key and reshape if name.endswith('.time_mix_r'): SCREAMING_SNAKE_CASE = name.replace('.time_mix_r' , '.time_mix_receptance') if name != "head.weight": SCREAMING_SNAKE_CASE = 'rwkv.' + name SCREAMING_SNAKE_CASE = weight return state_dict def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=False , _UpperCAmelCase=None): # 1. If possible, build the tokenizer. if tokenizer_file is None: print('No `--tokenizer_file` provided, we will use the default tokenizer.') SCREAMING_SNAKE_CASE = 5_0277 SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b') else: SCREAMING_SNAKE_CASE = PreTrainedTokenizerFast(tokenizer_file=_UpperCAmelCase) SCREAMING_SNAKE_CASE = len(_UpperCAmelCase) tokenizer.save_pretrained(_UpperCAmelCase) # 2. Build the config SCREAMING_SNAKE_CASE = list(NUM_HIDDEN_LAYERS_MAPPING.keys()) if size is None: # Try to infer size from the checkpoint name for candidate in possible_sizes: if candidate in checkpoint_file: SCREAMING_SNAKE_CASE = candidate break if size is None: raise ValueError('Could not infer the size, please provide it with the `--size` argument.') if size not in possible_sizes: raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.''') SCREAMING_SNAKE_CASE = RwkvConfig( vocab_size=_UpperCAmelCase , num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size] , hidden_size=HIDEN_SIZE_MAPPING[size] , ) config.save_pretrained(_UpperCAmelCase) # 3. Download model file then convert state_dict SCREAMING_SNAKE_CASE = hf_hub_download(_UpperCAmelCase , _UpperCAmelCase) SCREAMING_SNAKE_CASE = torch.load(_UpperCAmelCase , map_location='cpu') SCREAMING_SNAKE_CASE = convert_state_dict(_UpperCAmelCase) # 4. Split in shards and save SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = shard_checkpoint(_UpperCAmelCase) for shard_file, shard in shards.items(): torch.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) if index is not None: SCREAMING_SNAKE_CASE = os.path.join(_UpperCAmelCase , _UpperCAmelCase) # Save the index as well with open(_UpperCAmelCase , 'w' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = json.dumps(_UpperCAmelCase , indent=2 , sort_keys=_UpperCAmelCase) + '\n' f.write(_UpperCAmelCase) # 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict print( 'Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.') SCREAMING_SNAKE_CASE = list(shards.keys()) del state_dict del shards gc.collect() for shard_file in shard_files: SCREAMING_SNAKE_CASE = torch.load(os.path.join(_UpperCAmelCase , _UpperCAmelCase)) torch.save({k: v.cpu().clone() for k, v in state_dict.items()} , os.path.join(_UpperCAmelCase , _UpperCAmelCase)) del state_dict gc.collect() if push_to_hub: if model_name is None: raise ValueError('Please provide a `model_name` to push the model to the Hub.') SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(_UpperCAmelCase) model.push_to_hub(_UpperCAmelCase , max_shard_size='2GB') tokenizer.push_to_hub(_UpperCAmelCase) if __name__ == "__main__": a_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--repo_id', default=None, type=str, required=True, help='Repo ID from which to pull the checkpoint.' ) parser.add_argument( '--checkpoint_file', default=None, type=str, required=True, help='Name of the checkpoint file in the repo.' ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='Where to save the converted model.' ) parser.add_argument( '--tokenizer_file', default=None, type=str, help='Path to the tokenizer file to use (if not provided, only the model is converted).', ) parser.add_argument( '--size', default=None, type=str, help='Size of the model. Will be inferred from the `checkpoint_file` if not passed.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Push to the Hub the converted model.', ) parser.add_argument( '--model_name', default=None, type=str, help='Name of the pushed model on the Hub, including the username / organization.', ) a_ : Tuple = parser.parse_args() convert_rmkv_checkpoint_to_hf_format( args.repo_id, args.checkpoint_file, args.output_dir, size=args.size, tokenizer_file=args.tokenizer_file, push_to_hub=args.push_to_hub, model_name=args.model_name, )
327
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , a , a=7 , a=3 , a=30 , a=400 , a=True , a=None , a=True , a=[0.5, 0.5, 0.5] , a=[0.5, 0.5, 0.5] , a=True , a=1 / 255 , a=True , ) -> Optional[Any]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = min_resolution SCREAMING_SNAKE_CASE = max_resolution SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = do_normalize SCREAMING_SNAKE_CASE = image_mean SCREAMING_SNAKE_CASE = image_std SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE__ ( self , a , a=False) -> Any: if not batched: SCREAMING_SNAKE_CASE = image_inputs[0] if isinstance(a , Image.Image): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.size else: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE = int(self.size['shortest_edge'] * h / w) SCREAMING_SNAKE_CASE = self.size['shortest_edge'] elif w > h: SCREAMING_SNAKE_CASE = self.size['shortest_edge'] SCREAMING_SNAKE_CASE = int(self.size['shortest_edge'] * w / h) else: SCREAMING_SNAKE_CASE = self.size['shortest_edge'] SCREAMING_SNAKE_CASE = self.size['shortest_edge'] else: SCREAMING_SNAKE_CASE = [] for image in image_inputs: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[0])[0] SCREAMING_SNAKE_CASE = max(a , key=lambda a: item[1])[1] return expected_height, expected_width @require_torch @require_vision class _snake_case ( A__ , unittest.TestCase ): _lowercase : Dict = DetaImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self) -> Any: SCREAMING_SNAKE_CASE = DetaImageProcessingTester(self) @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(a , 'image_mean')) self.assertTrue(hasattr(a , 'image_std')) self.assertTrue(hasattr(a , 'do_normalize')) self.assertTrue(hasattr(a , 'do_resize')) self.assertTrue(hasattr(a , 'do_rescale')) self.assertTrue(hasattr(a , 'do_pad')) self.assertTrue(hasattr(a , 'size')) def SCREAMING_SNAKE_CASE__ ( self) -> str: SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333}) self.assertEqual(image_processor.do_pad , a) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: # 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 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) 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, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> Tuple: # 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 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: # 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 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE = image_processing(a , return_tensors='pt').pixel_values SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.image_processor_tester.get_expected_values(a , batched=a) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: # prepare image and target SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r') as f: SCREAMING_SNAKE_CASE = json.loads(f.read()) SCREAMING_SNAKE_CASE = {'image_id': 3_9769, 'annotations': target} # encode them SCREAMING_SNAKE_CASE = DetaImageProcessor() SCREAMING_SNAKE_CASE = image_processing(images=a , annotations=a , return_tensors='pt') # verify pixel values SCREAMING_SNAKE_CASE = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding['pixel_values'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.27_96, 0.31_38, 0.34_81]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , a , atol=1E-4)) # verify area SCREAMING_SNAKE_CASE = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , a)) # verify boxes SCREAMING_SNAKE_CASE = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , a , atol=1E-3)) # verify image_id SCREAMING_SNAKE_CASE = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , a)) # verify is_crowd SCREAMING_SNAKE_CASE = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , a)) # verify class_labels SCREAMING_SNAKE_CASE = torch.tensor([75, 75, 63, 65, 17, 17]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , a)) # verify orig_size SCREAMING_SNAKE_CASE = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , a)) # verify size SCREAMING_SNAKE_CASE = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , a)) @slow def SCREAMING_SNAKE_CASE__ ( self) -> Dict: # prepare image, target and masks_path SCREAMING_SNAKE_CASE = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png') with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r') as f: SCREAMING_SNAKE_CASE = json.loads(f.read()) SCREAMING_SNAKE_CASE = {'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target} SCREAMING_SNAKE_CASE = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic') # encode them SCREAMING_SNAKE_CASE = DetaImageProcessor(format='coco_panoptic') SCREAMING_SNAKE_CASE = image_processing(images=a , annotations=a , masks_path=a , return_tensors='pt') # verify pixel values SCREAMING_SNAKE_CASE = torch.Size([1, 3, 800, 1066]) self.assertEqual(encoding['pixel_values'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.27_96, 0.31_38, 0.34_81]) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , a , atol=1E-4)) # verify area SCREAMING_SNAKE_CASE = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147]) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , a)) # verify boxes SCREAMING_SNAKE_CASE = torch.Size([6, 4]) self.assertEqual(encoding['labels'][0]['boxes'].shape , a) SCREAMING_SNAKE_CASE = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25]) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , a , atol=1E-3)) # verify image_id SCREAMING_SNAKE_CASE = torch.tensor([3_9769]) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , a)) # verify is_crowd SCREAMING_SNAKE_CASE = torch.tensor([0, 0, 0, 0, 0, 0]) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , a)) # verify class_labels SCREAMING_SNAKE_CASE = torch.tensor([17, 17, 63, 75, 75, 93]) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , a)) # verify masks SCREAMING_SNAKE_CASE = 82_2873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , a) # verify orig_size SCREAMING_SNAKE_CASE = torch.tensor([480, 640]) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , a)) # verify size SCREAMING_SNAKE_CASE = torch.tensor([800, 1066]) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , a))
356
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): monkeypatch.setattr('datasets.utils.deprecation_utils._emitted_deprecation_warnings' , set()) @pytest.fixture def lowerCamelCase__ (_UpperCAmelCase): class _snake_case : def __init__( self , a) -> List[Any]: SCREAMING_SNAKE_CASE = metric_id class _snake_case : _lowercase : Optional[Any] = [MetricMock(A__ ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return self._metrics monkeypatch.setattr('datasets.inspect.huggingface_hub' , HfhMock()) @pytest.mark.parametrize( 'func, args' , [(load_metric, ('metrics/mse',)), (list_metrics, ()), (inspect_metric, ('metrics/mse', 'tmp_path'))]) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): if "tmp_path" in args: SCREAMING_SNAKE_CASE = tuple(arg if arg != 'tmp_path' else tmp_path for arg in args) with pytest.warns(_UpperCAmelCase , match='https://huggingface.co/docs/evaluate'): func(*_UpperCAmelCase)
327
0
"""simple docstring""" import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets a_ : Optional[Any] = '\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n' a_ : Any = '\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy.\n' a_ : List[str] = R'\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting "1/2" to "\\frac{1}{2}")\n\nExamples:\n >>> metric = datasets.load_metric("competition_math")\n >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"])\n >>> print(results)\n {\'accuracy\': 1.0}\n' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string'), 'references': datasets.Value('string'), }) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Optional[int]: SCREAMING_SNAKE_CASE = 0.0 for i, j in zip(a , a): n_correct += 1.0 if math_equivalence.is_equiv(a , a) else 0.0 SCREAMING_SNAKE_CASE = n_correct / len(a) return { "accuracy": accuracy, }
357
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available a_ : Any = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Dict = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys a_ : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
327
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ : List[Any] = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Tuple = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys a_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
358
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a_ : List[Any] = logging.get_logger(__name__) a_ : Union[str, Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} a_ : str = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } a_ : List[Any] = {'allegro/herbert-base-cased': 5_14} a_ : Dict = {} class _snake_case ( A__ ): _lowercase : Dict = VOCAB_FILES_NAMES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Any = PRETRAINED_INIT_CONFIGURATION _lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : Any = HerbertTokenizer def __init__( self , a=None , a=None , a=None , a="<s>" , a="<unk>" , a="<pad>" , a="<mask>" , a="</s>" , **a , ) -> Dict: super().__init__( a , a , tokenizer_file=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , sep_token=a , **a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a , token_ids_a=a , already_has_special_tokens=a) if token_ids_a is None: return [1] + ([0] * len(a)) + [1] return [1] + ([0] * len(a)) + [1] + ([0] * len(a)) + [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> List[int]: 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) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE__ ( self , a , a = None) -> Tuple[str]: SCREAMING_SNAKE_CASE = self._tokenizer.model.save(a , name=a) return tuple(a)
327
0
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version a_ : List[str] = version.parse(importlib_metadata.version('nltk')) if NLTK_VERSION >= version.Version('3.6.4'): from nltk import word_tokenize a_ : Any = '\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n' a_ : int = '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n' a_ : Any = '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n \'meteor\': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric(\'meteor\')\n >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results["meteor"], 4))\n 0.6944\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence'), 'references': datasets.Value('string' , id='sequence'), }) , codebase_urls=['https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py'] , reference_urls=[ 'https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score', 'https://en.wikipedia.org/wiki/METEOR', ] , ) def SCREAMING_SNAKE_CASE__ ( self , a) -> int: import nltk nltk.download('wordnet') if NLTK_VERSION >= version.Version('3.6.5'): nltk.download('punkt') if NLTK_VERSION >= version.Version('3.6.6'): nltk.download('omw-1.4') def SCREAMING_SNAKE_CASE__ ( self , a , a , a=0.9 , a=3 , a=0.5) -> Optional[Any]: if NLTK_VERSION >= version.Version('3.6.5'): SCREAMING_SNAKE_CASE = [ meteor_score.single_meteor_score( word_tokenize(a) , word_tokenize(a) , alpha=a , beta=a , gamma=a) for ref, pred in zip(a , a) ] else: SCREAMING_SNAKE_CASE = [ meteor_score.single_meteor_score(a , a , alpha=a , beta=a , gamma=a) for ref, pred in zip(a , a) ] return {"meteor": np.mean(a)}
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) self.log(a) else: SCREAMING_SNAKE_CASE = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , a) return metrics def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_test_dataloader(a) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , 'predict') SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
360
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a_ : Union[str, Any] = logging.get_logger(__name__) class _snake_case ( A__ ): _lowercase : List[str] = ['''pixel_values'''] def __init__( self , a = True , a = 1 / 255 , a = True , a = 8 , **a , ) -> None: super().__init__(**a) SCREAMING_SNAKE_CASE = do_rescale SCREAMING_SNAKE_CASE = rescale_factor SCREAMING_SNAKE_CASE = do_pad SCREAMING_SNAKE_CASE = pad_size def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None , **a) -> np.ndarray: return rescale(a , scale=a , data_format=a , **a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a = None) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_image_size(a) SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(a , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a) def SCREAMING_SNAKE_CASE__ ( self , a , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> List[str]: 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_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(a) for image in images] if do_rescale: SCREAMING_SNAKE_CASE = [self.rescale(image=a , scale=a) for image in images] if do_pad: SCREAMING_SNAKE_CASE = [self.pad(a , size=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)
327
0