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
"""simple docstring""" def _A ( lowercase , lowercase ): """simple docstring""" print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' ) for i in range(_A ): for j in range(_A ): if dist[i][j] != float('''inf''' ): print(int(dist[i][j] ) , end='''\t''' ) else: print('''INF''' , end='''\t''' ) print() def _A ( lowercase , lowercase ): """simple docstring""" a =[[float('''inf''' ) for _ in range(_A )] for _ in range(_A )] for i in range(_A ): for j in range(_A ): a =graph[i][j] # check vertex k against all other vertices (i, j) for k in range(_A ): # looping through rows of graph array for i in range(_A ): # looping through columns of graph array for j in range(_A ): if ( dist[i][k] != float('''inf''' ) and dist[k][j] != float('''inf''' ) and dist[i][k] + dist[k][j] < dist[i][j] ): a =dist[i][k] + dist[k][j] _print_dist(_A , _A ) return dist, v if __name__ == "__main__": lowerCamelCase_ : Tuple = int(input("""Enter number of vertices: """)) lowerCamelCase_ : int = int(input("""Enter number of edges: """)) lowerCamelCase_ : Dict = [[float("""inf""") for i in range(v)] for j in range(v)] for i in range(v): lowerCamelCase_ : Optional[Any] = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("""\nEdge """, i + 1) lowerCamelCase_ : List[str] = int(input("""Enter source:""")) lowerCamelCase_ : int = int(input("""Enter destination:""")) lowerCamelCase_ : Union[str, Any] = float(input("""Enter weight:""")) lowerCamelCase_ : Dict = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
81
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE( a_ ): _UpperCAmelCase = ["pixel_values"] def __init__( self: List[Any] , UpperCamelCase: bool = True , UpperCamelCase: Optional[Dict[str, int]] = None , UpperCamelCase: PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase: bool = True , UpperCamelCase: Dict[str, int] = None , UpperCamelCase: bool = True , UpperCamelCase: Union[int, float] = 1 / 2_55 , UpperCamelCase: bool = True , UpperCamelCase: Optional[Union[float, List[float]]] = None , UpperCamelCase: Optional[Union[float, List[float]]] = None , **UpperCamelCase: Optional[int] , ) -> None: super().__init__(**UpperCamelCase ) snake_case__ = size if size is not None else {'shortest_edge': 2_56} snake_case__ = get_size_dict(UpperCamelCase , default_to_square=UpperCamelCase ) snake_case__ = crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24} snake_case__ = get_size_dict(UpperCamelCase ) snake_case__ = do_resize snake_case__ = size snake_case__ = resample snake_case__ = do_center_crop snake_case__ = crop_size snake_case__ = do_rescale snake_case__ = rescale_factor snake_case__ = do_normalize snake_case__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCAmelCase_ ( self: Tuple , UpperCamelCase: np.ndarray , UpperCamelCase: Dict[str, int] , UpperCamelCase: PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase: Dict , ) -> np.ndarray: snake_case__ = get_size_dict(UpperCamelCase , default_to_square=UpperCamelCase ) if "shortest_edge" not in size: raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) snake_case__ = get_resize_output_image_size(UpperCamelCase , size=size['shortest_edge'] , default_to_square=UpperCamelCase ) return resize(UpperCamelCase , size=UpperCamelCase , resample=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def lowerCAmelCase_ ( self: List[Any] , UpperCamelCase: np.ndarray , UpperCamelCase: Dict[str, int] , UpperCamelCase: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase: List[Any] , ) -> np.ndarray: snake_case__ = get_size_dict(UpperCamelCase ) return center_crop(UpperCamelCase , size=(size['height'], size['width']) , data_format=UpperCamelCase , **UpperCamelCase ) def lowerCAmelCase_ ( self: Union[str, Any] , UpperCamelCase: np.ndarray , UpperCamelCase: float , UpperCamelCase: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase: Dict ) -> np.ndarray: return rescale(UpperCamelCase , scale=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def lowerCAmelCase_ ( self: Optional[Any] , UpperCamelCase: np.ndarray , UpperCamelCase: Union[float, List[float]] , UpperCamelCase: Union[float, List[float]] , UpperCamelCase: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase: Any , ) -> np.ndarray: return normalize(UpperCamelCase , mean=UpperCamelCase , std=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def lowerCAmelCase_ ( self: Any , UpperCamelCase: ImageInput , UpperCamelCase: Optional[bool] = None , UpperCamelCase: Dict[str, int] = None , UpperCamelCase: PILImageResampling = None , UpperCamelCase: bool = None , UpperCamelCase: Dict[str, int] = None , UpperCamelCase: Optional[bool] = None , UpperCamelCase: Optional[float] = None , UpperCamelCase: Optional[bool] = None , UpperCamelCase: Optional[Union[float, List[float]]] = None , UpperCamelCase: Optional[Union[float, List[float]]] = None , UpperCamelCase: Optional[Union[str, TensorType]] = None , UpperCamelCase: Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase: Any , ) -> Optional[Any]: snake_case__ = do_resize if do_resize is not None else self.do_resize snake_case__ = size if size is not None else self.size snake_case__ = get_size_dict(UpperCamelCase , default_to_square=UpperCamelCase ) snake_case__ = resample if resample is not None else self.resample snake_case__ = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case__ = crop_size if crop_size is not None else self.crop_size snake_case__ = get_size_dict(UpperCamelCase ) snake_case__ = do_rescale if do_rescale is not None else self.do_rescale snake_case__ = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case__ = do_normalize if do_normalize is not None else self.do_normalize snake_case__ = image_mean if image_mean is not None else self.image_mean snake_case__ = image_std if image_std is not None else self.image_std snake_case__ = make_list_of_images(UpperCamelCase ) if not valid_images(UpperCamelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. snake_case__ = [to_numpy_array(UpperCamelCase ) for image in images] if do_resize: snake_case__ = [self.resize(image=UpperCamelCase , size=UpperCamelCase , resample=UpperCamelCase ) for image in images] if do_center_crop: snake_case__ = [self.center_crop(image=UpperCamelCase , size=UpperCamelCase ) for image in images] if do_rescale: snake_case__ = [self.rescale(image=UpperCamelCase , scale=UpperCamelCase ) for image in images] if do_normalize: snake_case__ = [self.normalize(image=UpperCamelCase , mean=UpperCamelCase , std=UpperCamelCase ) for image in images] snake_case__ = [to_channel_dimension_format(UpperCamelCase , UpperCamelCase ) for image in images] snake_case__ = {'pixel_values': images} return BatchFeature(data=UpperCamelCase , tensor_type=UpperCamelCase )
307
0
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="""%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s""", datefmt="""%Y-%m-%d %H:%M:%S""", level=os.environ.get("""LOGLEVEL""", """INFO""").upper(), stream=sys.stdout, ) UpperCamelCase = logging.getLogger(__name__) UpperCamelCase = {'facebook/bart-base': BartForConditionalGeneration} UpperCamelCase = {'facebook/bart-base': BartTokenizer} def _SCREAMING_SNAKE_CASE ( ): A_ : Tuple = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' ) parser.add_argument( '''--validation_file''' , type=snake_case_ , default=snake_case_ , help='''A csv or a json file containing the validation data.''' ) parser.add_argument( '''--max_length''' , type=snake_case_ , default=5 , help='''The maximum total input sequence length after tokenization.''' , ) parser.add_argument( '''--num_beams''' , type=snake_case_ , default=snake_case_ , help=( '''Number of beams to use for evaluation. This argument will be ''' '''passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.''' ) , ) parser.add_argument( '''--model_name_or_path''' , type=snake_case_ , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=snake_case_ , ) parser.add_argument( '''--config_name''' , type=snake_case_ , default=snake_case_ , help='''Pretrained config name or path if not the same as model_name''' , ) parser.add_argument( '''--device''' , type=snake_case_ , default='''cpu''' , help='''Device where the model will be run''' , ) parser.add_argument('''--output_file_path''' , type=snake_case_ , default=snake_case_ , help='''Where to store the final ONNX file.''' ) A_ : Optional[Any] = parser.parse_args() return args def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="cpu" ): A_ : int = model_dict[model_name].from_pretrained(snake_case_ ).to(snake_case_ ) A_ : List[str] = tokenizer_dict[model_name].from_pretrained(snake_case_ ) if model_name in ["facebook/bart-base"]: A_ : List[str] = 0 A_ : List[Any] = None A_ : List[str] = 0 return huggingface_model, tokenizer def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): model.eval() A_ : List[Any] = None A_ : List[str] = torch.jit.script(BARTBeamSearchGenerator(snake_case_ ) ) with torch.no_grad(): A_ : Optional[int] = '''My friends are cool but they eat too many carbs.''' A_ : Optional[int] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1_024 , return_tensors='''pt''' ).to(model.device ) A_ : int = model.generate( inputs['''input_ids'''] , attention_mask=inputs['''attention_mask'''] , num_beams=snake_case_ , max_length=snake_case_ , early_stopping=snake_case_ , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( snake_case_ , ( inputs['''input_ids'''], inputs['''attention_mask'''], num_beams, max_length, model.config.decoder_start_token_id, ) , snake_case_ , opset_version=14 , input_names=['''input_ids''', '''attention_mask''', '''num_beams''', '''max_length''', '''decoder_start_token_id'''] , output_names=['''output_ids'''] , dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''seq'''}, '''output_ids''': {0: '''batch''', 1: '''seq_out'''}, } , example_outputs=snake_case_ , ) logger.info('''Model exported to {}'''.format(snake_case_ ) ) A_ : List[Any] = remove_dup_initializers(os.path.abspath(snake_case_ ) ) logger.info('''Deduplicated and optimized model written to {}'''.format(snake_case_ ) ) A_ : int = onnxruntime.InferenceSession(snake_case_ ) A_ : Optional[Any] = ort_sess.run( snake_case_ , { '''input_ids''': inputs['''input_ids'''].cpu().numpy(), '''attention_mask''': inputs['''attention_mask'''].cpu().numpy(), '''num_beams''': np.array(snake_case_ ), '''max_length''': np.array(snake_case_ ), '''decoder_start_token_id''': np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 ) logger.info('''Model outputs from torch and ONNX Runtime are similar.''' ) logger.info('''Success.''' ) def _SCREAMING_SNAKE_CASE ( ): A_ : Union[str, Any] = parse_args() A_ : List[str] = 5 A_ : str = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() A_ : int = torch.device(args.device ) A_ , A_ : int = load_model_tokenizer(args.model_name_or_path , snake_case_ ) if model.config.decoder_start_token_id is None: raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' ) model.to(snake_case_ ) if args.max_length: A_ : Optional[Any] = args.max_length if args.num_beams: A_ : List[str] = args.num_beams if args.output_file_path: A_ : Union[str, Any] = args.output_file_path else: A_ : Dict = '''BART.onnx''' logger.info('''Exporting model to ONNX''' ) export_and_validate_model(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) if __name__ == "__main__": main()
367
from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = ["image_processor"] snake_case = "SamImageProcessor" def __init__( self , _SCREAMING_SNAKE_CASE )->Union[str, Any]: '''simple docstring''' super().__init__(_SCREAMING_SNAKE_CASE ) A_ : Any = self.image_processor A_ : Optional[int] = -10 A_ : List[Any] = self.image_processor.size['''longest_edge'''] def __call__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )->BatchEncoding: '''simple docstring''' A_ : Union[str, Any] = self.image_processor( _SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) # pop arguments that are not used in the foward but used nevertheless A_ : Tuple = encoding_image_processor['''original_sizes'''] if hasattr(_SCREAMING_SNAKE_CASE , '''numpy''' ): # Checks if Torch or TF tensor A_ : int = original_sizes.numpy() A_ , A_ , A_ : str = self._check_and_preprocess_points( input_points=_SCREAMING_SNAKE_CASE , input_labels=_SCREAMING_SNAKE_CASE , input_boxes=_SCREAMING_SNAKE_CASE , ) A_ : Optional[Any] = self._normalize_and_convert( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , input_points=_SCREAMING_SNAKE_CASE , input_labels=_SCREAMING_SNAKE_CASE , input_boxes=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , ) return encoding_image_processor def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="pt" , )->Dict: '''simple docstring''' if input_points is not None: if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): A_ : Optional[Any] = [ self._normalize_coordinates(self.target_size , _SCREAMING_SNAKE_CASE , original_sizes[0] ) for point in input_points ] else: A_ : str = [ self._normalize_coordinates(self.target_size , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for point, original_size in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points ): if input_labels is not None: A_ , A_ : Optional[Any] = self._pad_points_and_labels(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : List[str] = np.array(_SCREAMING_SNAKE_CASE ) if input_labels is not None: A_ : Dict = np.array(_SCREAMING_SNAKE_CASE ) if input_boxes is not None: if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): A_ : Tuple = [ self._normalize_coordinates(self.target_size , _SCREAMING_SNAKE_CASE , original_sizes[0] , is_bounding_box=_SCREAMING_SNAKE_CASE ) for box in input_boxes ] else: A_ : List[Any] = [ self._normalize_coordinates(self.target_size , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , is_bounding_box=_SCREAMING_SNAKE_CASE ) for box, original_size in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ] A_ : Union[str, Any] = np.array(_SCREAMING_SNAKE_CASE ) if input_boxes is not None: if return_tensors == "pt": A_ : Dict = torch.from_numpy(_SCREAMING_SNAKE_CASE ) # boxes batch size of 1 by default A_ : Optional[Any] = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes elif return_tensors == "tf": A_ : Optional[int] = tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) # boxes batch size of 1 by default A_ : List[Any] = tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) if len(input_boxes.shape ) != 3 else input_boxes encoding_image_processor.update({'''input_boxes''': input_boxes} ) if input_points is not None: if return_tensors == "pt": A_ : Union[str, Any] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) # point batch size of 1 by default A_ : Union[str, Any] = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points elif return_tensors == "tf": A_ : List[str] = tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) # point batch size of 1 by default A_ : Union[str, Any] = tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) if len(input_points.shape ) != 4 else input_points encoding_image_processor.update({'''input_points''': input_points} ) if input_labels is not None: if return_tensors == "pt": A_ : Optional[Any] = torch.from_numpy(_SCREAMING_SNAKE_CASE ) # point batch size of 1 by default A_ : List[Any] = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels elif return_tensors == "tf": A_ : int = tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) # point batch size of 1 by default A_ : List[Any] = tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) if len(input_labels.shape ) != 3 else input_labels encoding_image_processor.update({'''input_labels''': input_labels} ) return encoding_image_processor def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )->Dict: '''simple docstring''' A_ : Optional[Any] = max([point.shape[0] for point in input_points] ) A_ : int = [] for i, point in enumerate(_SCREAMING_SNAKE_CASE ): if point.shape[0] != expected_nb_points: A_ : Optional[int] = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 ) A_ : int = np.append(input_labels[i] , [self.point_pad_value] ) processed_input_points.append(_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = processed_input_points return input_points, input_labels def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )->np.ndarray: '''simple docstring''' A_ , A_ : str = original_size A_ , A_ : Dict = self.image_processor._get_preprocess_shape(_SCREAMING_SNAKE_CASE , longest_edge=_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = deepcopy(_SCREAMING_SNAKE_CASE ).astype(_SCREAMING_SNAKE_CASE ) if is_bounding_box: A_ : Union[str, Any] = coords.reshape(-1 , 2 , 2 ) A_ : Any = coords[..., 0] * (new_w / old_w) A_ : List[str] = coords[..., 1] * (new_h / old_h) if is_bounding_box: A_ : str = coords.reshape(-1 , 4 ) return coords def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , )->str: '''simple docstring''' if input_points is not None: if hasattr(_SCREAMING_SNAKE_CASE , '''numpy''' ): # Checks for TF or Torch tensor A_ : List[str] = input_points.numpy().tolist() if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not isinstance(input_points[0] , _SCREAMING_SNAKE_CASE ): raise ValueError('''Input points must be a list of list of floating points.''' ) A_ : Optional[Any] = [np.array(_SCREAMING_SNAKE_CASE ) for input_point in input_points] else: A_ : Tuple = None if input_labels is not None: if hasattr(_SCREAMING_SNAKE_CASE , '''numpy''' ): A_ : Dict = input_labels.numpy().tolist() if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not isinstance(input_labels[0] , _SCREAMING_SNAKE_CASE ): raise ValueError('''Input labels must be a list of list integers.''' ) A_ : Union[str, Any] = [np.array(_SCREAMING_SNAKE_CASE ) for label in input_labels] else: A_ : str = None if input_boxes is not None: if hasattr(_SCREAMING_SNAKE_CASE , '''numpy''' ): A_ : str = input_boxes.numpy().tolist() if ( not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not isinstance(input_boxes[0] , _SCREAMING_SNAKE_CASE ) or not isinstance(input_boxes[0][0] , _SCREAMING_SNAKE_CASE ) ): raise ValueError('''Input boxes must be a list of list of list of floating points.''' ) A_ : Tuple = [np.array(_SCREAMING_SNAKE_CASE ).astype(np.floataa ) for box in input_boxes] else: A_ : Dict = None return input_points, input_labels, input_boxes @property def _snake_case ( self )->List[str]: '''simple docstring''' A_ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(_SCREAMING_SNAKE_CASE ) ) def _snake_case ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )->Union[str, Any]: '''simple docstring''' return self.image_processor.post_process_masks(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
65
0
from functools import lru_cache def lowerCAmelCase_ (lowerCAmelCase__: int ): """simple docstring""" UpperCAmelCase_: List[str] = 2 UpperCAmelCase_: Union[str, Any] = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(lowerCAmelCase__ ) if n > 1: factors.add(lowerCAmelCase__ ) return factors @lru_cache def lowerCAmelCase_ (lowerCAmelCase__: int ): """simple docstring""" return len(unique_prime_factors(lowerCAmelCase__ ) ) def lowerCAmelCase_ (lowerCAmelCase__: list ): """simple docstring""" return len(set(lowerCAmelCase__ ) ) in (0, 1) def lowerCAmelCase_ (lowerCAmelCase__: int ): """simple docstring""" UpperCAmelCase_: int = 2 while True: # Increment each value of a generated range UpperCAmelCase_: List[str] = [base + i for i in range(lowerCAmelCase__ )] # Run elements through out unique_prime_factors function # Append our target number to the end. UpperCAmelCase_: Any = [upf_len(lowerCAmelCase__ ) for x in group] checker.append(lowerCAmelCase__ ) # If all numbers in the list are equal, return the group variable. if equality(lowerCAmelCase__ ): return group # Increment our base variable by 1 base += 1 def lowerCAmelCase_ (lowerCAmelCase__: int = 4 ): """simple docstring""" UpperCAmelCase_: str = run(lowerCAmelCase__ ) return results[0] if len(lowerCAmelCase__ ) else None if __name__ == "__main__": print(solution())
147
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py a : List[str] = 'src/diffusers' a : Optional[Any] = '.' # This is to make sure the diffusers module imported is the one in the repo. a : Dict = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) a : str = spec.loader.load_module() def lowerCAmelCase_ (lowerCAmelCase__: Optional[int] , lowerCAmelCase__: List[str] ): """simple docstring""" return line.startswith(lowerCAmelCase__ ) or len(lowerCAmelCase__ ) <= 1 or re.search(r"""^\s*\)(\s*->.*:|:)\s*$""" , lowerCAmelCase__ ) is not None def lowerCAmelCase_ (lowerCAmelCase__: str ): """simple docstring""" UpperCAmelCase_: Optional[Any] = object_name.split(""".""" ) UpperCAmelCase_: Tuple = 0 # First let's find the module where our object lives. UpperCAmelCase_: Union[str, Any] = parts[i] while i < len(lowerCAmelCase__ ) and not os.path.isfile(os.path.join(lowerCAmelCase__ , F'{module}.py' ) ): i += 1 if i < len(lowerCAmelCase__ ): UpperCAmelCase_: List[Any] = os.path.join(lowerCAmelCase__ , parts[i] ) if i >= len(lowerCAmelCase__ ): raise ValueError(F'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(lowerCAmelCase__ , F'{module}.py' ) , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCAmelCase_: List[Any] = f.readlines() # Now let's find the class / func in the code! UpperCAmelCase_: Any = """""" UpperCAmelCase_: Tuple = 0 for name in parts[i + 1 :]: while ( line_index < len(lowerCAmelCase__ ) and re.search(rF'^{indent}(class|def)\s+{name}(\(|\:)' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(lowerCAmelCase__ ): raise ValueError(F' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). UpperCAmelCase_: Dict = line_index while line_index < len(lowerCAmelCase__ ) and _should_continue(lines[line_index] , lowerCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCAmelCase_: Optional[int] = lines[start_index:line_index] return "".join(lowerCAmelCase__ ) a : List[str] = re.compile(r'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') a : Optional[int] = re.compile(r'^\s*(\S+)->(\S+)(\s+.*|$)') a : List[Any] = re.compile(r'<FILL\s+[^>]*>') def lowerCAmelCase_ (lowerCAmelCase__: Dict ): """simple docstring""" UpperCAmelCase_: Dict = code.split("""\n""" ) UpperCAmelCase_: Any = 0 while idx < len(lowerCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(lowerCAmelCase__ ): return re.search(r"""^(\s*)\S""" , lines[idx] ).groups()[0] return "" def lowerCAmelCase_ (lowerCAmelCase__: Union[str, Any] ): """simple docstring""" UpperCAmelCase_: str = len(get_indent(lowerCAmelCase__ ) ) > 0 if has_indent: UpperCAmelCase_: Union[str, Any] = F'class Bla:\n{code}' UpperCAmelCase_: int = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 , preview=lowerCAmelCase__ ) UpperCAmelCase_: int = black.format_str(lowerCAmelCase__ , mode=lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_: List[Any] = style_docstrings_in_code(lowerCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def lowerCAmelCase_ (lowerCAmelCase__: Tuple , lowerCAmelCase__: int=False ): """simple docstring""" with open(lowerCAmelCase__ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCAmelCase_: List[str] = f.readlines() UpperCAmelCase_: List[str] = [] UpperCAmelCase_: Tuple = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(lowerCAmelCase__ ): UpperCAmelCase_: Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: Any = search.groups() UpperCAmelCase_: str = find_code_in_diffusers(lowerCAmelCase__ ) UpperCAmelCase_: int = get_indent(lowerCAmelCase__ ) UpperCAmelCase_: Dict = line_index + 1 if indent == theoretical_indent else line_index + 2 UpperCAmelCase_: Tuple = theoretical_indent UpperCAmelCase_: Dict = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. UpperCAmelCase_: Tuple = True while line_index < len(lowerCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(lowerCAmelCase__ ): break UpperCAmelCase_: Any = lines[line_index] UpperCAmelCase_: Tuple = _should_continue(lowerCAmelCase__ , lowerCAmelCase__ ) and re.search(F'^{indent}# End copy' , lowerCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCAmelCase_: int = lines[start_index:line_index] UpperCAmelCase_: Union[str, Any] = """""".join(lowerCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies UpperCAmelCase_: int = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(lowerCAmelCase__ ) is None] UpperCAmelCase_: Union[str, Any] = """\n""".join(lowerCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(lowerCAmelCase__ ) > 0: UpperCAmelCase_: Any = replace_pattern.replace("""with""" , """""" ).split(""",""" ) UpperCAmelCase_: int = [_re_replace_pattern.search(lowerCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_: str = pattern.groups() UpperCAmelCase_: int = re.sub(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if option.strip() == "all-casing": UpperCAmelCase_: List[Any] = re.sub(obja.lower() , obja.lower() , lowerCAmelCase__ ) UpperCAmelCase_: Optional[int] = re.sub(obja.upper() , obja.upper() , lowerCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line UpperCAmelCase_: Union[str, Any] = blackify(lines[start_index - 1] + theoretical_code ) UpperCAmelCase_: Dict = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: UpperCAmelCase_: str = lines[:start_index] + [theoretical_code] + lines[line_index:] UpperCAmelCase_: Optional[int] = start_index + 1 if overwrite and len(lowerCAmelCase__ ) > 0: # Warn the user a file has been modified. print(F'Detected changes, rewriting {filename}.' ) with open(lowerCAmelCase__ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lowerCAmelCase__ ) return diffs def lowerCAmelCase_ (lowerCAmelCase__: bool = False ): """simple docstring""" UpperCAmelCase_: Dict = glob.glob(os.path.join(lowerCAmelCase__ , """**/*.py""" ) , recursive=lowerCAmelCase__ ) UpperCAmelCase_: Optional[Any] = [] for filename in all_files: UpperCAmelCase_: str = is_copy_consistent(lowerCAmelCase__ , lowerCAmelCase__ ) diffs += [F'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(lowerCAmelCase__ ) > 0: UpperCAmelCase_: Dict = """\n""".join(lowerCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": a : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') a : List[Any] = parser.parse_args() check_copies(args.fix_and_overwrite)
147
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase_ : Optional[int] = logging.get_logger(__name__) lowerCAmelCase_ : Any = { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/config.json''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/config.json''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json''' ), '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json''', '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json''' ), '''distilbert-base-uncased-finetuned-sst-2-english''': ( '''https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json''' ), } class UpperCamelCase_ ( a_ ): _A : Union[str, Any] = 'distilbert' _A : Any = { 'hidden_size': 'dim', 'num_attention_heads': 'n_heads', 'num_hidden_layers': 'n_layers', } def __init__( self , snake_case__=3_05_22 , snake_case__=5_12 , snake_case__=False , snake_case__=6 , snake_case__=12 , snake_case__=7_68 , snake_case__=4 * 7_68 , snake_case__=0.1 , snake_case__=0.1 , snake_case__="gelu" , snake_case__=0.02 , snake_case__=0.1 , snake_case__=0.2 , snake_case__=0 , **snake_case__ , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = vocab_size UpperCAmelCase = max_position_embeddings UpperCAmelCase = sinusoidal_pos_embds UpperCAmelCase = n_layers UpperCAmelCase = n_heads UpperCAmelCase = dim UpperCAmelCase = hidden_dim UpperCAmelCase = dropout UpperCAmelCase = attention_dropout UpperCAmelCase = activation UpperCAmelCase = initializer_range UpperCAmelCase = qa_dropout UpperCAmelCase = seq_classif_dropout super().__init__(**snake_case__ , pad_token_id=snake_case__ ) class UpperCamelCase_ ( a_ ): @property def UpperCamelCase_ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": UpperCAmelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCAmelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
248
"""simple docstring""" from ...configuration_utils import PretrainedConfig lowerCAmelCase_ : Any = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class UpperCamelCase_ ( a_ ): _A : List[str] = 'tapas' def __init__( self , snake_case__=3_05_22 , snake_case__=7_68 , snake_case__=12 , snake_case__=12 , snake_case__=30_72 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=10_24 , snake_case__=[3, 2_56, 2_56, 2, 2_56, 2_56, 10] , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=0 , snake_case__=10.0 , snake_case__=0 , snake_case__=1.0 , snake_case__=None , snake_case__=1.0 , snake_case__=False , snake_case__=None , snake_case__=1.0 , snake_case__=1.0 , snake_case__=False , snake_case__=False , snake_case__="ratio" , snake_case__=None , snake_case__=None , snake_case__=64 , snake_case__=32 , snake_case__=False , snake_case__=True , snake_case__=False , snake_case__=False , snake_case__=True , snake_case__=False , snake_case__=None , snake_case__=None , **snake_case__ , ) -> Optional[Any]: """simple docstring""" super().__init__(pad_token_id=snake_case__ , **snake_case__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_sizes UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps # Fine-tuning task hyperparameters UpperCAmelCase = positive_label_weight UpperCAmelCase = num_aggregation_labels UpperCAmelCase = aggregation_loss_weight UpperCAmelCase = use_answer_as_supervision UpperCAmelCase = answer_loss_importance UpperCAmelCase = use_normalized_answer_loss UpperCAmelCase = huber_loss_delta UpperCAmelCase = temperature UpperCAmelCase = aggregation_temperature UpperCAmelCase = use_gumbel_for_cells UpperCAmelCase = use_gumbel_for_aggregation UpperCAmelCase = average_approximation_function UpperCAmelCase = cell_selection_preference UpperCAmelCase = answer_loss_cutoff UpperCAmelCase = max_num_rows UpperCAmelCase = max_num_columns UpperCAmelCase = average_logits_per_cell UpperCAmelCase = select_one_column UpperCAmelCase = allow_empty_column_selection UpperCAmelCase = init_cell_selection_weights_to_zero UpperCAmelCase = reset_position_index_per_cell UpperCAmelCase = disable_per_token_loss # Aggregation hyperparameters UpperCAmelCase = aggregation_labels UpperCAmelCase = no_aggregation_label_index if isinstance(self.aggregation_labels , snake_case__ ): UpperCAmelCase = {int(snake_case__ ): v for k, v in aggregation_labels.items()}
248
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import torch from ...utils import is_npu_available, is_xpu_available from .config_args import ClusterConfig, default_json_config_file from .config_utils import SubcommandHelpFormatter SCREAMING_SNAKE_CASE :Union[str, Any] = 'Create a default config file for Accelerate with only a few flags set.' def UpperCAmelCase ( a_="no" , a_ = default_json_config_file , a_ = False ) -> Optional[int]: """simple docstring""" __A = Path(a_ ) path.parent.mkdir(parents=a_ , exist_ok=a_ ) if path.exists(): print( F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.''' ) return False __A = mixed_precision.lower() if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: raise ValueError( F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}''' ) __A = { "compute_environment": "LOCAL_MACHINE", "mixed_precision": mixed_precision, } if torch.cuda.is_available(): __A = torch.cuda.device_count() __A = num_gpus __A = False if num_gpus > 1: __A = "MULTI_GPU" else: __A = "NO" elif is_xpu_available() and use_xpu: __A = torch.xpu.device_count() __A = num_xpus __A = False if num_xpus > 1: __A = "MULTI_XPU" else: __A = "NO" elif is_npu_available(): __A = torch.npu.device_count() __A = num_npus __A = False if num_npus > 1: __A = "MULTI_NPU" else: __A = "NO" else: __A = 0 __A = True __A = 1 __A = "NO" __A = ClusterConfig(**a_ ) config.to_json_file(a_ ) return path def UpperCAmelCase ( a_ , a_ ) -> List[Any]: """simple docstring""" __A = parser.add_parser("default" , parents=a_ , help=a_ , formatter_class=a_ ) parser.add_argument( "--config_file" , default=a_ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , dest="save_location" , ) parser.add_argument( "--mixed_precision" , choices=["no", "fp16", "bf16"] , type=a_ , help="Whether or not to use mixed precision training. " "Choose between FP16 and BF16 (bfloat16) training. " "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later." , default="no" , ) parser.set_defaults(func=a_ ) return parser def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" __A = write_basic_config(args.mixed_precision , args.save_location ) if config_file: print(F'''accelerate configuration saved at {config_file}''' )
15
"""simple docstring""" from sklearn.metrics import recall_score import datasets lowerCAmelCase__ = ''' Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. ''' lowerCAmelCase__ = ''' Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the \'positive class\' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`. - `\'binary\'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `\'micro\'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `\'weighted\'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `\'samples\'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `\'warn\'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric(\'recall\') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {\'recall\': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric(\'recall\') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {\'recall\': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric(\'recall\') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {\'recall\': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric(\'recall\') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'macro\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'micro\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'weighted\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {\'recall\': array([1., 0., 0.])} ''' lowerCAmelCase__ = ''' @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCamelCase ( datasets.Metric ): def snake_case_ (self ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"] , ) def snake_case_ (self , __a , __a , __a=None , __a=1 , __a="binary" , __a=None , __a="warn" , ) -> str: UpperCamelCase = recall_score( __a , __a , labels=__a , pos_label=__a , average=__a , sample_weight=__a , zero_division=__a , ) return {"recall": float(__a ) if score.size == 1 else score}
153
0
"""simple docstring""" import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : List[str] = logging.get_logger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = original_name.split("." )[0] __SCREAMING_SNAKE_CASE = key.split("." ) __SCREAMING_SNAKE_CASE = int(key_list[key_list.index(lowerCAmelCase_ ) - 2] ) __SCREAMING_SNAKE_CASE = int(key_list[key_list.index(lowerCAmelCase_ ) - 1] ) __SCREAMING_SNAKE_CASE = orig_block_num - offset __SCREAMING_SNAKE_CASE = key.replace(f"""{orig_block_num}.{layer_num}.{original_name}""" , f"""block.{new_block_num}.{layer_num}.{new_name}""" ) return key def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = OrderedDict() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0, 0 for key, value in state_dict.items(): if key.startswith("network" ): __SCREAMING_SNAKE_CASE = key.replace("network" , "poolformer.encoder" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("bias" ) and "patch_embed" not in key: patch_emb_offset += 1 __SCREAMING_SNAKE_CASE = key[: key.find("proj" )] __SCREAMING_SNAKE_CASE = key.replace(lowerCAmelCase_ , f"""patch_embeddings.{total_embed_found}.""" ) __SCREAMING_SNAKE_CASE = key.replace("proj" , "projection" ) if key.endswith("bias" ): total_embed_found += 1 if "patch_embeddings" in key: __SCREAMING_SNAKE_CASE = "poolformer.encoder." + key if "mlp.fc1" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "mlp.fc1" , "output.conv1" ) if "mlp.fc2" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "mlp.fc2" , "output.conv2" ) if "norm1" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "norm1" , "before_norm" ) if "norm2" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "norm2" , "after_norm" ) if "layer_scale_1" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "layer_scale_1" , "layer_scale_1" ) if "layer_scale_2" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "layer_scale_2" , "layer_scale_2" ) if "head" in key: __SCREAMING_SNAKE_CASE = key.replace("head" , "classifier" ) __SCREAMING_SNAKE_CASE = value return new_state_dict def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return image @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = PoolFormerConfig() # set attributes based on model_name __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = model_name[-3:] __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = (1, 1000) # set config attributes __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) __SCREAMING_SNAKE_CASE = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} if size == "s12": __SCREAMING_SNAKE_CASE = [2, 2, 6, 2] __SCREAMING_SNAKE_CASE = [64, 128, 320, 512] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 0.9 elif size == "s24": __SCREAMING_SNAKE_CASE = [4, 4, 12, 4] __SCREAMING_SNAKE_CASE = [64, 128, 320, 512] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 0.9 elif size == "s36": __SCREAMING_SNAKE_CASE = [6, 6, 18, 6] __SCREAMING_SNAKE_CASE = [64, 128, 320, 512] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 1E-6 __SCREAMING_SNAKE_CASE = 0.9 elif size == "m36": __SCREAMING_SNAKE_CASE = [6, 6, 18, 6] __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 1E-6 __SCREAMING_SNAKE_CASE = 0.95 elif size == "m48": __SCREAMING_SNAKE_CASE = [8, 8, 24, 8] __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 1E-6 __SCREAMING_SNAKE_CASE = 0.95 else: raise ValueError(f"""Size {size} not supported""" ) # load image processor __SCREAMING_SNAKE_CASE = PoolFormerImageProcessor(crop_pct=lowerCAmelCase_ ) # Prepare image __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=lowerCAmelCase_ , return_tensors="pt" ).pixel_values logger.info(f"""Converting model {model_name}...""" ) # load original state dict __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location=torch.device("cpu" ) ) # rename keys __SCREAMING_SNAKE_CASE = rename_keys(lowerCAmelCase_ ) # create HuggingFace model and load state dict __SCREAMING_SNAKE_CASE = PoolFormerForImageClassification(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) model.eval() # Define image processor __SCREAMING_SNAKE_CASE = PoolFormerImageProcessor(crop_pct=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="pt" ).pixel_values # forward pass __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits # define expected logit slices for different models if size == "s12": __SCREAMING_SNAKE_CASE = torch.tensor([-0.3045, -0.6758, -0.4869] ) elif size == "s24": __SCREAMING_SNAKE_CASE = torch.tensor([0.4402, -0.1374, -0.8045] ) elif size == "s36": __SCREAMING_SNAKE_CASE = torch.tensor([-0.6080, -0.5133, -0.5898] ) elif size == "m36": __SCREAMING_SNAKE_CASE = torch.tensor([0.3952, 0.2263, -1.2668] ) elif size == "m48": __SCREAMING_SNAKE_CASE = torch.tensor([0.1167, -0.0656, -0.3423] ) else: raise ValueError(f"""Size {size} not supported""" ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , lowerCAmelCase_ , atol=1E-2 ) # finally, save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : Any = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) a__ : List[str] = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
195
"""simple docstring""" from __future__ import annotations import requests def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = f"""https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty""" return requests.get(lowerCAmelCase_ ).json() def UpperCAmelCase__ (lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" __SCREAMING_SNAKE_CASE = requests.get(lowerCAmelCase_ ).json()[:max_stories] return [get_hackernews_story(lowerCAmelCase_ ) for story_id in story_ids] def UpperCAmelCase__ (lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = hackernews_top_stories(lowerCAmelCase_ ) return "\n".join("* [{title}]({url})".format(**lowerCAmelCase_ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
195
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Dict = { 'MIT/ast-finetuned-audioset-10-10-0.4593': ( 'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json' ), } class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : Optional[int] = '''audio-spectrogram-transformer''' def __init__(self , SCREAMING_SNAKE_CASE__=7_68 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=30_72 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=10 , SCREAMING_SNAKE_CASE__=10_24 , SCREAMING_SNAKE_CASE__=1_28 , **SCREAMING_SNAKE_CASE__ , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int = initializer_range SCREAMING_SNAKE_CASE__ : int = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = qkv_bias SCREAMING_SNAKE_CASE__ : Optional[int] = frequency_stride SCREAMING_SNAKE_CASE__ : Any = time_stride SCREAMING_SNAKE_CASE__ : Optional[int] = max_length SCREAMING_SNAKE_CASE__ : Any = num_mel_bins
25
'''simple docstring''' def lowercase__ ( __UpperCamelCase = 2000000 )-> int: UpperCamelCase = [0 for i in range(n + 1 )] UpperCamelCase = 1 UpperCamelCase = 1 for i in range(2 , int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i , n + 1 , __UpperCamelCase ): UpperCamelCase = 1 UpperCamelCase = 0 for i in range(__UpperCamelCase ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'{solution() = }')
321
0
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging __UpperCAmelCase =logging.get_logger(__name__) class a__ ( UpperCAmelCase__ ): lowerCamelCase : str ="linear" lowerCamelCase : int ="cosine" lowerCamelCase : Union[str, Any] ="cosine_with_restarts" lowerCamelCase : Tuple ="polynomial" lowerCamelCase : Dict ="constant" lowerCamelCase : Dict ="constant_with_warmup" lowerCamelCase : Union[str, Any] ="piecewise_constant" def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = -1 ) -> Dict: return LambdaLR(UpperCamelCase__ , lambda UpperCamelCase__ : 1 , last_epoch=UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = -1 ) -> Any: def lr_lambda(UpperCamelCase__ ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1.0 , UpperCamelCase__ ) ) return 1.0 return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , last_epoch=UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = -1 ) -> Any: __lowerCamelCase = {} __lowerCamelCase = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: __lowerCamelCase , __lowerCamelCase = rule_str.split(''':''' ) __lowerCamelCase = int(UpperCamelCase__ ) __lowerCamelCase = float(UpperCamelCase__ ) __lowerCamelCase = value __lowerCamelCase = float(rule_list[-1] ) def create_rules_function(UpperCamelCase__ , UpperCamelCase__ ): def rule_func(UpperCamelCase__ ) -> float: __lowerCamelCase = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(UpperCamelCase__ ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __lowerCamelCase = create_rules_function(UpperCamelCase__ , UpperCamelCase__ ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , last_epoch=UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=-1 ) -> Optional[int]: def lr_lambda(UpperCamelCase__ ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 0.5 , UpperCamelCase__ = -1 ) -> int: def lr_lambda(UpperCamelCase__ ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) __lowerCamelCase = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(UpperCamelCase__ ) * 2.0 * progress )) ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = 1 , UpperCamelCase__ = -1 ) -> Any: def lr_lambda(UpperCamelCase__ ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) __lowerCamelCase = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(UpperCamelCase__ ) * progress) % 1.0) )) ) return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=1E-7 , UpperCamelCase__=1.0 , UpperCamelCase__=-1 ) -> Dict: __lowerCamelCase = optimizer.defaults['''lr'''] if not (lr_init > lr_end): raise ValueError(f"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" ) def lr_lambda(UpperCamelCase__ ): if current_step < num_warmup_steps: return float(UpperCamelCase__ ) / float(max(1 , UpperCamelCase__ ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __lowerCamelCase = lr_init - lr_end __lowerCamelCase = num_training_steps - num_warmup_steps __lowerCamelCase = 1 - (current_step - num_warmup_steps) / decay_steps __lowerCamelCase = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) __UpperCAmelCase ={ SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = 1 , UpperCamelCase__ = 1.0 , UpperCamelCase__ = -1 , ) -> int: __lowerCamelCase = SchedulerType(UpperCamelCase__ ) __lowerCamelCase = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(UpperCamelCase__ , last_epoch=UpperCamelCase__ ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(UpperCamelCase__ , step_rules=UpperCamelCase__ , last_epoch=UpperCamelCase__ ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f"""{name} requires `num_warmup_steps`, please provide that argument.""" ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , last_epoch=UpperCamelCase__ ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f"""{name} requires `num_training_steps`, please provide that argument.""" ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , num_training_steps=UpperCamelCase__ , num_cycles=UpperCamelCase__ , last_epoch=UpperCamelCase__ , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , num_training_steps=UpperCamelCase__ , power=UpperCamelCase__ , last_epoch=UpperCamelCase__ , ) return schedule_func( UpperCamelCase__ , num_warmup_steps=UpperCamelCase__ , num_training_steps=UpperCamelCase__ , last_epoch=UpperCamelCase__ )
237
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> str: return "".join(chr(ord(UpperCamelCase__ ) - 32 ) if '''a''' <= char <= '''z''' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
237
1
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): if not head: return True # split the list to two parts A_ , A_ : List[str] = head.next, head while fast and fast.next: A_ : List[Any] = fast.next.next A_ : Optional[int] = slow.next A_ : Dict = slow.next A_ : List[str] = None # Don't forget here! But forget still works! # reverse the second part A_ : Union[str, Any] = None while second: A_ : str = second.next A_ : Tuple = node A_ : List[Any] = second A_ : Optional[int] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False A_ : Tuple = node.next A_ : Union[str, Any] = head.next return True def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): if not head or not head.next: return True # 1. Get the midpoint (slow) A_ : Union[str, Any] = head while fast and fast.next: A_ , A_ : Dict = fast.next.next, slow.next # 2. Push the second half into the stack A_ : Dict = [slow.val] while slow.next: A_ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False A_ : Optional[int] = cur.next return True def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): if not head or not head.next: return True A_ : List[Any] = {} A_ : str = 0 while head: if head.val in d: d[head.val].append(SCREAMING_SNAKE_CASE ) else: A_ : Any = [pos] A_ : Dict = head.next pos += 1 A_ : Union[str, Any] = pos - 1 A_ : Dict = 0 for v in d.values(): if len(SCREAMING_SNAKE_CASE ) % 2 != 0: middle += 1 else: A_ : Dict = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE ) ): if v[i] + v[len(SCREAMING_SNAKE_CASE ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
186
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class _lowerCamelCase ( unittest.TestCase ): """simple docstring""" def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )->List[Any]: '''simple docstring''' A_ : Optional[int] = jnp.ones((batch_size, length) ) / length return scores def _snake_case ( self )->Tuple: '''simple docstring''' A_ : Union[str, Any] = None A_ : Any = 20 A_ : Any = self._get_uniform_logits(batch_size=2 , length=_SCREAMING_SNAKE_CASE ) # tweak scores to not be uniform anymore A_ : Dict = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch A_ : Tuple = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax A_ : List[str] = jax.nn.softmax(_SCREAMING_SNAKE_CASE , axis=-1 ) A_ : Any = FlaxTemperatureLogitsWarper(temperature=0.5 ) A_ : Optional[int] = FlaxTemperatureLogitsWarper(temperature=1.3 ) A_ : Optional[Any] = jax.nn.softmax(temp_dist_warper_sharper(_SCREAMING_SNAKE_CASE , scores.copy() , cur_len=_SCREAMING_SNAKE_CASE ) , axis=-1 ) A_ : List[Any] = jax.nn.softmax(temp_dist_warper_smoother(_SCREAMING_SNAKE_CASE , scores.copy() , cur_len=_SCREAMING_SNAKE_CASE ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def _snake_case ( self )->List[Any]: '''simple docstring''' A_ : Any = None A_ : List[Any] = 10 A_ : str = 2 # create ramp distribution A_ : Any = np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE )[None, :] , (batch_size, vocab_size) ).copy() A_ : List[Any] = ramp_logits[1:, : vocab_size // 2] + vocab_size A_ : Any = FlaxTopKLogitsWarper(3 ) A_ : Tuple = top_k_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case A_ : Optional[int] = 5 A_ : List[Any] = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) A_ : Optional[Any] = np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE )[None, :] , (batch_size, length) ).copy() A_ : Dict = top_k_warp_safety_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def _snake_case ( self )->Any: '''simple docstring''' A_ : str = None A_ : Optional[Any] = 10 A_ : Any = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) A_ : Optional[int] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]] ) ) A_ : str = FlaxTopPLogitsWarper(0.8 ) A_ : Optional[int] = np.exp(top_p_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 A_ : Tuple = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]] ) self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # check edge cases with negative and extreme logits A_ : Union[str, Any] = np.broadcast_to(np.arange(_SCREAMING_SNAKE_CASE )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme A_ : str = ramp_logits[1] * 1_0_0.0 # make sure at least 2 tokens are kept A_ : str = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) A_ : str = top_p_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def _snake_case ( self )->Any: '''simple docstring''' A_ : str = 20 A_ : Union[str, Any] = 4 A_ : Optional[Any] = 0 A_ : Union[str, Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_SCREAMING_SNAKE_CASE ) # check that min length is applied at length 5 A_ : int = ids_tensor((batch_size, 20) , vocab_size=20 ) A_ : List[Any] = 5 A_ : Optional[int] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Optional[int] = min_dist_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('''inf''' )] ) # check that min length is not applied anymore at length 15 A_ : Tuple = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Any = 15 A_ : int = min_dist_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE ).any() ) def _snake_case ( self )->Optional[Any]: '''simple docstring''' A_ : Optional[int] = 20 A_ : Optional[int] = 4 A_ : Optional[int] = 0 A_ : Optional[Any] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE ) # check that all scores are -inf except the bos_token_id score A_ : Optional[Any] = ids_tensor((batch_size, 1) , vocab_size=20 ) A_ : str = 1 A_ : List[str] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : List[str] = logits_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 A_ : Optional[int] = 3 A_ : List[Any] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Tuple = logits_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE ).any() ) def _snake_case ( self )->List[str]: '''simple docstring''' A_ : Union[str, Any] = 20 A_ : str = 4 A_ : Dict = 0 A_ : Optional[int] = 5 A_ : Tuple = FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE ) # check that all scores are -inf except the eos_token_id when max_length is reached A_ : List[Any] = ids_tensor((batch_size, 4) , vocab_size=20 ) A_ : Any = 4 A_ : Optional[Any] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : List[Any] = logits_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached A_ : int = 3 A_ : Union[str, Any] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Dict = logits_processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) self.assertFalse(jnp.isinf(_SCREAMING_SNAKE_CASE ).any() ) def _snake_case ( self )->str: '''simple docstring''' A_ : str = 4 A_ : Dict = 10 A_ : Union[str, Any] = 15 A_ : str = 2 A_ : int = 1 A_ : List[str] = 15 # dummy input_ids and scores A_ : Tuple = ids_tensor((batch_size, sequence_length) , _SCREAMING_SNAKE_CASE ) A_ : int = input_ids.copy() A_ : List[Any] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = scores.copy() # instantiate all dist processors A_ : Dict = FlaxTemperatureLogitsWarper(temperature=0.5 ) A_ : Any = FlaxTopKLogitsWarper(3 ) A_ : List[Any] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors A_ : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE ) A_ : Dict = FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = 10 # no processor list A_ : int = temp_dist_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : List[str] = top_k_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Any = top_p_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Dict = min_dist_proc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = bos_dist_proc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = eos_dist_proc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) # with processor list A_ : Any = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) A_ : List[str] = processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) # scores should be equal self.assertTrue(jnp.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def _snake_case ( self )->Dict: '''simple docstring''' A_ : str = 4 A_ : Dict = 10 A_ : Tuple = 15 A_ : List[str] = 2 A_ : List[str] = 1 A_ : Union[str, Any] = 15 # dummy input_ids and scores A_ : Any = ids_tensor((batch_size, sequence_length) , _SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = input_ids.copy() A_ : Optional[Any] = self._get_uniform_logits(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : Tuple = scores.copy() # instantiate all dist processors A_ : List[str] = FlaxTemperatureLogitsWarper(temperature=0.5 ) A_ : Optional[Any] = FlaxTopKLogitsWarper(3 ) A_ : int = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors A_ : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_SCREAMING_SNAKE_CASE ) A_ : Dict = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE ) A_ : str = 10 # no processor list def run_no_processor_list(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): A_ : int = temp_dist_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = top_k_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : List[Any] = top_p_warp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Dict = min_dist_proc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Any = bos_dist_proc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) A_ : Optional[Any] = eos_dist_proc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) return scores # with processor list def run_processor_list(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): A_ : Optional[int] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) A_ : Optional[int] = processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , cur_len=_SCREAMING_SNAKE_CASE ) return scores A_ : Optional[int] = jax.jit(_SCREAMING_SNAKE_CASE ) A_ : Union[str, Any] = jax.jit(_SCREAMING_SNAKE_CASE ) A_ : Dict = jitted_run_no_processor_list(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) A_ : List[Any] = jitted_run_processor_list(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # scores should be equal self.assertTrue(jnp.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
186
1
def _a ( SCREAMING_SNAKE_CASE_ : str ): return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
364
import enum import shutil import sys UpperCamelCase__ , UpperCamelCase__ = shutil.get_terminal_size() UpperCamelCase__ = {"""UP""": """A""", """DOWN""": """B""", """RIGHT""": """C""", """LEFT""": """D"""} class a__ ( enum.Enum ): _a : Any = 0 _a : Dict = 1 def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Dict="" ): sys.stdout.write(str(SCREAMING_SNAKE_CASE_ ) + end ) sys.stdout.flush() def _a ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : str="" ): forceWrite(F"""\u001b[{color}m{content}\u001b[0m""" , SCREAMING_SNAKE_CASE_ ) def _a ( ): forceWrite("\r" ) def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str ): forceWrite(F"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}""" ) def _a ( ): forceWrite(" " * TERMINAL_WIDTH ) reset_cursor() def _a ( ): reset_cursor() forceWrite("-" * TERMINAL_WIDTH )
102
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _a : Optional[int]= {"configuration_xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : int= ["XLNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Optional[int]= ["XLNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Union[str, Any]= [ "XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "XLNetForMultipleChoice", "XLNetForQuestionAnswering", "XLNetForQuestionAnsweringSimple", "XLNetForSequenceClassification", "XLNetForTokenClassification", "XLNetLMHeadModel", "XLNetModel", "XLNetPreTrainedModel", "load_tf_weights_in_xlnet", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a : Dict= [ "TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLNetForMultipleChoice", "TFXLNetForQuestionAnsweringSimple", "TFXLNetForSequenceClassification", "TFXLNetForTokenClassification", "TFXLNetLMHeadModel", "TFXLNetMainLayer", "TFXLNetModel", "TFXLNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _a : Union[str, Any]= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
172
"""simple docstring""" from __future__ import annotations _a : List[Any]= [] def __UpperCAmelCase ( UpperCAmelCase_ : list[list[int]] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> bool: '''simple docstring''' for i in range(len(UpperCAmelCase_ ) ): if board[row][i] == 1: return False for i in range(len(UpperCAmelCase_ ) ): if board[i][column] == 1: return False for i, j in zip(range(UpperCAmelCase_ , -1 , -1 ) , range(UpperCAmelCase_ , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(UpperCAmelCase_ , -1 , -1 ) , range(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) ): if board[i][j] == 1: return False return True def __UpperCAmelCase ( UpperCAmelCase_ : list[list[int]] , UpperCAmelCase_ : int ) -> bool: '''simple docstring''' if row >= len(UpperCAmelCase_ ): solution.append(UpperCAmelCase_ ) printboard(UpperCAmelCase_ ) print() return True for i in range(len(UpperCAmelCase_ ) ): if is_safe(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): __snake_case : Any = 1 solve(UpperCAmelCase_ , row + 1 ) __snake_case : List[str] = 0 return False def __UpperCAmelCase ( UpperCAmelCase_ : list[list[int]] ) -> None: '''simple docstring''' for i in range(len(UpperCAmelCase_ ) ): for j in range(len(UpperCAmelCase_ ) ): if board[i][j] == 1: print('Q' , end=' ' ) else: print('.' , end=' ' ) print() # n=int(input("The no. of queens")) _a : Optional[int]= 8 _a : List[str]= [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
172
1
from PIL import Image def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Any = (259 * (level + 255)) / (255 * (259 - level)) def contrast(__lowerCamelCase ) -> int: return int(128 + factor * (c - 128) ) return img.point(lowercase_ ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change contrast to 170 UpperCamelCase__ =change_contrast(img, 170) cont_img.save('image_data/lena_high_contrast.png', format='png')
362
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class lowerCAmelCase__( __lowercase ): '''simple docstring''' __snake_case = ['vqvae'] def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> List[Any]: super().__init__() self.register_modules(unet=__lowerCamelCase , scheduler=__lowerCamelCase , mel=__lowerCamelCase , vqvae=__lowerCamelCase ) def UpperCamelCase_ ( self ) -> int: return 5_0 if isinstance(self.scheduler , __lowerCamelCase ) else 1_0_0_0 @torch.no_grad() def __call__( self , __lowerCamelCase = 1 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = 0 , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: _SCREAMING_SNAKE_CASE : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: _SCREAMING_SNAKE_CASE : Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: _SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__lowerCamelCase , device=self.device , ) _SCREAMING_SNAKE_CASE : Union[str, Any] = noise _SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) _SCREAMING_SNAKE_CASE : Optional[int] = (input_image / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: _SCREAMING_SNAKE_CASE : Union[str, Any] = self.vqvae.encode(torch.unsqueeze(__lowerCamelCase , 0 ) ).latent_dist.sample( generator=__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE : int = self.vqvae.config.scaling_factor * input_images if start_step > 0: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , self.scheduler.timesteps[start_step - 1] ) _SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) _SCREAMING_SNAKE_CASE : Optional[Any] = int(mask_start_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[int] = int(mask_end_secs * pixels_per_second ) _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(__lowerCamelCase , __lowerCamelCase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : List[str] = self.unet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase )["sample"] else: _SCREAMING_SNAKE_CASE : str = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] if isinstance(self.scheduler , __lowerCamelCase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , eta=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] else: _SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step( model_output=__lowerCamelCase , timestep=__lowerCamelCase , sample=__lowerCamelCase , generator=__lowerCamelCase , )["prev_sample"] if mask is not None: if mask_start > 0: _SCREAMING_SNAKE_CASE : str = mask[:, step, :, :mask_start] if mask_end > 0: _SCREAMING_SNAKE_CASE : Dict = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance _SCREAMING_SNAKE_CASE : Optional[Any] = 1 / self.vqvae.config.scaling_factor * images _SCREAMING_SNAKE_CASE : Dict = self.vqvae.decode(__lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : Union[str, Any] = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE : Union[str, Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() _SCREAMING_SNAKE_CASE : List[str] = (images * 2_5_5).round().astype("uint8" ) _SCREAMING_SNAKE_CASE : Tuple = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__lowerCamelCase , mode="RGB" ).convert("L" ) for _ in images) ) _SCREAMING_SNAKE_CASE : Tuple = [self.mel.image_to_audio(__lowerCamelCase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__lowerCamelCase )[:, np.newaxis, :] ) , **ImagePipelineOutput(__lowerCamelCase ) ) @torch.no_grad() def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = 5_0 ) -> np.ndarray: assert isinstance(self.scheduler , __lowerCamelCase ) self.scheduler.set_timesteps(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Optional[int] = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) _SCREAMING_SNAKE_CASE : Union[str, Any] = (sample / 2_5_5) * 2 - 1 _SCREAMING_SNAKE_CASE : Any = torch.Tensor(__lowerCamelCase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): _SCREAMING_SNAKE_CASE : Optional[int] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps _SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.alphas_cumprod[t] _SCREAMING_SNAKE_CASE : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) _SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t _SCREAMING_SNAKE_CASE : Optional[int] = self.unet(__lowerCamelCase , __lowerCamelCase )["sample"] _SCREAMING_SNAKE_CASE : List[str] = (1 - alpha_prod_t_prev) ** 0.5 * model_output _SCREAMING_SNAKE_CASE : str = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) _SCREAMING_SNAKE_CASE : List[str] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def UpperCamelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> torch.Tensor: _SCREAMING_SNAKE_CASE : Any = acos(torch.dot(torch.flatten(__lowerCamelCase ) , torch.flatten(__lowerCamelCase ) ) / torch.norm(__lowerCamelCase ) / torch.norm(__lowerCamelCase ) ) return sin((1 - alpha) * theta ) * xa / sin(__lowerCamelCase ) + sin(alpha * theta ) * xa / sin(__lowerCamelCase )
325
0
def A ( _SCREAMING_SNAKE_CASE ) -> int: lowerCamelCase : list[list[int]] = [[0 for _ in range(_SCREAMING_SNAKE_CASE )] for _ in range(m + 1 )] for i in range(m + 1 ): lowerCamelCase : Optional[int] = 1 for n in range(m + 1 ): for k in range(1 ,_SCREAMING_SNAKE_CASE ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: SCREAMING_SNAKE_CASE__ : List[str] = int(input('Enter a number: ').strip()) print(partition(n)) except ValueError: print('Please enter a number.') else: try: SCREAMING_SNAKE_CASE__ : Optional[Any] = int(sys.argv[1]) print(partition(n)) except ValueError: print('Please pass a number.')
48
def A ( _SCREAMING_SNAKE_CASE = 100_0000 ) -> int: lowerCamelCase : Tuple = 1 lowerCamelCase : int = 1 lowerCamelCase : Optional[Any] = {1: 1} for inputa in range(2 ,_SCREAMING_SNAKE_CASE ): lowerCamelCase : Union[str, Any] = 0 lowerCamelCase : List[str] = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: lowerCamelCase : str = (3 * number) + 1 counter += 1 if inputa not in counters: lowerCamelCase : str = counter if counter > pre_counter: lowerCamelCase : str = inputa lowerCamelCase : Any = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
48
1
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 __a ( A__ ): def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE : Optional[Features] = None , SCREAMING_SNAKE_CASE : str = None , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : Optional[str] = None , SCREAMING_SNAKE_CASE : Optional[int] = None , **SCREAMING_SNAKE_CASE : Any , ): '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE , split=SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , keep_in_memory=SCREAMING_SNAKE_CASE , streaming=SCREAMING_SNAKE_CASE , num_proc=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) UpperCamelCase__ : Any = field UpperCamelCase__ : Any = path_or_paths if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else {self.split: path_or_paths} UpperCamelCase__ : List[str] = Json( cache_dir=SCREAMING_SNAKE_CASE , data_files=SCREAMING_SNAKE_CASE , features=SCREAMING_SNAKE_CASE , field=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) def __lowercase ( self : Tuple ): '''simple docstring''' if self.streaming: UpperCamelCase__ : Union[str, Any] = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: UpperCamelCase__ : Optional[Any] = None UpperCamelCase__ : Union[str, Any] = None UpperCamelCase__ : Optional[Any] = None UpperCamelCase__ : Union[str, Any] = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE , download_mode=SCREAMING_SNAKE_CASE , verification_mode=SCREAMING_SNAKE_CASE , base_path=SCREAMING_SNAKE_CASE , num_proc=self.num_proc , ) UpperCamelCase__ : str = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory ) return dataset class __a : def __init__( self : List[str] , SCREAMING_SNAKE_CASE : Dataset , SCREAMING_SNAKE_CASE : Union[PathLike, BinaryIO] , SCREAMING_SNAKE_CASE : Optional[int] = None , SCREAMING_SNAKE_CASE : Optional[int] = None , **SCREAMING_SNAKE_CASE : Optional[int] , ): '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(F'num_proc {num_proc} must be an integer > 0.' ) UpperCamelCase__ : str = dataset UpperCamelCase__ : Dict = path_or_buf UpperCamelCase__ : List[str] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE UpperCamelCase__ : Optional[Any] = num_proc UpperCamelCase__ : Tuple = "utf-8" UpperCamelCase__ : Dict = to_json_kwargs def __lowercase ( self : str ): '''simple docstring''' UpperCamelCase__ : List[Any] = self.to_json_kwargs.pop("path_or_buf" , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Dict = self.to_json_kwargs.pop("orient" , "records" ) UpperCamelCase__ : Any = self.to_json_kwargs.pop("lines" , True if orient == "records" else False ) UpperCamelCase__ : Optional[int] = self.to_json_kwargs.pop("index" , False if orient in ["split", "table"] else True ) UpperCamelCase__ : Any = self.to_json_kwargs.pop("compression" , SCREAMING_SNAKE_CASE ) 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=SCREAMING_SNAKE_CASE ) as buffer: UpperCamelCase__ : str = self._write(file_obj=SCREAMING_SNAKE_CASE , orient=SCREAMING_SNAKE_CASE , lines=SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE , **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." ) UpperCamelCase__ : Tuple = self._write( file_obj=self.path_or_buf , orient=SCREAMING_SNAKE_CASE , lines=SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE , **self.to_json_kwargs ) return written def __lowercase ( self : List[str] , SCREAMING_SNAKE_CASE : str ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : int = args UpperCamelCase__ : List[Any] = query_table( table=self.dataset.data , key=slice(SCREAMING_SNAKE_CASE , offset + self.batch_size ) , indices=self.dataset._indices , ) UpperCamelCase__ : Dict = batch.to_pandas().to_json( path_or_buf=SCREAMING_SNAKE_CASE , orient=SCREAMING_SNAKE_CASE , lines=SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) if not json_str.endswith("\n" ): json_str += "\n" return json_str.encode(self.encoding ) def __lowercase ( self : Tuple , SCREAMING_SNAKE_CASE : BinaryIO , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Tuple , **SCREAMING_SNAKE_CASE : Optional[int] , ): '''simple docstring''' UpperCamelCase__ : List[str] = 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" , ): UpperCamelCase__ : Any = self._batch_json((offset, orient, lines, index, to_json_kwargs) ) written += file_obj.write(SCREAMING_SNAKE_CASE ) else: UpperCamelCase__ , UpperCamelCase__ : Optional[int] = 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 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )] , ) , 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(SCREAMING_SNAKE_CASE ) return written
196
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> list[int]: UpperCamelCase__ : Optional[Any] = 0 UpperCamelCase__ : Any = len(__lowerCAmelCase ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: UpperCamelCase__ : Optional[int] = i + 1 else: UpperCamelCase__ : Dict = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(F"""{two_pointer([2, 7, 11, 15], 9) = }""")
196
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : List[Any] ={ """configuration_electra""": ["""ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ElectraConfig""", """ElectraOnnxConfig"""], """tokenization_electra""": ["""ElectraTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str =["""ElectraTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any =[ """ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """ElectraForCausalLM""", """ElectraForMaskedLM""", """ElectraForMultipleChoice""", """ElectraForPreTraining""", """ElectraForQuestionAnswering""", """ElectraForSequenceClassification""", """ElectraForTokenClassification""", """ElectraModel""", """ElectraPreTrainedModel""", """load_tf_weights_in_electra""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict =[ """TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFElectraForMaskedLM""", """TFElectraForMultipleChoice""", """TFElectraForPreTraining""", """TFElectraForQuestionAnswering""", """TFElectraForSequenceClassification""", """TFElectraForTokenClassification""", """TFElectraModel""", """TFElectraPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Dict =[ """FlaxElectraForCausalLM""", """FlaxElectraForMaskedLM""", """FlaxElectraForMultipleChoice""", """FlaxElectraForPreTraining""", """FlaxElectraForQuestionAnswering""", """FlaxElectraForSequenceClassification""", """FlaxElectraForTokenClassification""", """FlaxElectraModel""", """FlaxElectraPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys UpperCAmelCase : int =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
128
"""simple docstring""" from __future__ import annotations from math import pi, sqrt def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase ) -> tuple: if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
177
0
'''simple docstring''' import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy lowercase__ : Union[str, Any] = logging.getLogger(__name__) def a__ ( lowercase : torch.nn.Module, lowercase : BnbQuantizationConfig, lowercase : Union[str, os.PathLike] = None, lowercase : Optional[Dict[str, Union[int, str, torch.device]]] = None, lowercase : Optional[List[str]] = None, lowercase : Optional[Dict[Union[int, str], Union[int, str]]] = None, lowercase : Optional[Union[str, os.PathLike]] = None, lowercase : bool = False, ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = bnb_quantization_config.load_in_abit _UpperCamelCase = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( '''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,''' ''' make sure you have the latest version of `bitsandbytes` installed.''' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( '''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,''' '''make sure you have the latest version of `bitsandbytes` installed.''' ) _UpperCamelCase = [] # custom device map if isinstance(lowerCamelCase_, lowerCamelCase_ ) and len(device_map.keys() ) > 1: _UpperCamelCase = [key for key, value in device_map.items() if value in ['''disk''', '''cpu''']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: _UpperCamelCase = get_keys_to_not_convert(lowerCamelCase_ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(lowerCamelCase_ ) _UpperCamelCase = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: _UpperCamelCase = [] _UpperCamelCase = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(lowerCamelCase_ ) # compatibility with peft _UpperCamelCase = load_in_abit _UpperCamelCase = load_in_abit _UpperCamelCase = get_parameter_device(lowerCamelCase_ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( '''It is not recommended to quantize a loaded model. ''' '''The model should be instantiated under the `init_empty_weights` context manager.''' ) _UpperCamelCase = replace_with_bnb_layers(lowerCamelCase_, lowerCamelCase_, modules_to_not_convert=lowerCamelCase_ ) # convert param to the right dtype _UpperCamelCase = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: _UpperCamelCase = name.replace('''.weight''', '''''' ).replace('''.bias''', '''''' ) _UpperCamelCase = getattr(lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(lowerCamelCase_ ): param.to(lowerCamelCase_ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" '''We move the model to cuda.''' ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): _UpperCamelCase = replace_with_bnb_layers( lowerCamelCase_, lowerCamelCase_, modules_to_not_convert=lowerCamelCase_ ) _UpperCamelCase = get_quantized_model_device_map( lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, max_memory=lowerCamelCase_, no_split_module_classes=lowerCamelCase_, ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): _UpperCamelCase = True _UpperCamelCase = any(x in list(device_map.values() ) for x in ['''cpu''', '''disk'''] ) load_checkpoint_in_model( lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, dtype=bnb_quantization_config.torch_dtype, offload_folder=lowerCamelCase_, offload_state_dict=lowerCamelCase_, keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules, offload_abit_bnb=load_in_abit and offload, ) return dispatch_model(lowerCamelCase_, device_map=lowerCamelCase_, offload_dir=lowerCamelCase_ ) def a__ ( lowercase : Optional[int], lowercase : List[str], lowercase : Tuple=None, lowercase : Union[str, Any]=None, lowercase : List[str]=None ) -> Dict: """simple docstring""" if device_map is None: if torch.cuda.is_available(): _UpperCamelCase = {'''''': torch.cuda.current_device()} else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.''' ) if isinstance(lowerCamelCase_, lowerCamelCase_ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( '''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ''' '''\'sequential\'.''' ) _UpperCamelCase = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) _UpperCamelCase = {} _UpperCamelCase = special_dtypes _UpperCamelCase = no_split_module_classes _UpperCamelCase = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": _UpperCamelCase = get_balanced_memory( lowerCamelCase_, low_zero=(device_map == '''balanced_low_0'''), max_memory=lowerCamelCase_, **lowerCamelCase_, ) _UpperCamelCase = max_memory _UpperCamelCase = infer_auto_device_map(lowerCamelCase_, **lowerCamelCase_ ) if isinstance(lowerCamelCase_, lowerCamelCase_ ): # check if don't have any quantized module on the cpu _UpperCamelCase = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules _UpperCamelCase = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( ''' Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. ''' ) else: logger.info( '''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit''' ) del device_map_without_some_modules return device_map def a__ ( lowercase : List[Any], lowercase : Optional[Any], lowercase : int=None, lowercase : int=None ) -> List[Any]: """simple docstring""" if modules_to_not_convert is None: _UpperCamelCase = [] _UpperCamelCase = _replace_with_bnb_layers( lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def a__ ( lowercase : Optional[int], lowercase : List[str], lowercase : List[Any]=None, lowercase : str=None, ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase = False for name, module in model.named_children(): if current_key_name is None: _UpperCamelCase = [] current_key_name.append(lowerCamelCase_ ) if isinstance(lowerCamelCase_, nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` _UpperCamelCase = '''.'''.join(lowerCamelCase_ ) _UpperCamelCase = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: _UpperCamelCase = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: _UpperCamelCase = bnb.nn.LinearabitLt( module.in_features, module.out_features, module.bias is not None, has_fpaa_weights=lowerCamelCase_, threshold=bnb_quantization_config.llm_inta_threshold, ) elif bnb_quantization_config.load_in_abit: _UpperCamelCase = bnb.nn.Linearabit( module.in_features, module.out_features, module.bias is not None, bnb_quantization_config.bnb_abit_compute_dtype, compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant, quant_type=bnb_quantization_config.bnb_abit_quant_type, ) else: raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False''' ) _UpperCamelCase = module.weight.data if module.bias is not None: _UpperCamelCase = module.bias.data bnb_module.requires_grad_(lowerCamelCase_ ) setattr(lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ) _UpperCamelCase = True if len(list(module.children() ) ) > 0: _UpperCamelCase = _replace_with_bnb_layers( lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ) _UpperCamelCase = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def a__ ( lowercase : str ) -> Union[str, Any]: """simple docstring""" with init_empty_weights(): _UpperCamelCase = deepcopy(lowerCamelCase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` _UpperCamelCase = find_tied_parameters(lowerCamelCase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowerCamelCase_, lowerCamelCase_ ): _UpperCamelCase = sum(list(tied_params.values() ), [] ) + list(tied_params.keys() ) else: _UpperCamelCase = sum(lowerCamelCase_, [] ) _UpperCamelCase = len(lowerCamelCase_ ) > 0 # Check if it is a base model _UpperCamelCase = False if hasattr(lowerCamelCase_, '''base_model_prefix''' ): _UpperCamelCase = not hasattr(lowerCamelCase_, model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _UpperCamelCase = list(model.named_children() ) _UpperCamelCase = [list_modules[-1][0]] # add last module together with tied weights _UpperCamelCase = set(lowerCamelCase_ ) - set(lowerCamelCase_ ) _UpperCamelCase = list(set(lowerCamelCase_ ) ) + list(lowerCamelCase_ ) # remove ".weight" from the keys _UpperCamelCase = ['''.weight''', '''.bias'''] _UpperCamelCase = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _UpperCamelCase = name.replace(lowerCamelCase_, '''''' ) filtered_module_names.append(lowerCamelCase_ ) return filtered_module_names def a__ ( lowercase : str ) -> Optional[int]: """simple docstring""" for m in model.modules(): if isinstance(lowerCamelCase_, bnb.nn.Linearabit ): return True return False def a__ ( lowercase : nn.Module ) -> Union[str, Any]: """simple docstring""" return next(parameter.parameters() ).device def a__ ( lowercase : List[str], lowercase : Dict, lowercase : Tuple, lowercase : Tuple, lowercase : Union[str, Any], lowercase : int, lowercase : str ) -> Union[str, Any]: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(lowerCamelCase_, lowerCamelCase_, 0, dtype=lowerCamelCase_, value=lowerCamelCase_ ) _UpperCamelCase = param_name _UpperCamelCase = model if "." in tensor_name: _UpperCamelCase = tensor_name.split('''.''' ) for split in splits[:-1]: _UpperCamelCase = getattr(lowerCamelCase_, lowerCamelCase_ ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) _UpperCamelCase = new_module _UpperCamelCase = splits[-1] # offload weights _UpperCamelCase = False offload_weight(module._parameters[tensor_name], lowerCamelCase_, lowerCamelCase_, index=lowerCamelCase_ ) if hasattr(module._parameters[tensor_name], '''SCB''' ): offload_weight( module._parameters[tensor_name].SCB, param_name.replace('''weight''', '''SCB''' ), lowerCamelCase_, index=lowerCamelCase_, ) else: offload_weight(lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, index=lowerCamelCase_ ) offload_weight(lowerCamelCase_, param_name.replace('''weight''', '''SCB''' ), lowerCamelCase_, index=lowerCamelCase_ ) set_module_tensor_to_device(lowerCamelCase_, lowerCamelCase_, '''meta''', dtype=lowerCamelCase_, value=torch.empty(*param.size() ) )
356
'''simple docstring''' def a__ ( lowercase : int, lowercase : int ) -> int: """simple docstring""" return x if y == 0 else greatest_common_divisor(lowercase, x % y ) def a__ ( lowercase : int, lowercase : int ) -> int: """simple docstring""" return (x * y) // greatest_common_divisor(lowercase, lowercase ) def a__ ( lowercase : int = 20 ) -> int: """simple docstring""" _UpperCamelCase = 1 for i in range(1, n + 1 ): _UpperCamelCase = lcm(lowercase, lowercase ) return g if __name__ == "__main__": print(F"""{solution() = }""")
287
0
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """facebook/encodec_24khz""": """https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json""", """facebook/encodec_48khz""": """https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json""", } class a ( UpperCAmelCase__ ): UpperCamelCase : str = 'encodec' def __init__( self : str , lowerCAmelCase : Union[str, Any]=[1.5, 3.0, 6.0, 1_2.0, 2_4.0] , lowerCAmelCase : Optional[int]=2_4000 , lowerCAmelCase : Union[str, Any]=1 , lowerCAmelCase : Tuple=False , lowerCAmelCase : Tuple=None , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : int=128 , lowerCAmelCase : Optional[Any]=32 , lowerCAmelCase : str=1 , lowerCAmelCase : Optional[int]=[8, 5, 4, 2] , lowerCAmelCase : Tuple="weight_norm" , lowerCAmelCase : Tuple=7 , lowerCAmelCase : int=7 , lowerCAmelCase : Optional[int]=3 , lowerCAmelCase : int=2 , lowerCAmelCase : int=True , lowerCAmelCase : Any="reflect" , lowerCAmelCase : int=2 , lowerCAmelCase : Union[str, Any]=2 , lowerCAmelCase : Union[str, Any]=1.0 , lowerCAmelCase : Optional[int]=1024 , lowerCAmelCase : List[str]=None , lowerCAmelCase : Union[str, Any]=True , **lowerCAmelCase : List[Any] , ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =target_bandwidths SCREAMING_SNAKE_CASE_: Any =sampling_rate SCREAMING_SNAKE_CASE_: Tuple =audio_channels SCREAMING_SNAKE_CASE_: Optional[Any] =normalize SCREAMING_SNAKE_CASE_: List[Any] =chunk_length_s SCREAMING_SNAKE_CASE_: Dict =overlap SCREAMING_SNAKE_CASE_: str =hidden_size SCREAMING_SNAKE_CASE_: Any =num_filters SCREAMING_SNAKE_CASE_: List[str] =num_residual_layers SCREAMING_SNAKE_CASE_: List[str] =upsampling_ratios SCREAMING_SNAKE_CASE_: Union[str, Any] =norm_type SCREAMING_SNAKE_CASE_: Optional[int] =kernel_size SCREAMING_SNAKE_CASE_: Optional[int] =last_kernel_size SCREAMING_SNAKE_CASE_: Optional[int] =residual_kernel_size SCREAMING_SNAKE_CASE_: Union[str, Any] =dilation_growth_rate SCREAMING_SNAKE_CASE_: List[Any] =use_causal_conv SCREAMING_SNAKE_CASE_: List[str] =pad_mode SCREAMING_SNAKE_CASE_: Optional[Any] =compress SCREAMING_SNAKE_CASE_: List[Any] =num_lstm_layers SCREAMING_SNAKE_CASE_: Optional[int] =trim_right_ratio SCREAMING_SNAKE_CASE_: List[str] =codebook_size SCREAMING_SNAKE_CASE_: Optional[int] =codebook_dim if codebook_dim is not None else hidden_size SCREAMING_SNAKE_CASE_: List[str] =use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( f'''self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}''' ) super().__init__(**_lowerCAmelCase ) @property def lowerCamelCase__ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def lowerCamelCase__ ( self : str ) -> List[Any]: '''simple docstring''' if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def lowerCamelCase__ ( self : Any ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE_: Dict =np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def lowerCamelCase__ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
173
'''simple docstring''' from datetime import datetime import requests def _A ( _lowerCAmelCase ): """simple docstring""" __lowercase ='https://downloadgram.net/wp-json/wppress/video-downloader/video?url=' __lowercase =requests.get(base_url + url ).json()[0]['urls'][0]['src'] return requests.get(_lowerCAmelCase ).content if __name__ == "__main__": lowerCamelCase = input("""Enter Video/IGTV url: """).strip() lowerCamelCase = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4" with open(file_name, """wb""") as fp: fp.write(download_video(url)) print(f"Done. Video saved to disk as {file_name}.")
166
0
'''simple docstring''' import collections import importlib.util import os import re from pathlib import Path lowercase ='src/transformers' # Matches is_xxx_available() lowercase =re.compile(r'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} lowercase =re.compile(r'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] lowercase =re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available lowercase =re.compile(r'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") lowercase =re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] lowercase =re.compile(r'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", lowercase =re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], lowercase =re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo lowercase =re.compile(r'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: lowercase =re.compile(r'^\s*try:') # Catches a line with else: lowercase =re.compile(r'^\s*else:') def lowerCamelCase__ ( __lowerCamelCase ): '''simple docstring''' if _re_test_backend.search(_A ) is None: return None _UpperCAmelCase : Dict =[b[0] for b in _re_backend.findall(_A )] backends.sort() return "_and_".join(_A ) def lowerCamelCase__ ( __lowerCamelCase ): '''simple docstring''' with open(_A , 'r' , encoding='utf-8' , newline='\n' ) as f: _UpperCAmelCase : Optional[int] =f.readlines() _UpperCAmelCase : Tuple =0 while line_index < len(_A ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(_A ): return None # First grab the objects without a specific backend in _import_structure _UpperCAmelCase : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: _UpperCAmelCase : Dict =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(_A ): _UpperCAmelCase : Any =_re_one_line_import_struct.search(_A ).groups()[0] _UpperCAmelCase : Union[str, Any] =re.findall('\[([^\]]+)\]' , _A ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue _UpperCAmelCase : List[Any] =_re_import_struct_key_value.search(_A ) if single_line_import_search is not None: _UpperCAmelCase : Union[str, Any] =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(_A ) > 0] objects.extend(_A ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 _UpperCAmelCase : List[str] ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. _UpperCAmelCase : Dict =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _UpperCAmelCase : List[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _UpperCAmelCase : int =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): _UpperCAmelCase : Union[str, Any] =lines[line_index] if _re_import_struct_add_one.search(_A ) is not None: objects.append(_re_import_struct_add_one.search(_A ).groups()[0] ) elif _re_import_struct_add_many.search(_A ) is not None: _UpperCAmelCase : Tuple =_re_import_struct_add_many.search(_A ).groups()[0].split(', ' ) _UpperCAmelCase : Any =[obj[1:-1] for obj in imports if len(_A ) > 0] objects.extend(_A ) elif _re_between_brackets.search(_A ) is not None: _UpperCAmelCase : Dict =_re_between_brackets.search(_A ).groups()[0].split(', ' ) _UpperCAmelCase : List[str] =[obj[1:-1] for obj in imports if len(_A ) > 0] objects.extend(_A ) elif _re_quote_object.search(_A ) is not None: objects.append(_re_quote_object.search(_A ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 1_2 + '"' ): objects.append(line[1_3:-3] ) line_index += 1 _UpperCAmelCase : Dict =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend _UpperCAmelCase : Optional[Any] =[] while ( line_index < len(_A ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): _UpperCAmelCase : Any =lines[line_index] _UpperCAmelCase : Dict =_re_import.search(_A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 _UpperCAmelCase : List[str] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(_A ): # If the line is an if is_backend_available, we grab all objects associated. _UpperCAmelCase : Tuple =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _UpperCAmelCase : Optional[Any] =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _UpperCAmelCase : Dict =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): _UpperCAmelCase : List[Any] =lines[line_index] _UpperCAmelCase : int =_re_import.search(_A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 1_2 ): objects.append(line[1_2:-2] ) line_index += 1 _UpperCAmelCase : Tuple =objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowerCamelCase__ ( __lowerCamelCase , __lowerCamelCase ): '''simple docstring''' def find_duplicates(__lowerCamelCase ): return [k for k, v in collections.Counter(_A ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] _UpperCAmelCase : Dict =[] for key in import_dict_objects.keys(): _UpperCAmelCase : Tuple =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}" ) _UpperCAmelCase : Dict =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): _UpperCAmelCase : Dict ='base imports' if key == 'none' else f"{key} backend" errors.append(f"Differences for {name}:" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f" {a} in TYPE_HINT but not in _import_structure." ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f" {a} in _import_structure but not in TYPE_HINT." ) return errors def lowerCamelCase__ ( ): '''simple docstring''' _UpperCAmelCase : Dict =[] for root, _, files in os.walk(_A ): if "__init__.py" in files: _UpperCAmelCase : Tuple =os.path.join(_A , '__init__.py' ) _UpperCAmelCase : Dict =parse_init(_A ) if objects is not None: _UpperCAmelCase : Optional[Any] =analyze_results(*_A ) if len(_A ) > 0: _UpperCAmelCase : List[str] =f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append('\n'.join(_A ) ) if len(_A ) > 0: raise ValueError('\n\n'.join(_A ) ) def lowerCamelCase__ ( ): '''simple docstring''' _UpperCAmelCase : str =[] for path, directories, files in os.walk(_A ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(_A ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(_A ) / folder).glob('*.py' ) ) ) == 0: continue _UpperCAmelCase : Dict =str((Path(_A ) / folder).relative_to(_A ) ) _UpperCAmelCase : Any =short_path.replace(os.path.sep , '.' ) submodules.append(_A ) for fname in files: if fname == "__init__.py": continue _UpperCAmelCase : int =str((Path(_A ) / fname).relative_to(_A ) ) _UpperCAmelCase : Dict =short_path.replace('.py' , '' ).replace(os.path.sep , '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(_A ) return submodules lowercase =[ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def lowerCamelCase__ ( ): '''simple docstring''' _UpperCAmelCase : Dict =importlib.util.spec_from_file_location( 'transformers' , os.path.join(_A , '__init__.py' ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) _UpperCAmelCase : Union[str, Any] =spec.loader.load_module() _UpperCAmelCase : int =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(_A ) > 0: _UpperCAmelCase : Optional[Any] ='\n'.join(f"- {module}" for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' f"{list_of_modules}\n" 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
358
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class __magic_name__ ( lowerCAmelCase ): UpperCAmelCase =42 UpperCAmelCase =42 class __magic_name__ ( nn.Module ): UpperCAmelCase =42 UpperCAmelCase =(1_6, 3_2, 9_6, 2_5_6) UpperCAmelCase =jnp.floataa def lowerCAmelCase ( self) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : str =nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) _UpperCAmelCase : Tuple =[] for i in range(len(self.block_out_channels) - 1): _UpperCAmelCase : Optional[int] =self.block_out_channels[i] _UpperCAmelCase : List[Any] =self.block_out_channels[i + 1] _UpperCAmelCase : Tuple =nn.Conv( snake_case , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case) _UpperCAmelCase : Optional[int] =nn.Conv( snake_case , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case) _UpperCAmelCase : Dict =blocks _UpperCAmelCase : Tuple =nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , snake_case) -> List[str]: '''simple docstring''' _UpperCAmelCase : int =self.conv_in(snake_case) _UpperCAmelCase : Any =nn.silu(snake_case) for block in self.blocks: _UpperCAmelCase : Optional[Any] =block(snake_case) _UpperCAmelCase : Union[str, Any] =nn.silu(snake_case) _UpperCAmelCase : str =self.conv_out(snake_case) return embedding @flax_register_to_config class __magic_name__ ( nn.Module ,lowerCAmelCase ,lowerCAmelCase ): UpperCAmelCase =3_2 UpperCAmelCase =4 UpperCAmelCase =( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) UpperCAmelCase =False UpperCAmelCase =(3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0) UpperCAmelCase =2 UpperCAmelCase =8 UpperCAmelCase =None UpperCAmelCase =1_2_8_0 UpperCAmelCase =0.0 UpperCAmelCase =False UpperCAmelCase =jnp.floataa UpperCAmelCase =True UpperCAmelCase =0 UpperCAmelCase ="rgb" UpperCAmelCase =(1_6, 3_2, 9_6, 2_5_6) def lowerCAmelCase ( self , snake_case) -> FrozenDict: '''simple docstring''' # init input tensors _UpperCAmelCase : Any =(1, self.in_channels, self.sample_size, self.sample_size) _UpperCAmelCase : Optional[Any] =jnp.zeros(snake_case , dtype=jnp.floataa) _UpperCAmelCase : Optional[int] =jnp.ones((1,) , dtype=jnp.intaa) _UpperCAmelCase : str =jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa) _UpperCAmelCase : Optional[Any] =(1, 3, self.sample_size * 8, self.sample_size * 8) _UpperCAmelCase : int =jnp.zeros(snake_case , dtype=jnp.floataa) _UpperCAmelCase , _UpperCAmelCase : List[Any] =jax.random.split(snake_case) _UpperCAmelCase : str ={'params': params_rng, 'dropout': dropout_rng} return self.init(snake_case , snake_case , snake_case , snake_case , snake_case)["params"] def lowerCAmelCase ( self) -> Tuple: '''simple docstring''' _UpperCAmelCase : Optional[Any] =self.block_out_channels _UpperCAmelCase : Tuple =block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _UpperCAmelCase : Optional[Any] =self.num_attention_heads or self.attention_head_dim # input _UpperCAmelCase : Tuple =nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _UpperCAmelCase : Union[str, Any] =FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift) _UpperCAmelCase : str =FlaxTimestepEmbedding(snake_case , dtype=self.dtype) _UpperCAmelCase : Optional[Any] =FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) _UpperCAmelCase : Optional[int] =self.only_cross_attention if isinstance(snake_case , snake_case): _UpperCAmelCase : Dict =(only_cross_attention,) * len(self.down_block_types) if isinstance(snake_case , snake_case): _UpperCAmelCase : Optional[Any] =(num_attention_heads,) * len(self.down_block_types) # down _UpperCAmelCase : int =[] _UpperCAmelCase : Optional[int] =[] _UpperCAmelCase : List[str] =block_out_channels[0] _UpperCAmelCase : int =nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case) for i, down_block_type in enumerate(self.down_block_types): _UpperCAmelCase : Tuple =output_channel _UpperCAmelCase : Dict =block_out_channels[i] _UpperCAmelCase : str =i == len(snake_case) - 1 if down_block_type == "CrossAttnDownBlock2D": _UpperCAmelCase : Tuple =FlaxCrossAttnDownBlockaD( in_channels=snake_case , out_channels=snake_case , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: _UpperCAmelCase : Optional[Any] =FlaxDownBlockaD( in_channels=snake_case , out_channels=snake_case , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(snake_case) for _ in range(self.layers_per_block): _UpperCAmelCase : Tuple =nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case) if not is_final_block: _UpperCAmelCase : List[str] =nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case) _UpperCAmelCase : List[Any] =down_blocks _UpperCAmelCase : Optional[Any] =controlnet_down_blocks # mid _UpperCAmelCase : int =block_out_channels[-1] _UpperCAmelCase : Optional[Any] =FlaxUNetMidBlockaDCrossAttn( in_channels=snake_case , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) _UpperCAmelCase : Optional[int] =nn.Conv( snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self , snake_case , snake_case , snake_case , snake_case , snake_case = 1.0 , snake_case = True , snake_case = False , ) -> Union[FlaxControlNetOutput, Tuple]: '''simple docstring''' _UpperCAmelCase : Union[str, Any] =self.controlnet_conditioning_channel_order if channel_order == "bgr": _UpperCAmelCase : Optional[int] =jnp.flip(snake_case , axis=1) # 1. time if not isinstance(snake_case , jnp.ndarray): _UpperCAmelCase : Optional[int] =jnp.array([timesteps] , dtype=jnp.intaa) elif isinstance(snake_case , jnp.ndarray) and len(timesteps.shape) == 0: _UpperCAmelCase : str =timesteps.astype(dtype=jnp.floataa) _UpperCAmelCase : Dict =jnp.expand_dims(snake_case , 0) _UpperCAmelCase : int =self.time_proj(snake_case) _UpperCAmelCase : Any =self.time_embedding(snake_case) # 2. pre-process _UpperCAmelCase : str =jnp.transpose(snake_case , (0, 2, 3, 1)) _UpperCAmelCase : Any =self.conv_in(snake_case) _UpperCAmelCase : List[str] =jnp.transpose(snake_case , (0, 2, 3, 1)) _UpperCAmelCase : Optional[int] =self.controlnet_cond_embedding(snake_case) sample += controlnet_cond # 3. down _UpperCAmelCase : Tuple =(sample,) for down_block in self.down_blocks: if isinstance(snake_case , snake_case): _UpperCAmelCase , _UpperCAmelCase : Dict =down_block(snake_case , snake_case , snake_case , deterministic=not train) else: _UpperCAmelCase , _UpperCAmelCase : Dict =down_block(snake_case , snake_case , deterministic=not train) down_block_res_samples += res_samples # 4. mid _UpperCAmelCase : List[Any] =self.mid_block(snake_case , snake_case , snake_case , deterministic=not train) # 5. contronet blocks _UpperCAmelCase : Union[str, Any] =() for down_block_res_sample, controlnet_block in zip(snake_case , self.controlnet_down_blocks): _UpperCAmelCase : List[str] =controlnet_block(snake_case) controlnet_down_block_res_samples += (down_block_res_sample,) _UpperCAmelCase : Optional[int] =controlnet_down_block_res_samples _UpperCAmelCase : List[str] =self.controlnet_mid_block(snake_case) # 6. scaling _UpperCAmelCase : Tuple =[sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=snake_case , mid_block_res_sample=snake_case)
242
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator class SCREAMING_SNAKE_CASE: """simple docstring""" def __init__( self : Any , __snake_case : int ) -> None: UpperCAmelCase : List[Any] = value UpperCAmelCase : Node | None = None UpperCAmelCase : Node | None = None class SCREAMING_SNAKE_CASE: """simple docstring""" def __init__( self : str , __snake_case : Node ) -> None: UpperCAmelCase : Optional[int] = tree def A ( self : Union[str, Any] , __snake_case : Node | None ) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : List[Any] ) -> Iterator[int]: yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
23
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( _UpperCamelCase : list[list[int]] ) -> int: """simple docstring""" for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(_UpperCamelCase ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(_UpperCamelCase ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
150
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib a__ = get_logger() a__ = None class UpperCAmelCase_ ( TensorFormatter[Mapping, "jax.Array", Mapping] ): """simple docstring""" def __init__( self , _a=None , _a=None , **_a ) -> str: super().__init__(features=_a ) import jax from jaxlib.xla_client import Device if isinstance(_a , _a ): raise ValueError( F"""Expected {device} to be a `str` not {type(_a )}, as `jaxlib.xla_extension.Device` """ '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround ''' '''the device with `str()` to get its string identifier that will be internally mapped ''' '''to the actual `jaxlib.xla_extension.Device`.''' ) _a : List[str] = device if isinstance(_a , _a ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _a : Dict = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"""Device with string identifier {self.device} not listed among the available """ F"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ F"""device: {str(jax.devices()[0] )}.""" ) _a : Any = str(jax.devices()[0] ) _a : Optional[Any] = jnp_array_kwargs @staticmethod def __lowercase ( ) -> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(_a ): device for device in jax.devices()} def __lowercase ( self , _a ) -> str: import jax import jax.numpy as jnp if isinstance(_a , _a ) and column: if all( isinstance(_a , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(_a , axis=0 ) return column def __lowercase ( self , _a ) -> Optional[Any]: import jax import jax.numpy as jnp if isinstance(_a , (str, bytes, type(_a )) ): return value elif isinstance(_a , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _a : str = {} if isinstance(_a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: _a : Dict = {'''dtype''': jnp.intaa} else: _a : Optional[int] = {'''dtype''': jnp.intaa} elif isinstance(_a , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _a : Optional[Any] = {'''dtype''': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_a , PIL.Image.Image ): _a : int = np.asarray(_a ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _a : str = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(_a , **{**default_dtype, **self.jnp_array_kwargs} ) def __lowercase ( self , _a ) -> int: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(_a , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(_a , '''__array__''' ) and not isinstance(_a , jax.Array ): _a : List[Any] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_a , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) elif isinstance(_a , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) return self._tensorize(_a ) def __lowercase ( self , _a ) -> List[Any]: return map_nested(self._recursive_tensorize , _a , map_list=_a ) def __lowercase ( self , _a ) -> Mapping: _a : Any = self.numpy_arrow_extractor().extract_row(_a ) _a : int = self.python_features_decoder.decode_row(_a ) return self.recursive_tensorize(_a ) def __lowercase ( self , _a ) -> "jax.Array": _a : int = self.numpy_arrow_extractor().extract_column(_a ) _a : Dict = self.python_features_decoder.decode_column(_a , pa_table.column_names[0] ) _a : Optional[Any] = self.recursive_tensorize(_a ) _a : Dict = self._consolidate(_a ) return column def __lowercase ( self , _a ) -> Mapping: _a : Union[str, Any] = self.numpy_arrow_extractor().extract_batch(_a ) _a : Optional[Any] = self.python_features_decoder.decode_batch(_a ) _a : Any = self.recursive_tensorize(_a ) for column_name in batch: _a : int = self._consolidate(batch[column_name] ) return batch
15
from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image 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_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract a__ = logging.get_logger(__name__) def __UpperCAmelCase ( __a : Union[str, Any] ,__a : str ,__a : Union[str, Any] ) -> List[str]: """simple docstring""" return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def __UpperCAmelCase ( __a : np.ndarray ,__a : Optional[str] ,__a : Optional[str] ) -> List[Any]: """simple docstring""" _a : str = to_pil_image(__a ) _a , _a : Optional[Any] = pil_image.size _a : Tuple = pytesseract.image_to_data(__a ,lang=__a ,output_type='''dict''' ,config=__a ) _a , _a , _a , _a , _a : List[str] = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates _a : Dict = [idx for idx, word in enumerate(__a ) if not word.strip()] _a : str = [word for idx, word in enumerate(__a ) if idx not in irrelevant_indices] _a : List[str] = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] _a : Union[str, Any] = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] _a : str = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] _a : Union[str, Any] = [coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : int = [] for x, y, w, h in zip(__a ,__a ,__a ,__a ): _a : List[str] = [x, y, x + w, y + h] actual_boxes.append(__a ) # finally, normalize the bounding boxes _a : Dict = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__a ,__a ,__a ) ) assert len(__a ) == len(__a ), "Not as many words as there are bounding boxes" return words, normalized_boxes class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = ["pixel_values"] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = 1 / 2_5_5 , _a = True , _a = None , _a = None , _a = True , _a = None , _a = "" , **_a , ) -> None: super().__init__(**_a ) _a : List[str] = size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} _a : Union[str, Any] = get_size_dict(_a ) _a : int = do_resize _a : Optional[int] = size _a : str = resample _a : str = do_rescale _a : Any = rescale_value _a : Optional[Any] = do_normalize _a : int = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _a : List[str] = image_std if image_std is not None else IMAGENET_STANDARD_STD _a : List[Any] = apply_ocr _a : Optional[int] = ocr_lang _a : Tuple = tesseract_config def __lowercase ( self , _a , _a , _a = PILImageResampling.BILINEAR , _a = None , **_a , ) -> np.ndarray: _a : Any = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) _a : Optional[int] = (size['''height'''], size['''width''']) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def __lowercase ( self , _a , _a , _a = None , **_a , ) -> np.ndarray: return rescale(_a , scale=_a , data_format=_a , **_a ) def __lowercase ( self , _a , _a , _a , _a = None , **_a , ) -> np.ndarray: return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def __lowercase ( 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: _a : Optional[int] = do_resize if do_resize is not None else self.do_resize _a : Union[str, Any] = size if size is not None else self.size _a : Any = get_size_dict(_a ) _a : List[str] = resample if resample is not None else self.resample _a : int = do_rescale if do_rescale is not None else self.do_rescale _a : Union[str, Any] = rescale_factor if rescale_factor is not None else self.rescale_factor _a : int = do_normalize if do_normalize is not None else self.do_normalize _a : str = image_mean if image_mean is not None else self.image_mean _a : Tuple = image_std if image_std is not None else self.image_std _a : Any = apply_ocr if apply_ocr is not None else self.apply_ocr _a : int = ocr_lang if ocr_lang is not None else self.ocr_lang _a : Optional[int] = tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[Any] = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.''' ) # All transformations expect numpy arrays. _a : Any = [to_numpy_array(_a ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , '''pytesseract''' ) _a : str = [] _a : str = [] for image in images: _a , _a : Union[str, Any] = apply_tesseract(_a , _a , _a ) words_batch.append(_a ) boxes_batch.append(_a ) if do_resize: _a : List[str] = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_rescale: _a : Optional[Any] = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: _a : List[Any] = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] _a : List[str] = [to_channel_dimension_format(_a , _a ) for image in images] _a : List[str] = BatchFeature(data={'''pixel_values''': images} , tensor_type=_a ) if apply_ocr: _a : Optional[int] = words_batch _a : List[Any] = boxes_batch return data
15
1
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class a__: '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase=13 , __lowerCAmelCase=7 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=99 , __lowerCAmelCase=24 , __lowerCAmelCase=2 , __lowerCAmelCase=6 , __lowerCAmelCase=37 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=512 , __lowerCAmelCase=16 , __lowerCAmelCase=2 , __lowerCAmelCase=0.02 , __lowerCAmelCase=3 , __lowerCAmelCase=None , __lowerCAmelCase=1000 , ): """simple docstring""" lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = seq_length lowerCAmelCase = is_training lowerCAmelCase = use_input_mask lowerCAmelCase = use_token_type_ids lowerCAmelCase = use_labels lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = num_labels lowerCAmelCase = scope lowerCAmelCase = range_bbox def a_ ( self): """simple docstring""" lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: lowerCAmelCase = bbox[i, j, 3] lowerCAmelCase = bbox[i, j, 1] lowerCAmelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: lowerCAmelCase = bbox[i, j, 2] lowerCAmelCase = bbox[i, j, 0] lowerCAmelCase = t lowerCAmelCase = None if self.use_input_mask: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) lowerCAmelCase = None if self.use_token_type_ids: lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) lowerCAmelCase = None lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size) lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) lowerCAmelCase = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def a_ ( self): """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): """simple docstring""" lowerCAmelCase = LiltModel(config=__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCAmelCase = model(__lowerCAmelCase , bbox=__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase) lowerCAmelCase = model(__lowerCAmelCase , bbox=__lowerCAmelCase , token_type_ids=__lowerCAmelCase) lowerCAmelCase = model(__lowerCAmelCase , bbox=__lowerCAmelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size)) def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): """simple docstring""" lowerCAmelCase = self.num_labels lowerCAmelCase = LiltForTokenClassification(config=__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCAmelCase = model( __lowerCAmelCase , bbox=__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): """simple docstring""" lowerCAmelCase = LiltForQuestionAnswering(config=__lowerCAmelCase) model.to(__lowerCAmelCase) model.eval() lowerCAmelCase = model( __lowerCAmelCase , bbox=__lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def a_ ( self): """simple docstring""" lowerCAmelCase = self.prepare_config_and_inputs() ( ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ) = config_and_inputs lowerCAmelCase = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class a__( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : int = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) UpperCAmelCase_ : Dict = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase_ : Optional[Any] = False UpperCAmelCase_ : List[Any] = False def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase): """simple docstring""" return True def a_ ( self): """simple docstring""" lowerCAmelCase = LiltModelTester(self) lowerCAmelCase = ConfigTester(self , config_class=__lowerCAmelCase , hidden_size=37) def a_ ( self): """simple docstring""" self.config_tester.run_common_tests() def a_ ( self): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCAmelCase = type self.model_tester.create_and_check_model(*__lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase) @slow def a_ ( self): """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = LiltModel.from_pretrained(__lowerCAmelCase) self.assertIsNotNone(__lowerCAmelCase) @require_torch @slow class a__( unittest.TestCase ): '''simple docstring''' def a_ ( self): """simple docstring""" lowerCAmelCase = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""").to(__lowerCAmelCase) lowerCAmelCase = torch.tensor([[1, 2]] , device=__lowerCAmelCase) lowerCAmelCase = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__lowerCAmelCase) # forward pass with torch.no_grad(): lowerCAmelCase = model(input_ids=__lowerCAmelCase , bbox=__lowerCAmelCase) lowerCAmelCase = torch.Size([1, 2, 768]) lowerCAmelCase = torch.tensor( [[-0.0653, 0.0950, -0.0061], [-0.0545, 0.0926, -0.0324]] , device=__lowerCAmelCase , ) self.assertTrue(outputs.last_hidden_state.shape , __lowerCAmelCase) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __lowerCAmelCase , atol=1E-3))
272
'''simple docstring''' from math import sqrt def snake_case__ ( _A: int = 1000000 ) -> int: '''simple docstring''' lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = 42 while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(_A , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'{solution() = }')
272
1
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs lowerCAmelCase_ = imread(r"""digital_image_processing/image_data/lena_small.jpg""") lowerCAmelCase_ = cvtColor(img, COLOR_BGR2GRAY) def lowerCamelCase_ ( )-> Optional[int]: _snake_case : List[Any] = cn.convert_to_negative(lowerCAmelCase ) # assert negative_img array for at least one True assert negative_img.any() def lowerCamelCase_ ( )-> str: with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowerCAmelCase , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def lowerCamelCase_ ( )-> int: _snake_case : Dict = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def lowerCamelCase_ ( )-> Tuple: _snake_case : Any = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() _snake_case : Any = canny.canny(lowerCAmelCase ) # assert canny array for at least one True assert canny_array.any() def lowerCamelCase_ ( )-> Dict: assert gg.gaussian_filter(lowerCAmelCase , 5 , sigma=0.9 ).all() def lowerCamelCase_ ( )-> int: # laplace diagonals _snake_case : List[str] = array([[0.2_5, 0.5, 0.2_5], [0.5, -3, 0.5], [0.2_5, 0.5, 0.2_5]] ) _snake_case : Any = conv.img_convolve(lowerCAmelCase , lowerCAmelCase ).astype(lowerCAmelCase ) assert res.any() def lowerCamelCase_ ( )-> Union[str, Any]: assert med.median_filter(lowerCAmelCase , 3 ).any() def lowerCamelCase_ ( )-> List[Any]: _snake_case , _snake_case : Any = sob.sobel_filter(lowerCAmelCase ) assert grad.any() and theta.any() def lowerCamelCase_ ( )-> int: _snake_case : Tuple = sp.make_sepia(lowerCAmelCase , 20 ) assert sepia.all() def lowerCamelCase_ ( lowerCAmelCase: str = "digital_image_processing/image_data/lena_small.jpg" )-> List[str]: _snake_case : Optional[int] = bs.Burkes(imread(lowerCAmelCase , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def lowerCamelCase_ ( lowerCAmelCase: str = "digital_image_processing/image_data/lena_small.jpg" , )-> List[Any]: _snake_case : Optional[int] = rs.NearestNeighbour(imread(lowerCAmelCase , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def lowerCamelCase_ ( )-> Dict: _snake_case : str = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. _snake_case : Dict = imread(lowerCAmelCase , 0 ) # Test for get_neighbors_pixel function() return not None _snake_case : List[Any] = 0 _snake_case : Union[str, Any] = 0 _snake_case : Tuple = image[x_coordinate][y_coordinate] _snake_case : List[Any] = lbp.get_neighbors_pixel( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image _snake_case : int = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): _snake_case : Any = lbp.local_binary_value(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) assert lbp_image.any()
260
def lowerCamelCase_ ( lowerCAmelCase: int )-> bool: return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
260
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor lowerCAmelCase__ = logging.get_logger(__name__) class lowercase_ (lowerCamelCase__ ): """simple docstring""" def __init__( self : List[Any] ,*lowercase__ : Optional[Any] ,**lowercase__ : List[Any] ): warnings.warn( '''The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use CLIPImageProcessor instead.''' ,lowercase__ ,) super().__init__(*lowercase__ ,**lowercase__ )
104
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class A ( UpperCAmelCase_ ): __UpperCAmelCase : torch.FloatTensor __UpperCAmelCase : Optional[torch.FloatTensor] = None def lowerCAmelCase_ ( __A, __A=0.999, __A="cosine", ) -> Tuple: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(__A ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__A ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase__ = [] for i in range(__A ): UpperCAmelCase__ = i / num_diffusion_timesteps UpperCAmelCase__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__A ) / alpha_bar_fn(__A ), __A ) ) return torch.tensor(__A, dtype=torch.floataa ) class A ( UpperCAmelCase_ , UpperCAmelCase_ ): @register_to_config def __init__(self : List[str] , __UpperCAmelCase : int = 1_0_0_0 , __UpperCAmelCase : str = "fixed_small_log" , __UpperCAmelCase : bool = True , __UpperCAmelCase : Optional[float] = 1.0 , __UpperCAmelCase : str = "epsilon" , __UpperCAmelCase : str = "squaredcos_cap_v2" , ) -> Optional[int]: """simple docstring""" if beta_schedule != "squaredcos_cap_v2": raise ValueError("UnCLIPScheduler only supports `beta_schedule`: 'squaredcos_cap_v2'" ) UpperCAmelCase__ = betas_for_alpha_bar(__UpperCAmelCase ) UpperCAmelCase__ = 1.0 - self.betas UpperCAmelCase__ = torch.cumprod(self.alphas , dim=0 ) UpperCAmelCase__ = torch.tensor(1.0 ) # standard deviation of the initial noise distribution UpperCAmelCase__ = 1.0 # setable values UpperCAmelCase__ = None UpperCAmelCase__ = torch.from_numpy(np.arange(0 , __UpperCAmelCase )[::-1].copy() ) UpperCAmelCase__ = variance_type def lowercase_ (self : List[str] , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : Optional[int] = None ) -> torch.FloatTensor: """simple docstring""" return sample def lowercase_ (self : int , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, torch.device] = None ) -> Any: """simple docstring""" UpperCAmelCase__ = num_inference_steps UpperCAmelCase__ = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) UpperCAmelCase__ = (np.arange(0 , __UpperCAmelCase ) * step_ratio).round()[::-1].copy().astype(np.intaa ) UpperCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase ) def lowercase_ (self : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Tuple=None , __UpperCAmelCase : List[str]=None ) -> Tuple: """simple docstring""" if prev_timestep is None: UpperCAmelCase__ = t - 1 UpperCAmelCase__ = self.alphas_cumprod[t] UpperCAmelCase__ = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCAmelCase__ = 1 - alpha_prod_t UpperCAmelCase__ = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCAmelCase__ = self.betas[t] else: UpperCAmelCase__ = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample UpperCAmelCase__ = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: UpperCAmelCase__ = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": UpperCAmelCase__ = torch.log(torch.clamp(__UpperCAmelCase , min=1E-20 ) ) UpperCAmelCase__ = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler UpperCAmelCase__ = variance.log() UpperCAmelCase__ = beta.log() UpperCAmelCase__ = (predicted_variance + 1) / 2 UpperCAmelCase__ = frac * max_log + (1 - frac) * min_log return variance def lowercase_ (self : Optional[int] , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : int , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : bool = True , ) -> Union[UnCLIPSchedulerOutput, Tuple]: """simple docstring""" UpperCAmelCase__ = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": UpperCAmelCase__ , UpperCAmelCase__ = torch.split(__UpperCAmelCase , sample.shape[1] , dim=1 ) else: UpperCAmelCase__ = None # 1. compute alphas, betas if prev_timestep is None: UpperCAmelCase__ = t - 1 UpperCAmelCase__ = self.alphas_cumprod[t] UpperCAmelCase__ = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCAmelCase__ = 1 - alpha_prod_t UpperCAmelCase__ = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCAmelCase__ = self.betas[t] UpperCAmelCase__ = self.alphas[t] else: UpperCAmelCase__ = 1 - alpha_prod_t / alpha_prod_t_prev UpperCAmelCase__ = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": UpperCAmelCase__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": UpperCAmelCase__ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`""" " for the UnCLIPScheduler." ) # 3. Clip "predicted x_0" if self.config.clip_sample: UpperCAmelCase__ = torch.clamp( __UpperCAmelCase , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase__ = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t UpperCAmelCase__ = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCAmelCase__ = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise UpperCAmelCase__ = 0 if t > 0: UpperCAmelCase__ = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=__UpperCAmelCase , device=model_output.device ) UpperCAmelCase__ = self._get_variance( __UpperCAmelCase , predicted_variance=__UpperCAmelCase , prev_timestep=__UpperCAmelCase , ) if self.variance_type == "fixed_small_log": UpperCAmelCase__ = variance elif self.variance_type == "learned_range": UpperCAmelCase__ = (0.5 * variance).exp() else: raise ValueError( f"""variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`""" " for the UnCLIPScheduler." ) UpperCAmelCase__ = variance * variance_noise UpperCAmelCase__ = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=__UpperCAmelCase , pred_original_sample=__UpperCAmelCase ) def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : torch.IntTensor , ) -> torch.FloatTensor: """simple docstring""" UpperCAmelCase__ = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) UpperCAmelCase__ = timesteps.to(original_samples.device ) UpperCAmelCase__ = alphas_cumprod[timesteps] ** 0.5 UpperCAmelCase__ = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): UpperCAmelCase__ = sqrt_alpha_prod.unsqueeze(-1 ) UpperCAmelCase__ = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCAmelCase__ = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): UpperCAmelCase__ = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) UpperCAmelCase__ = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
65
0
'''simple docstring''' from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class UpperCAmelCase__ : """simple docstring""" def __lowercase ( self : Any ,_a : List[Any] ): '''simple docstring''' raise NotImplementedError() def __lowercase ( self : List[str] ): '''simple docstring''' raise NotImplementedError() class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Tuple ,_a : "AutoTokenizer" ,_a : bool = False ,**_a : Tuple ): '''simple docstring''' _a : Union[str, Any] = tokenizer _a : Any = skip_prompt _a : List[str] = decode_kwargs # variables used in the streaming process _a : Tuple = [] _a : int = 0 _a : List[Any] = True def __lowercase ( self : List[str] ,_a : Tuple ): '''simple docstring''' if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError('TextStreamer only supports batch size 1' ) elif len(value.shape ) > 1: _a : int = value[0] if self.skip_prompt and self.next_tokens_are_prompt: _a : Tuple = False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) _a : Any = self.tokenizer.decode(self.token_cache ,**self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith('\n' ): _a : str = text[self.print_len :] _a : Optional[Any] = [] _a : List[str] = 0 # If the last token is a CJK character, we print the characters. elif len(_a ) > 0 and self._is_chinese_char(ord(text[-1] ) ): _a : List[str] = text[self.print_len :] self.print_len += len(_a ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: _a : int = text[self.print_len : text.rfind(' ' ) + 1] self.print_len += len(_a ) self.on_finalized_text(_a ) def __lowercase ( self : List[Any] ): '''simple docstring''' if len(self.token_cache ) > 0: _a : Dict = self.tokenizer.decode(self.token_cache ,**self.decode_kwargs ) _a : Tuple = text[self.print_len :] _a : str = [] _a : str = 0 else: _a : Tuple = '' _a : str = True self.on_finalized_text(_a ,stream_end=_a ) def __lowercase ( self : Dict ,_a : str ,_a : bool = False ): '''simple docstring''' print(_a ,flush=_a ,end='' if not stream_end else None ) def __lowercase ( self : List[str] ,_a : Optional[Any] ): '''simple docstring''' if ( (cp >= 0X4e00 and cp <= 0X9fff) or (cp >= 0X3400 and cp <= 0X4dbf) # or (cp >= 0X2_0000 and cp <= 0X2_a6df) # or (cp >= 0X2_a700 and cp <= 0X2_b73f) # or (cp >= 0X2_b740 and cp <= 0X2_b81f) # or (cp >= 0X2_b820 and cp <= 0X2_ceaf) # or (cp >= 0Xf900 and cp <= 0Xfaff) or (cp >= 0X2_f800 and cp <= 0X2_fa1f) # ): # return True return False class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : int ,_a : "AutoTokenizer" ,_a : bool = False ,_a : Optional[float] = None ,**_a : Union[str, Any] ): '''simple docstring''' super().__init__(_a ,_a ,**_a ) _a : List[str] = Queue() _a : Union[str, Any] = None _a : Optional[Any] = timeout def __lowercase ( self : str ,_a : str ,_a : bool = False ): '''simple docstring''' self.text_queue.put(_a ,timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal ,timeout=self.timeout ) def __iter__( self : List[str] ): '''simple docstring''' return self def __lowercase ( self : List[Any] ): '''simple docstring''' _a : Tuple = self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
5
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def UpperCAmelCase_ (__a : str , __a : Dict=0.999 , __a : List[str]="cosine" , ): """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(__a : Union[str, Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__a : int ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _a : Tuple = [] for i in range(__a ): _a : Union[str, Any] = i / num_diffusion_timesteps _a : Any = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__a ) / alpha_bar_fn(__a ) , __a ) ) return torch.tensor(__a , dtype=torch.floataa ) class UpperCAmelCase__ ( lowercase__ , lowercase__ ): """simple docstring""" __UpperCAmelCase : Optional[Any] = [e.name for e in KarrasDiffusionSchedulers] __UpperCAmelCase : Dict = 2 @register_to_config def __init__( self : str ,_a : int = 1000 ,_a : float = 0.0_0085 ,_a : float = 0.012 ,_a : str = "linear" ,_a : Optional[Union[np.ndarray, List[float]]] = None ,_a : str = "epsilon" ,_a : Optional[bool] = False ,_a : Optional[bool] = False ,_a : float = 1.0 ,_a : str = "linspace" ,_a : int = 0 ,): '''simple docstring''' if trained_betas is not None: _a : List[str] = torch.tensor(_a ,dtype=torch.floataa ) elif beta_schedule == "linear": _a : Tuple = torch.linspace(_a ,_a ,_a ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _a : List[str] = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,_a ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _a : Dict = betas_for_alpha_bar(_a ,alpha_transform_type='cosine' ) elif beta_schedule == "exp": _a : Tuple = betas_for_alpha_bar(_a ,alpha_transform_type='exp' ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _a : Optional[Any] = 1.0 - self.betas _a : Optional[int] = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(_a ,_a ,_a ) _a : Optional[int] = use_karras_sigmas def __lowercase ( self : Any ,_a : Union[str, Any] ,_a : Optional[Any]=None ): '''simple docstring''' if schedule_timesteps is None: _a : List[Any] = self.timesteps _a : Dict = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _a : int = 1 if len(_a ) > 1 else 0 else: _a : str = timestep.cpu().item() if torch.is_tensor(_a ) else timestep _a : str = self._index_counter[timestep_int] return indices[pos].item() @property def __lowercase ( self : Optional[Any] ): '''simple docstring''' if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __lowercase ( self : int ,_a : torch.FloatTensor ,_a : Union[float, torch.FloatTensor] ,): '''simple docstring''' _a : List[Any] = self.index_for_timestep(_a ) _a : Tuple = self.sigmas[step_index] _a : Optional[Any] = sample / ((sigma**2 + 1) ** 0.5) return sample def __lowercase ( self : Any ,_a : int ,_a : Union[str, torch.device] = None ,_a : Optional[int] = None ,): '''simple docstring''' _a : Optional[Any] = num_inference_steps _a : Dict = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _a : Optional[Any] = np.linspace(0 ,num_train_timesteps - 1 ,_a ,dtype=_a )[::-1].copy() elif self.config.timestep_spacing == "leading": _a : str = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _a : int = (np.arange(0 ,_a ) * step_ratio).round()[::-1].copy().astype(_a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _a : Any = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _a : Union[str, Any] = (np.arange(_a ,0 ,-step_ratio )).round().copy().astype(_a ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) _a : Tuple = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _a : Union[str, Any] = np.log(_a ) _a : str = np.interp(_a ,np.arange(0 ,len(_a ) ) ,_a ) if self.config.use_karras_sigmas: _a : List[Any] = self._convert_to_karras(in_sigmas=_a ,num_inference_steps=self.num_inference_steps ) _a : Dict = np.array([self._sigma_to_t(_a ,_a ) for sigma in sigmas] ) _a : int = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _a : Union[str, Any] = torch.from_numpy(_a ).to(device=_a ) _a : Any = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) _a : List[Any] = torch.from_numpy(_a ) _a : List[str] = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(_a ).startswith('mps' ): # mps does not support float64 _a : Tuple = timesteps.to(_a ,dtype=torch.floataa ) else: _a : Dict = timesteps.to(device=_a ) # empty dt and derivative _a : Tuple = None _a : Optional[Any] = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _a : Union[str, Any] = defaultdict(_a ) def __lowercase ( self : str ,_a : Dict ,_a : Dict ): '''simple docstring''' _a : Optional[int] = np.log(_a ) # get distribution _a : Union[str, Any] = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range _a : List[Any] = np.cumsum((dists >= 0) ,axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) _a : Tuple = low_idx + 1 _a : Union[str, Any] = log_sigmas[low_idx] _a : Optional[Any] = log_sigmas[high_idx] # interpolate sigmas _a : Optional[Any] = (low - log_sigma) / (low - high) _a : List[str] = np.clip(_a ,0 ,1 ) # transform interpolation to time range _a : Union[str, Any] = (1 - w) * low_idx + w * high_idx _a : List[str] = t.reshape(sigma.shape ) return t def __lowercase ( self : int ,_a : torch.FloatTensor ,_a : Tuple ): '''simple docstring''' _a : float = in_sigmas[-1].item() _a : float = in_sigmas[0].item() _a : Tuple = 7.0 # 7.0 is the value used in the paper _a : str = np.linspace(0 ,1 ,_a ) _a : Optional[Any] = sigma_min ** (1 / rho) _a : Union[str, Any] = sigma_max ** (1 / rho) _a : str = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def __lowercase ( self : Optional[Any] ): '''simple docstring''' return self.dt is None def __lowercase ( self : int ,_a : Union[torch.FloatTensor, np.ndarray] ,_a : Union[float, torch.FloatTensor] ,_a : Union[torch.FloatTensor, np.ndarray] ,_a : bool = True ,): '''simple docstring''' _a : Union[str, Any] = self.index_for_timestep(_a ) # advance index counter by 1 _a : Any = timestep.cpu().item() if torch.is_tensor(_a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _a : Tuple = self.sigmas[step_index] _a : int = self.sigmas[step_index + 1] else: # 2nd order / Heun's method _a : List[str] = self.sigmas[step_index - 1] _a : List[Any] = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _a : Optional[int] = 0 _a : Tuple = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _a : Dict = sigma_hat if self.state_in_first_order else sigma_next _a : Optional[int] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _a : List[Any] = sigma_hat if self.state_in_first_order else sigma_next _a : List[Any] = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": _a : Union[str, Any] = model_output else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: _a : Optional[int] = pred_original_sample.clamp( -self.config.clip_sample_range ,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _a : Optional[Any] = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _a : Any = sigma_next - sigma_hat # store for 2nd order step _a : int = derivative _a : List[str] = dt _a : Union[str, Any] = sample else: # 2. 2nd order / Heun's method _a : Dict = (sample - pred_original_sample) / sigma_next _a : Tuple = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample _a : Optional[Any] = self.dt _a : Union[str, Any] = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" _a : List[Any] = None _a : Union[str, Any] = None _a : Dict = None _a : str = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def __lowercase ( self : Optional[int] ,_a : torch.FloatTensor ,_a : torch.FloatTensor ,_a : torch.FloatTensor ,): '''simple docstring''' _a : str = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(_a ): # mps does not support float64 _a : Dict = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) _a : Optional[Any] = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: _a : int = self.timesteps.to(original_samples.device ) _a : Optional[Any] = timesteps.to(original_samples.device ) _a : Any = [self.index_for_timestep(_a ,_a ) for t in timesteps] _a : Optional[int] = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _a : Optional[Any] = sigma.unsqueeze(-1 ) _a : Any = original_samples + noise * sigma return noisy_samples def __len__( self : Optional[int] ): '''simple docstring''' return self.config.num_train_timesteps
5
1
"""simple docstring""" def __UpperCAmelCase ( lowercase ): """simple docstring""" if p < 2: raise ValueError("""p should not be less than 2!""" ) elif p == 2: return True _UpperCAmelCase = 4 _UpperCAmelCase = (1 << p) - 1 for _ in range(p - 2 ): _UpperCAmelCase = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(1_1))
289
"""simple docstring""" 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 MobileViTImageProcessor class a ( unittest.TestCase ): def __init__( self : Dict , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=7 , __lowerCAmelCase : Optional[Any]=3 , __lowerCAmelCase : Optional[Any]=18 , __lowerCAmelCase : str=30 , __lowerCAmelCase : List[str]=400 , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : str=None , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : int=None , __lowerCAmelCase : List[str]=True , ): _UpperCAmelCase = size if size is not None else {"""shortest_edge""": 20} _UpperCAmelCase = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_center_crop _UpperCAmelCase = crop_size _UpperCAmelCase = do_flip_channel_order def lowerCAmelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class a ( lowerCAmelCase_ , unittest.TestCase ): _snake_case : Optional[int] = MobileViTImageProcessor if is_vision_available() else None def lowerCAmelCase_ ( self : Optional[Any] ): _UpperCAmelCase = MobileViTImageProcessingTester(self ) @property def lowerCAmelCase_ ( self : Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase_ ( self : Dict ): _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """size""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """do_center_crop""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """center_crop""" ) ) self.assertTrue(hasattr(__lowerCAmelCase , """do_flip_channel_order""" ) ) def lowerCAmelCase_ ( self : Union[str, Any] ): _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCAmelCase_ ( self : List[str] ): pass def lowerCAmelCase_ ( self : Dict ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , Image.Image ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _UpperCAmelCase = image_processing(__lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase_ ( self : str ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , numpify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , np.ndarray ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _UpperCAmelCase = image_processing(__lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase_ ( self : Optional[int] ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , torchify=__lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(__lowerCAmelCase , torch.Tensor ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _UpperCAmelCase = image_processing(__lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
289
1
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters _SCREAMING_SNAKE_CASE = (720, 1280) # Height, Width _SCREAMING_SNAKE_CASE = (0.4, 0.6) # if height or width lower than this scale, drop it. _SCREAMING_SNAKE_CASE = 1 / 100 _SCREAMING_SNAKE_CASE = "" _SCREAMING_SNAKE_CASE = "" _SCREAMING_SNAKE_CASE = "" _SCREAMING_SNAKE_CASE = 250 def __lowerCamelCase ( ) -> None: snake_case , snake_case = get_dataset(__lowerCAmelCase , __lowerCAmelCase ) for index in range(__lowerCAmelCase ): snake_case = random.sample(range(len(__lowerCAmelCase ) ) , 4 ) snake_case , snake_case , snake_case = update_image_and_anno( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , filter_scale=__lowerCAmelCase , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' snake_case = random_chars(32 ) snake_case = path.split(os.sep )[-1].rsplit(""".""" , 1 )[0] snake_case = F'''{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}''' cva.imwrite(F'''{file_root}.jpg''' , __lowerCAmelCase , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}''' ) snake_case = [] for anno in new_annos: snake_case = anno[3] - anno[1] snake_case = anno[4] - anno[2] snake_case = anno[1] + width / 2 snake_case = anno[2] + height / 2 snake_case = F'''{anno[0]} {x_center} {y_center} {width} {height}''' annos_list.append(__lowerCAmelCase ) with open(F'''{file_root}.txt''' , """w""" ) as outfile: outfile.write("""\n""".join(line for line in annos_list ) ) def __lowerCamelCase ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> tuple[list, list]: snake_case = [] snake_case = [] for label_file in glob.glob(os.path.join(__lowerCAmelCase , """*.txt""" ) ): snake_case = label_file.split(os.sep )[-1].rsplit(""".""" , 1 )[0] with open(__lowerCAmelCase ) as in_file: snake_case = in_file.readlines() snake_case = os.path.join(__lowerCAmelCase , F'''{label_name}.jpg''' ) snake_case = [] for obj_list in obj_lists: snake_case = obj_list.rstrip("""\n""" ).split(""" """ ) snake_case = float(obj[1] ) - float(obj[3] ) / 2 snake_case = float(obj[2] ) - float(obj[4] ) / 2 snake_case = float(obj[1] ) + float(obj[3] ) / 2 snake_case = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(__lowerCAmelCase ) labels.append(__lowerCAmelCase ) return img_paths, labels def __lowerCamelCase ( __lowerCAmelCase : list , __lowerCAmelCase : list , __lowerCAmelCase : list[int] , __lowerCAmelCase : tuple[int, int] , __lowerCAmelCase : tuple[float, float] , __lowerCAmelCase : float = 0.0 , ) -> tuple[list, list, str]: snake_case = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) snake_case = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) snake_case = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) snake_case = int(scale_x * output_size[1] ) snake_case = int(scale_y * output_size[0] ) snake_case = [] snake_case = [] for i, index in enumerate(__lowerCAmelCase ): snake_case = all_img_list[index] path_list.append(__lowerCAmelCase ) snake_case = all_annos[index] snake_case = cva.imread(__lowerCAmelCase ) if i == 0: # top-left snake_case = cva.resize(__lowerCAmelCase , (divid_point_x, divid_point_y) ) snake_case = img for bbox in img_annos: snake_case = bbox[1] * scale_x snake_case = bbox[2] * scale_y snake_case = bbox[3] * scale_x snake_case = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right snake_case = cva.resize(__lowerCAmelCase , (output_size[1] - divid_point_x, divid_point_y) ) snake_case = img for bbox in img_annos: snake_case = scale_x + bbox[1] * (1 - scale_x) snake_case = bbox[2] * scale_y snake_case = scale_x + bbox[3] * (1 - scale_x) snake_case = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left snake_case = cva.resize(__lowerCAmelCase , (divid_point_x, output_size[0] - divid_point_y) ) snake_case = img for bbox in img_annos: snake_case = bbox[1] * scale_x snake_case = scale_y + bbox[2] * (1 - scale_y) snake_case = bbox[3] * scale_x snake_case = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right snake_case = cva.resize( __lowerCAmelCase , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) snake_case = img for bbox in img_annos: snake_case = scale_x + bbox[1] * (1 - scale_x) snake_case = scale_y + bbox[2] * (1 - scale_y) snake_case = scale_x + bbox[3] * (1 - scale_x) snake_case = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: snake_case = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def __lowerCamelCase ( __lowerCAmelCase : int ) -> str: assert number_char > 1, "The number of character should greater than 1" snake_case = ascii_lowercase + digits return "".join(random.choice(__lowerCAmelCase ) for _ in range(__lowerCAmelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
3
'''simple docstring''' import requests from bsa import BeautifulSoup def __lowerCamelCase ( __lowerCAmelCase : str = "https://www.worldometers.info/coronavirus" ) -> dict: snake_case = BeautifulSoup(requests.get(__lowerCAmelCase ).text , """html.parser""" ) snake_case = soup.findAll("""h1""" ) snake_case = soup.findAll("""div""" , {"""class""": """maincounter-number"""} ) keys += soup.findAll("""span""" , {"""class""": """panel-title"""} ) values += soup.findAll("""div""" , {"""class""": """number-table-main"""} ) return {key.text.strip(): value.text.strip() for key, value in zip(__lowerCAmelCase , __lowerCAmelCase )} if __name__ == "__main__": print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") for key, value in world_covidaa_stats().items(): print(F"""{key}\n{value}\n""")
3
1
def a__ ( A_ ): '''simple docstring''' if not all(x.isalpha() for x in string ): raise ValueError("""String must only contain alphabetic characters.""" ) __magic_name__ = sorted(string.lower() ) return len(A_ ) == len(set(A_ ) ) if __name__ == "__main__": __lowerCAmelCase : Dict = input('Enter a string ').strip() __lowerCAmelCase : Union[str, Any] = is_isogram(input_str) print(F'''{input_str} is {"an" if isogram else "not an"} isogram.''')
88
import re import string import numpy as np import datasets __lowerCAmelCase : Optional[int] = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' __lowerCAmelCase : Optional[int] = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' __lowerCAmelCase : Optional[int] = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _lowercase ( self : str ) -> Optional[int]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : int=False , UpperCamelCase__ : Tuple=False , ) -> Dict: """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: __magic_name__ = np.array([re.sub(UpperCamelCase__ , """""" , UpperCamelCase__ ) for x in predictions] ) __magic_name__ = np.array([re.sub(UpperCamelCase__ , """""" , UpperCamelCase__ ) for x in references] ) else: __magic_name__ = np.asarray(UpperCamelCase__ ) __magic_name__ = np.asarray(UpperCamelCase__ ) if ignore_case: __magic_name__ = np.char.lower(UpperCamelCase__ ) __magic_name__ = np.char.lower(UpperCamelCase__ ) if ignore_punctuation: __magic_name__ = string.punctuation.maketrans("""""" , """""" , string.punctuation ) __magic_name__ = np.char.translate(UpperCamelCase__ , table=UpperCamelCase__ ) __magic_name__ = np.char.translate(UpperCamelCase__ , table=UpperCamelCase__ ) if ignore_numbers: __magic_name__ = string.digits.maketrans("""""" , """""" , string.digits ) __magic_name__ = np.char.translate(UpperCamelCase__ , table=UpperCamelCase__ ) __magic_name__ = np.char.translate(UpperCamelCase__ , table=UpperCamelCase__ ) __magic_name__ = predictions == references return {"exact_match": np.mean(UpperCamelCase__ ) * 100}
88
1
def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[list[int]] ): def update_area_of_max_square(__lowerCamelCase : int , __lowerCamelCase : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 snake_case : List[Any] = update_area_of_max_square(__lowerCamelCase , col + 1 ) snake_case : int = update_area_of_max_square(row + 1 , col + 1 ) snake_case : Union[str, Any] = update_area_of_max_square(row + 1 , __lowerCamelCase ) if mat[row][col]: snake_case : Optional[Any] = 1 + min([right, diagonal, down] ) snake_case : List[Any] = max(largest_square_area[0] , __lowerCamelCase ) return sub_problem_sol else: return 0 snake_case : Union[str, Any] = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[list[int]] ): def update_area_of_max_square_using_dp_array( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] snake_case : Optional[Any] = update_area_of_max_square_using_dp_array(__lowerCamelCase , col + 1 , __lowerCamelCase ) snake_case : str = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , __lowerCamelCase ) snake_case : Optional[int] = update_area_of_max_square_using_dp_array(row + 1 , __lowerCamelCase , __lowerCamelCase ) if mat[row][col]: snake_case : Union[str, Any] = 1 + min([right, diagonal, down] ) snake_case : Dict = max(largest_square_area[0] , __lowerCamelCase ) snake_case : Optional[int] = sub_problem_sol return sub_problem_sol else: return 0 snake_case : Any = [0] snake_case : Optional[Any] = [[-1] * cols for _ in range(__lowerCamelCase )] update_area_of_max_square_using_dp_array(0 , 0 , __lowerCamelCase ) return largest_square_area[0] def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[list[int]] ): snake_case : Optional[Any] = [[0] * (cols + 1) for _ in range(rows + 1 )] snake_case : Optional[int] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): snake_case : Optional[int] = dp_array[row][col + 1] snake_case : Any = dp_array[row + 1][col + 1] snake_case : Optional[int] = dp_array[row + 1][col] if mat[row][col] == 1: snake_case : Tuple = 1 + min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) snake_case : Tuple = max(dp_array[row][col] , __lowerCamelCase ) else: snake_case : int = 0 return largest_square_area def UpperCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : list[list[int]] ): snake_case : Optional[Any] = [0] * (cols + 1) snake_case : Any = [0] * (cols + 1) snake_case : int = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): snake_case : Dict = current_row[col + 1] snake_case : List[str] = next_row[col + 1] snake_case : Optional[int] = next_row[col] if mat[row][col] == 1: snake_case : Optional[Any] = 1 + min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) snake_case : List[str] = max(current_row[col] , __lowerCamelCase ) else: snake_case : str = 0 snake_case : List[str] = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
354
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image __lowerCamelCase = ["""text""", """image""", """audio"""] def UpperCamelCase ( __lowerCamelCase : List[str] ): snake_case : str = [] for input_type in input_types: if input_type == "text": inputs.append("Text input" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3000 ) ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): inputs.append(create_inputs(__lowerCamelCase ) ) else: raise ValueError(f"""Invalid type requested: {input_type}""" ) return inputs def UpperCamelCase ( __lowerCamelCase : List ): snake_case : List[str] = [] for output in outputs: if isinstance(__lowerCamelCase , (str, AgentText) ): output_types.append("text" ) elif isinstance(__lowerCamelCase , (Image.Image, AgentImage) ): output_types.append("image" ) elif isinstance(__lowerCamelCase , (torch.Tensor, AgentAudio) ): output_types.append("audio" ) else: raise ValueError(f"""Invalid output: {output}""" ) return output_types @is_tool_test class UpperCAmelCase : def _SCREAMING_SNAKE_CASE (self : List[str] ) -> List[str]: '''simple docstring''' self.assertTrue(hasattr(self.tool , "inputs" ) ) self.assertTrue(hasattr(self.tool , "outputs" ) ) snake_case : List[Any] = self.tool.inputs for _input in inputs: if isinstance(_input , snake_case__ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) snake_case : str = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' snake_case : List[str] = create_inputs(self.tool.inputs ) snake_case : Dict = self.tool(*snake_case__ ) # There is a single output if len(self.tool.outputs ) == 1: snake_case : List[Any] = [outputs] self.assertListEqual(output_types(snake_case__ ) , self.tool.outputs ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> List[Any]: '''simple docstring''' self.assertTrue(hasattr(self.tool , "description" ) ) self.assertTrue(hasattr(self.tool , "default_checkpoint" ) ) self.assertTrue(self.tool.description.startswith("This is a tool that" ) ) def _SCREAMING_SNAKE_CASE (self : int ) -> Union[str, Any]: '''simple docstring''' snake_case : str = create_inputs(self.tool.inputs ) snake_case : int = self.tool(*snake_case__ ) if not isinstance(snake_case__ , snake_case__ ): snake_case : Optional[Any] = [outputs] self.assertEqual(len(snake_case__ ) , len(self.tool.outputs ) ) for output, output_type in zip(snake_case__ , self.tool.outputs ): snake_case : Any = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(snake_case__ , snake_case__ ) ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Optional[int]: '''simple docstring''' snake_case : List[Any] = create_inputs(self.tool.inputs ) snake_case : str = [] for _input, input_type in zip(snake_case__ , self.tool.inputs ): if isinstance(snake_case__ , snake_case__ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error snake_case : Optional[int] = self.tool(*snake_case__ ) if not isinstance(snake_case__ , snake_case__ ): snake_case : List[str] = [outputs] self.assertEqual(len(snake_case__ ) , len(self.tool.outputs ) )
10
0
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class a__ ( UpperCamelCase__ ): def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" return 0.0 def _a ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : int ): __lowerCAmelCase = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __lowerCAmelCase = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _a ( SCREAMING_SNAKE_CASE_ : FilterType , SCREAMING_SNAKE_CASE_ : int ): __lowerCAmelCase = 5_12 __lowerCAmelCase = [1] + [0] * (size - 1) __lowerCAmelCase = [filter_type.process(SCREAMING_SNAKE_CASE_ ) for item in inputs] __lowerCAmelCase = [0] * (samplerate - size) # zero-padding outputs += filler __lowerCAmelCase = np.abs(np.fft.fft(SCREAMING_SNAKE_CASE_ ) ) __lowerCAmelCase = 20 * np.logaa(SCREAMING_SNAKE_CASE_ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) # Display within reasonable bounds __lowerCAmelCase = get_bounds(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("Gain (dB)" ) plt.plot(SCREAMING_SNAKE_CASE_ ) plt.show() def _a ( SCREAMING_SNAKE_CASE_ : FilterType , SCREAMING_SNAKE_CASE_ : int ): __lowerCAmelCase = 5_12 __lowerCAmelCase = [1] + [0] * (size - 1) __lowerCAmelCase = [filter_type.process(SCREAMING_SNAKE_CASE_ ) for item in inputs] __lowerCAmelCase = [0] * (samplerate - size) # zero-padding outputs += filler __lowerCAmelCase = np.angle(np.fft.fft(SCREAMING_SNAKE_CASE_ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("Frequency (Hz)" ) plt.xscale("log" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("Phase shift (Radians)" ) plt.plot(np.unwrap(SCREAMING_SNAKE_CASE_ , -2 * pi ) ) plt.show()
92
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Dict = logging.get_logger(__name__) UpperCAmelCase : Tuple = { """caidas/swin2sr-classicalsr-x2-64""": ( """https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Any = """swin2sr""" _lowercase : Tuple = { """hidden_size""": """embed_dim""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self , lowerCAmelCase__=6_4 , lowerCAmelCase__=1 , lowerCAmelCase__=3 , lowerCAmelCase__=1_8_0 , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=[6, 6, 6, 6, 6, 6] , lowerCAmelCase__=8 , lowerCAmelCase__=2.0 , lowerCAmelCase__=True , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.1 , lowerCAmelCase__="gelu" , lowerCAmelCase__=False , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-5 , lowerCAmelCase__=2 , lowerCAmelCase__=1.0 , lowerCAmelCase__="1conv" , lowerCAmelCase__="pixelshuffle" , **lowerCAmelCase__ , ) -> int: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) a__ : Optional[Any] =image_size a__ : Dict =patch_size a__ : Tuple =num_channels a__ : Union[str, Any] =embed_dim a__ : Optional[Any] =depths a__ : List[str] =len(lowerCAmelCase__ ) a__ : Any =num_heads a__ : Any =window_size a__ : str =mlp_ratio a__ : List[str] =qkv_bias a__ : Dict =hidden_dropout_prob a__ : List[str] =attention_probs_dropout_prob a__ : Dict =drop_path_rate a__ : Optional[Any] =hidden_act a__ : Union[str, Any] =use_absolute_embeddings a__ : Optional[Any] =layer_norm_eps a__ : List[Any] =initializer_range a__ : int =upscale a__ : Optional[int] =img_range a__ : Any =resi_connection a__ : Optional[Any] =upsampler
95
0
"""simple docstring""" from collections.abc import Sequence from queue import Queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[str]=None , lowercase_ : Tuple=None): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = start SCREAMING_SNAKE_CASE_ : int = end SCREAMING_SNAKE_CASE_ : Any = val SCREAMING_SNAKE_CASE_ : List[Any] = (start + end) // 2 SCREAMING_SNAKE_CASE_ : Dict = left SCREAMING_SNAKE_CASE_ : List[str] = right def __repr__( self : Union[str, Any]): '''simple docstring''' return F'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})' class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , lowercase_ : Sequence , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = collection SCREAMING_SNAKE_CASE_ : Any = function if self.collection: SCREAMING_SNAKE_CASE_ : List[Any] = self._build_tree(0 , len(lowercase_) - 1) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : List[str] , lowercase_ : Optional[int]): '''simple docstring''' self._update_tree(self.root , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : Any , lowercase_ : List[Any]): '''simple docstring''' return self._query_range(self.root , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : int , lowercase_ : Any , lowercase_ : Any): '''simple docstring''' if start == end: return SegmentTreeNode(lowercase_ , lowercase_ , self.collection[start]) SCREAMING_SNAKE_CASE_ : Optional[int] = (start + end) // 2 SCREAMING_SNAKE_CASE_ : Tuple = self._build_tree(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : str = self._build_tree(mid + 1 , lowercase_) return SegmentTreeNode(lowercase_ , lowercase_ , self.fn(left.val , right.val) , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowercase_ : List[Any] , lowercase_ : Any , lowercase_ : Optional[Any]): '''simple docstring''' if node.start == i and node.end == i: SCREAMING_SNAKE_CASE_ : Dict = val return if i <= node.mid: self._update_tree(node.left , lowercase_ , lowercase_) else: self._update_tree(node.right , lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Optional[int] = self.fn(node.left.val , node.right.val) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any]): '''simple docstring''' if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , lowercase_ , lowercase_) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , lowercase_ , node.mid) , self._query_range(node.right , node.mid + 1 , lowercase_) , ) else: # range in right child tree return self._query_range(node.right , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' if self.root is not None: SCREAMING_SNAKE_CASE_ : Dict = Queue() queue.put(self.root) while not queue.empty(): SCREAMING_SNAKE_CASE_ : Tuple = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("""*""" * 50) UpperCAmelCase_ : Any = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
318
"""simple docstring""" from __future__ import annotations import queue class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[int] = data SCREAMING_SNAKE_CASE_ : Tuple = None SCREAMING_SNAKE_CASE_ : Dict = None def _A () -> TreeNode: """simple docstring""" print('''\n********Press N to stop entering at any point of time********\n''' ) SCREAMING_SNAKE_CASE_ : List[Any] = input('''Enter the value of the root node: ''' ).strip().lower() SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() SCREAMING_SNAKE_CASE_ : Union[str, Any] = TreeNode(int(__a ) ) q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Optional[int] = q.get() SCREAMING_SNAKE_CASE_ : List[str] = f'Enter the left node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : Optional[int] = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : List[str] = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = left_node q.put(__a ) SCREAMING_SNAKE_CASE_ : str = f'Enter the right node of {node_found.data}: ' SCREAMING_SNAKE_CASE_ : str = input(__a ).strip().lower() or '''n''' if check == "n": return tree_node SCREAMING_SNAKE_CASE_ : Any = TreeNode(int(__a ) ) SCREAMING_SNAKE_CASE_ : int = right_node q.put(__a ) raise def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return print(node.data , end=''',''' ) pre_order(node.left ) pre_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return in_order(node.left ) print(node.data , end=''',''' ) in_order(node.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=''',''' ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : Tuple = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : queue.Queue = queue.Queue() q.put(__a ) while not q.empty(): SCREAMING_SNAKE_CASE_ : str = [] while not q.empty(): SCREAMING_SNAKE_CASE_ : List[str] = q.get() print(node_dequeued.data , end=''',''' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__a ) def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Union[str, Any] = node while n or stack: while n: # start from root node, find its left child print(n.data , end=''',''' ) stack.append(__a ) SCREAMING_SNAKE_CASE_ : Optional[Any] = n.left # end of while means current node doesn't have left child SCREAMING_SNAKE_CASE_ : Tuple = stack.pop() # start to traverse its right child SCREAMING_SNAKE_CASE_ : str = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ : list[TreeNode] = [] SCREAMING_SNAKE_CASE_ : Any = node while n or stack: while n: stack.append(__a ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.left SCREAMING_SNAKE_CASE_ : Any = stack.pop() print(n.data , end=''',''' ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = n.right def _A (__a ) -> None: """simple docstring""" if not isinstance(__a , __a ) or not node: return SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = [], [] SCREAMING_SNAKE_CASE_ : List[Any] = node stacka.append(__a ) while stacka: # to find the reversed order of post order, store it in stack2 SCREAMING_SNAKE_CASE_ : List[str] = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__a ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=''',''' ) def _A (__a = "" , __a=50 , __a="*" ) -> str: """simple docstring""" if not s: return "\n" + width * char SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Dict = divmod(width - len(__a ) - 2 , 2 ) return f'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) UpperCAmelCase_ : TreeNode = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
318
1
"""simple docstring""" import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class A_ : """simple docstring""" def __init__( self :str , lowercase_ :Tuple , lowercase_ :Tuple=14 , lowercase_ :str=7 , lowercase_ :int=True , lowercase_ :Optional[Any]=True , lowercase_ :Union[str, Any]=False , lowercase_ :str=True , lowercase_ :int=99 , lowercase_ :List[Any]=32 , lowercase_ :Any=4 , lowercase_ :int=4 , lowercase_ :Any=4 , lowercase_ :Optional[Any]=37 , lowercase_ :Dict="gelu" , lowercase_ :Optional[Any]=0.1 , lowercase_ :Tuple=0.1 , lowercase_ :int=5_12 , lowercase_ :Optional[Any]=0.02 , ) -> Optional[int]: UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = rotary_dim UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = initializer_range UpperCAmelCase = None UpperCAmelCase = vocab_size - 1 UpperCAmelCase = vocab_size - 1 UpperCAmelCase = vocab_size - 1 def UpperCAmelCase__ ( self :Optional[int] ) -> str: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=a_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def UpperCAmelCase__ ( self :Optional[Any] ) -> List[str]: UpperCAmelCase = self.prepare_config_and_inputs() UpperCAmelCase = config_and_inputs UpperCAmelCase = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict def UpperCAmelCase__ ( self :Dict , lowercase_ :Any , lowercase_ :Optional[Any] , lowercase_ :Optional[Any] , lowercase_ :Optional[Any] ) -> Dict: UpperCAmelCase = 20 UpperCAmelCase = model_class_name(a_ ) UpperCAmelCase = model.init_cache(input_ids.shape[0] , a_ ) UpperCAmelCase = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) UpperCAmelCase = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) UpperCAmelCase = model( input_ids[:, :-1] , attention_mask=a_ , past_key_values=a_ , position_ids=a_ , ) UpperCAmelCase = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) UpperCAmelCase = model( input_ids[:, -1:] , attention_mask=a_ , past_key_values=outputs_cache.past_key_values , position_ids=a_ , ) UpperCAmelCase = model(a_ ) UpperCAmelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) def UpperCAmelCase__ ( self :str , lowercase_ :Any , lowercase_ :Optional[Any] , lowercase_ :Optional[Any] , lowercase_ :Union[str, Any] ) -> Tuple: UpperCAmelCase = 20 UpperCAmelCase = model_class_name(a_ ) UpperCAmelCase = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) UpperCAmelCase = model.init_cache(input_ids.shape[0] , a_ ) UpperCAmelCase = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) UpperCAmelCase = model( input_ids[:, :-1] , attention_mask=a_ , past_key_values=a_ , position_ids=a_ , ) UpperCAmelCase = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) UpperCAmelCase = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=a_ , position_ids=a_ , ) UpperCAmelCase = model(a_ , attention_mask=a_ ) UpperCAmelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"""Max diff is {diff}""" ) @require_flax class A_ ( __snake_case , __snake_case , unittest.TestCase ): """simple docstring""" __UpperCamelCase = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () __UpperCamelCase = (FlaxGPTJForCausalLM,) if is_flax_available() else () def UpperCAmelCase__ ( self :int ) -> str: UpperCAmelCase = FlaxGPTJModelTester(self ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> str: for model_class_name in self.all_model_classes: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(a_ , a_ , a_ , a_ ) def UpperCAmelCase__ ( self :Tuple ) -> Optional[Any]: for model_class_name in self.all_model_classes: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( a_ , a_ , a_ , a_ ) @tooslow def UpperCAmelCase__ ( self :Optional[int] ) -> Tuple: UpperCAmelCase = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) UpperCAmelCase = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=a_ , truncation=a_ ) UpperCAmelCase = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) UpperCAmelCase = False UpperCAmelCase = model.config.eos_token_id UpperCAmelCase = jax.jit(model.generate ) UpperCAmelCase = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences UpperCAmelCase = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) UpperCAmelCase = [ '''Hello this is a long string of text.\n\nI\'m trying to get the text of the''', '''Hey, I\'m a little late to the party. I\'m going to''', ] self.assertListEqual(a_ , a_ ) @is_pt_flax_cross_test def UpperCAmelCase__ ( self :Any ) -> Optional[Any]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs UpperCAmelCase = self._prepare_for_class(a_ , a_ ) UpperCAmelCase = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class UpperCAmelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning UpperCAmelCase = getattr(a_ , a_ ) UpperCAmelCase = pt_inputs['''input_ids'''].shape UpperCAmelCase = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(a_ ): UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = pt_model_class(a_ ).eval() UpperCAmelCase = model_class(a_ , dtype=jnp.floataa ) UpperCAmelCase = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , a_ ) UpperCAmelCase = fx_state with torch.no_grad(): UpperCAmelCase = pt_model(**a_ ).to_tuple() UpperCAmelCase = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(a_ ) UpperCAmelCase = model_class.from_pretrained(a_ , from_pt=a_ ) UpperCAmelCase = fx_model_loaded(**a_ ).to_tuple() self.assertEqual( len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @is_pt_flax_cross_test def UpperCAmelCase__ ( self :Any ) -> int: UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs UpperCAmelCase = self._prepare_for_class(a_ , a_ ) UpperCAmelCase = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class UpperCAmelCase = model_class.__name__[4:] # Skip the "Flax" at the beginning UpperCAmelCase = getattr(a_ , a_ ) UpperCAmelCase = pt_model_class(a_ ).eval() UpperCAmelCase = model_class(a_ , dtype=jnp.floataa ) UpperCAmelCase = load_flax_weights_in_pytorch_model(a_ , fx_model.params ) UpperCAmelCase = pt_inputs['''input_ids'''].shape UpperCAmelCase = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(a_ ): UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 0 UpperCAmelCase = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): UpperCAmelCase = pt_model(**a_ ).to_tuple() UpperCAmelCase = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(a_ ) UpperCAmelCase = pt_model_class.from_pretrained(a_ , from_flax=a_ ) with torch.no_grad(): UpperCAmelCase = pt_model_loaded(**a_ ).to_tuple() self.assertEqual( len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4E-2 ) @tooslow def UpperCAmelCase__ ( self :Union[str, Any] ) -> Any: for model_class_name in self.all_model_classes: UpperCAmelCase = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) UpperCAmelCase = model(np.ones((1, 1) ) ) self.assertIsNotNone(a_ )
78
"""simple docstring""" import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging SCREAMING_SNAKE_CASE : Union[str, Any] = """\ """ SCREAMING_SNAKE_CASE : Any = """ Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity """ SCREAMING_SNAKE_CASE : Dict = """ Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to 'cuda' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"] >>> results = perplexity.compute(model_id='gpt2', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 78.22 >>> print(round(results[\"perplexities\"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = datasets.load_dataset(\"wikitext\", ... \"wikitext-2-raw-v1\", ... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=''] >>> results = perplexity.compute(model_id='gpt2', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 60.35 >>> print(round(results[\"perplexities\"][0], 2)) 81.12 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''input_texts''': datasets.Value('''string''' ), } ) , reference_urls=['''https://huggingface.co/docs/transformers/perplexity'''] , ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ = 16 , a_ = True , a_=None ): '''simple docstring''' if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": __snake_case : Optional[Any] = '''cuda''' else: __snake_case : Tuple = '''cuda''' if torch.cuda.is_available() else '''cpu''' __snake_case : int = AutoModelForCausalLM.from_pretrained(a_ ) __snake_case : Optional[int] = model.to(a_ ) __snake_case : Optional[int] = AutoTokenizer.from_pretrained(a_ ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: __snake_case : List[Any] = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(a_ ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" __snake_case : List[Any] = model.config.max_length - 1 else: __snake_case : Dict = model.config.max_length __snake_case : Tuple = tokenizer( a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , return_tensors='''pt''' , return_attention_mask=a_ , ).to(a_ ) __snake_case : List[Any] = encodings['''input_ids'''] __snake_case : str = encodings['''attention_mask'''] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." __snake_case : Union[str, Any] = [] __snake_case : str = CrossEntropyLoss(reduction='''none''' ) for start_index in logging.tqdm(range(0 , len(a_ ) , a_ ) ): __snake_case : Optional[int] = min(start_index + batch_size , len(a_ ) ) __snake_case : int = encoded_texts[start_index:end_index] __snake_case : Optional[int] = attn_masks[start_index:end_index] if add_start_token: __snake_case : List[Any] = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(a_ ) __snake_case : Union[str, Any] = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) __snake_case : int = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(a_ ), attn_mask] , dim=1 ) __snake_case : List[Any] = encoded_batch with torch.no_grad(): __snake_case : List[str] = model(a_ , attention_mask=a_ ).logits __snake_case : List[str] = out_logits[..., :-1, :].contiguous() __snake_case : int = labels[..., 1:].contiguous() __snake_case : int = attn_mask[..., 1:].contiguous() __snake_case : Tuple = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , a_ ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(a_ )}
102
0
from maths.prime_check import is_prime def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ): if not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A_ : Dict = f'''Input value of [number={number}] must be an integer''' raise TypeError(SCREAMING_SNAKE_CASE ) if is_prime(SCREAMING_SNAKE_CASE ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
65
import warnings from ...utils import logging from .image_processing_yolos import YolosImageProcessor UpperCamelCase = logging.get_logger(__name__) class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )->None: '''simple docstring''' warnings.warn( '''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use YolosImageProcessor instead.''' , _SCREAMING_SNAKE_CASE , ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
65
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase__ = {"configuration_vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMAEForPreTraining", "ViTMAELayer", "ViTMAEModel", "ViTMAEPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ = [ "TFViTMAEForPreTraining", "TFViTMAEModel", "TFViTMAEPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowercase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
241
import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py A : Tuple = "src/transformers" A : Optional[Any] = "docs/source/en/tasks" def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): with open(__UpperCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: SCREAMING_SNAKE_CASE_ = f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE_ = 0 while not lines[start_index].startswith(__UpperCamelCase ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE_ = start_index while not lines[end_index].startswith(__UpperCamelCase ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. A : List[str] = direct_transformers_import(TRANSFORMERS_PATH) A : List[Any] = { "asr.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, "audio_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, "language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, "image_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, "masked_language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, "multiple_choice.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, "object_detection.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, "question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, "semantic_segmentation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, "sequence_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, "summarization.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, "token_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, "translation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, "video_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, "document_question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, "monocular_depth_estimation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). A : Any = { "summarization.md": ("nllb",), "translation.md": ("nllb",), } def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = TASK_GUIDE_TO_MODELS[task_guide] SCREAMING_SNAKE_CASE_ = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(__UpperCamelCase , set() ) SCREAMING_SNAKE_CASE_ = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'''[{name}](../model_doc/{code})''' for code, name in model_names.items()] ) + "\n" def a__ ( __UpperCamelCase , __UpperCamelCase=False ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = _find_text_in_file( filename=os.path.join(__UpperCamelCase , __UpperCamelCase ) , start_prompt="<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->" , end_prompt="<!--End of the generated tip-->" , ) SCREAMING_SNAKE_CASE_ = get_model_list_for_task(__UpperCamelCase ) if current_list != new_list: if overwrite: with open(os.path.join(__UpperCamelCase , __UpperCamelCase ) , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'''The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`''' " to fix this." ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") A : Dict = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
118
0
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def __UpperCamelCase ( *_lowerCAmelCase ) -> List[str]: """simple docstring""" if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): A : List[str] = list(_lowerCAmelCase ) for i in range(len(_lowerCAmelCase ) ): A : Optional[int] = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def __UpperCamelCase ( _lowerCAmelCase ) -> bool: """simple docstring""" A : Dict = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def __UpperCamelCase ( _lowerCAmelCase = None , _lowerCAmelCase = 128 ) -> List[str]: """simple docstring""" if function is None: return functools.partial(_lowerCAmelCase , starting_batch_size=_lowerCAmelCase ) A : Any = starting_batch_size def decorator(*_lowerCAmelCase , **_lowerCAmelCase ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() A : Tuple = list(inspect.signature(_lowerCAmelCase ).parameters.keys() ) # Guard against user error if len(_lowerCAmelCase ) < (len(_lowerCAmelCase ) + 1): A : str = """, """.join([f'''{arg}={value}''' for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( f'''Batch size was passed into `{function.__name__}` as the first argument when called.''' f'''Remove this as the decorator already does so: `{function.__name__}({arg_str})`''' ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(_lowerCAmelCase , *_lowerCAmelCase , **_lowerCAmelCase ) except Exception as e: if should_reduce_batch_size(_lowerCAmelCase ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
368
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 OwlViTImageProcessor, OwlViTProcessor @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase ( self ): A : str = tempfile.mkdtemp() # fmt: off A : List[Any] = ["""""", """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 A : Optional[int] = dict(zip(lowerCamelCase__, range(len(lowerCamelCase__ ) ) ) ) A : Optional[Any] = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] A : Union[str, Any] = {"""unk_token""": """<unk>"""} A : List[Any] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["""vocab_file"""] ) A : int = 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(lowerCamelCase__ ) + """\n""" ) with open(self.merges_file, """w""", encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCamelCase__ ) ) A : int = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], } A : List[Any] = os.path.join(self.tmpdirname, lowerCamelCase__ ) with open(self.image_processor_file, """w""", encoding="""utf-8""" ) as fp: json.dump(lowerCamelCase__, lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return CLIPTokenizer.from_pretrained(self.tmpdirname, pad_token="""!""", **lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname, pad_token="""!""", **lowerCamelCase__ ) def _lowerCAmelCase ( self, **lowerCamelCase__ ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname, **lowerCamelCase__ ) def _lowerCAmelCase ( self ): shutil.rmtree(self.tmpdirname ) def _lowerCAmelCase ( self ): A : str = [np.random.randint(255, size=(3, 30, 400), dtype=np.uinta )] A : Optional[int] = [Image.fromarray(np.moveaxis(lowerCamelCase__, 0, -1 ) ) for x in image_inputs] return image_inputs def _lowerCAmelCase ( self ): A : Optional[Any] = self.get_tokenizer() A : Optional[Any] = self.get_rust_tokenizer() A : Optional[int] = self.get_image_processor() A : List[str] = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname, use_fast=lowerCamelCase__ ) A : Tuple = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) A : str = OwlViTProcessor.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, lowerCamelCase__ ) self.assertIsInstance(processor_fast.tokenizer, lowerCamelCase__ ) 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, lowerCamelCase__ ) self.assertIsInstance(processor_fast.image_processor, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[int] = self.get_tokenizer(bos_token="""(BOS)""", eos_token="""(EOS)""" ) A : Tuple = self.get_image_processor(do_normalize=lowerCamelCase__ ) A : Optional[Any] = OwlViTProcessor.from_pretrained( self.tmpdirname, bos_token="""(BOS)""", eos_token="""(EOS)""", do_normalize=lowerCamelCase__ ) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer, lowerCamelCase__ ) self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor, lowerCamelCase__ ) def _lowerCAmelCase ( self ): A : List[Any] = self.get_image_processor() A : str = self.get_tokenizer() A : List[str] = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Optional[Any] = self.prepare_image_inputs() A : Optional[Any] = image_processor(lowerCamelCase__, return_tensors="""np""" ) A : Any = processor(images=lowerCamelCase__, return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum(), input_processor[key].sum(), delta=1e-2 ) def _lowerCAmelCase ( self ): A : int = self.get_image_processor() A : Optional[Any] = self.get_tokenizer() A : Optional[int] = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Any = """lower newer""" A : Union[str, Any] = processor(text=lowerCamelCase__, return_tensors="""np""" ) A : str = tokenizer(lowerCamelCase__, return_tensors="""np""" ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist(), encoded_processor[key][0].tolist() ) def _lowerCAmelCase ( self ): A : Tuple = self.get_image_processor() A : int = self.get_tokenizer() A : str = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : List[str] = """lower newer""" A : Any = self.prepare_image_inputs() A : Tuple = processor(text=lowerCamelCase__, images=lowerCamelCase__ ) self.assertListEqual(list(inputs.keys() ), ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase__ ): processor() def _lowerCAmelCase ( self ): A : str = """google/owlvit-base-patch32""" A : Dict = OwlViTProcessor.from_pretrained(lowerCamelCase__ ) A : str = ["""cat""", """nasa badge"""] A : Optional[int] = processor(text=lowerCamelCase__ ) A : Any = 16 self.assertListEqual(list(inputs.keys() ), ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape, (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase__ ): processor() def _lowerCAmelCase ( self ): A : Tuple = """google/owlvit-base-patch32""" A : Any = OwlViTProcessor.from_pretrained(lowerCamelCase__ ) A : int = [["""cat""", """nasa badge"""], ["""person"""]] A : List[Any] = processor(text=lowerCamelCase__ ) A : Dict = 16 A : List[str] = len(lowerCamelCase__ ) A : List[str] = max([len(lowerCamelCase__ ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ), ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape, (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase__ ): processor() def _lowerCAmelCase ( self ): A : Dict = """google/owlvit-base-patch32""" A : int = OwlViTProcessor.from_pretrained(lowerCamelCase__ ) A : str = ["""cat""", """nasa badge"""] A : Optional[Any] = processor(text=lowerCamelCase__ ) A : int = 16 A : Optional[Any] = inputs["""input_ids"""] A : Optional[int] = [ [4_9406, 2368, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_9406, 6841, 1_1301, 4_9407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ), ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape, (2, seq_length) ) self.assertListEqual(list(input_ids[0] ), predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ), predicted_ids[1] ) def _lowerCAmelCase ( self ): A : Tuple = self.get_image_processor() A : Dict = self.get_tokenizer() A : Optional[Any] = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Any = self.prepare_image_inputs() A : Optional[Any] = self.prepare_image_inputs() A : List[str] = processor(images=lowerCamelCase__, query_images=lowerCamelCase__ ) self.assertListEqual(list(inputs.keys() ), ["""query_pixel_values""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowerCamelCase__ ): processor() def _lowerCAmelCase ( self ): A : Any = self.get_image_processor() A : Optional[Any] = self.get_tokenizer() A : List[str] = OwlViTProcessor(tokenizer=lowerCamelCase__, image_processor=lowerCamelCase__ ) A : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] A : Optional[Any] = processor.batch_decode(lowerCamelCase__ ) A : Union[str, Any] = tokenizer.batch_decode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__, lowerCamelCase__ )
115
0
'''simple docstring''' import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class lowercase_ ( tf.keras.optimizers.schedules.LearningRateSchedule ): def __init__( self , a , a , a , a = 1.0 , a = None , ): super().__init__() UpperCamelCase__ = initial_learning_rate UpperCamelCase__ = warmup_steps UpperCamelCase__ = power UpperCamelCase__ = decay_schedule_fn UpperCamelCase__ = name def __call__( self , a ): with tf.name_scope(self.name or "WarmUp" ) as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. UpperCamelCase__ = tf.cast(A__ , tf.floataa ) UpperCamelCase__ = tf.cast(self.warmup_steps , tf.floataa ) UpperCamelCase__ = global_step_float / warmup_steps_float UpperCamelCase__ = self.initial_learning_rate * tf.math.pow(A__ , self.power ) return tf.cond( global_step_float < warmup_steps_float , lambda: warmup_learning_rate , lambda: self.decay_schedule_fn(step - self.warmup_steps ) , name=A__ , ) def __a ( self ): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name, } def _UpperCamelCase ( __A , __A , __A , __A = 0.0 , __A = 0.9 , __A = 0.999 , __A = 1E-8 , __A = None , __A = None , __A = 0.0 , __A = 1.0 , __A = None , ) -> str: '''simple docstring''' UpperCamelCase__ = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=lowerCAmelCase__ , decay_steps=num_train_steps - num_warmup_steps , end_learning_rate=init_lr * min_lr_ratio , power=lowerCAmelCase__ , ) if num_warmup_steps: UpperCamelCase__ = WarmUp( initial_learning_rate=lowerCAmelCase__ , decay_schedule_fn=lowerCAmelCase__ , warmup_steps=lowerCAmelCase__ , ) if weight_decay_rate > 0.0: UpperCamelCase__ = AdamWeightDecay( learning_rate=lowerCAmelCase__ , weight_decay_rate=lowerCAmelCase__ , beta_a=lowerCAmelCase__ , beta_a=lowerCAmelCase__ , epsilon=lowerCAmelCase__ , clipnorm=lowerCAmelCase__ , global_clipnorm=lowerCAmelCase__ , exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"] , include_in_weight_decay=lowerCAmelCase__ , ) else: UpperCamelCase__ = tf.keras.optimizers.Adam( learning_rate=lowerCAmelCase__ , beta_a=lowerCAmelCase__ , beta_a=lowerCAmelCase__ , epsilon=lowerCAmelCase__ , clipnorm=lowerCAmelCase__ , global_clipnorm=lowerCAmelCase__ , ) # We return the optimizer and the LR scheduler in order to better track the # evolution of the LR independently of the optimizer. return optimizer, lr_schedule class lowercase_ ( SCREAMING_SNAKE_CASE__ ): def __init__( self , a = 0.001 , a = 0.9 , a = 0.999 , a = 1e-7 , a = False , a = 0.0 , a = None , a = None , a = "AdamWeightDecay" , **a , ): super().__init__(A__ , A__ , A__ , A__ , A__ , A__ , **A__ ) UpperCamelCase__ = weight_decay_rate UpperCamelCase__ = include_in_weight_decay UpperCamelCase__ = exclude_from_weight_decay @classmethod def __a ( cls , a ): UpperCamelCase__ = {"WarmUp": WarmUp} return super(A__ , cls ).from_config(A__ , custom_objects=A__ ) def __a ( self , a , a , a ): super(A__ , self )._prepare_local(A__ , A__ , A__ ) UpperCamelCase__ = tf.constant( self.weight_decay_rate , name="adam_weight_decay_rate" ) def __a ( self , a , a , a ): UpperCamelCase__ = self._do_use_weight_decay(var.name ) if do_decay: return var.assign_sub( learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"] , use_locking=self._use_locking , ) return tf.no_op() def __a ( self , a , a=None , **a ): UpperCamelCase__ , UpperCamelCase__ = list(zip(*A__ ) ) return super(A__ , self ).apply_gradients(zip(A__ , A__ ) , name=A__ , **A__ ) def __a ( self , a , a , a ): if apply_state is None: return self._decayed_lr_t[var_dtype], {} UpperCamelCase__ = apply_state or {} UpperCamelCase__ = apply_state.get((var_device, var_dtype) ) if coefficients is None: UpperCamelCase__ = self._fallback_apply_state(A__ , A__ ) UpperCamelCase__ = coefficients return coefficients["lr_t"], {"apply_state": apply_state} def __a ( self , a , a , a=None ): UpperCamelCase__ , UpperCamelCase__ = self._get_lr(var.device , var.dtype.base_dtype , A__ ) UpperCamelCase__ = self._decay_weights_op(A__ , A__ , A__ ) with tf.control_dependencies([decay] ): return super(A__ , self )._resource_apply_dense(A__ , A__ , **A__ ) def __a ( self , a , a , a , a=None ): UpperCamelCase__ , UpperCamelCase__ = self._get_lr(var.device , var.dtype.base_dtype , A__ ) UpperCamelCase__ = self._decay_weights_op(A__ , A__ , A__ ) with tf.control_dependencies([decay] ): return super(A__ , self )._resource_apply_sparse(A__ , A__ , A__ , **A__ ) def __a ( self ): UpperCamelCase__ = super().get_config() config.update({"weight_decay_rate": self.weight_decay_rate} ) return config def __a ( self , a ): if self.weight_decay_rate == 0: return False if self._include_in_weight_decay: for r in self._include_in_weight_decay: if re.search(A__ , A__ ) is not None: return True if self._exclude_from_weight_decay: for r in self._exclude_from_weight_decay: if re.search(A__ , A__ ) is not None: return False return True class lowercase_ ( SCREAMING_SNAKE_CASE__ ): def __init__( self ): UpperCamelCase__ = [] UpperCamelCase__ = None @property def __a ( self ): if self._accum_steps is None: UpperCamelCase__ = tf.Variable( tf.constant(0 , dtype=tf.intaa ) , trainable=A__ , synchronization=tf.VariableSynchronization.ON_READ , aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA , ) return self._accum_steps.value() @property def __a ( self ): if not self._gradients: raise ValueError("The accumulator should be called first to initialize the gradients" ) return [gradient.value() if gradient is not None else gradient for gradient in self._gradients] def __call__( self , a ): if not self._gradients: UpperCamelCase__ = self.step # Create the step variable. self._gradients.extend( [ tf.Variable( tf.zeros_like(A__ ) , trainable=A__ , synchronization=tf.VariableSynchronization.ON_READ , aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA , ) if gradient is not None else gradient for gradient in gradients ] ) if len(A__ ) != len(self._gradients ): raise ValueError(f'''Expected {len(self._gradients )} gradients, but got {len(A__ )}''' ) for accum_gradient, gradient in zip(self._gradients , A__ ): if accum_gradient is not None and gradient is not None: accum_gradient.assign_add(A__ ) self._accum_steps.assign_add(1 ) def __a ( self ): if not self._gradients: return self._accum_steps.assign(0 ) for gradient in self._gradients: if gradient is not None: gradient.assign(tf.zeros_like(A__ ) )
80
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowercase__ :str = logging.get_logger(__name__) def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = '''huggingface/label-files''' lowercase = '''imagenet-1k-id2label.json''' lowercase = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) lowercase = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} lowercase = {v: k for k, v in idalabel.items()} lowercase = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" lowercase = BitConfig( conv_layer=lowerCAmelCase__ , num_labels=1000 , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , ) return config def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' if "stem.conv" in name: lowercase = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: lowercase = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: lowercase = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): lowercase = '''bit.''' + name if "bit" not in name and "classifier" not in name: lowercase = '''bit.encoder.''' + name return name def UpperCamelCase ( ): '''simple docstring''' lowercase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ): '''simple docstring''' lowercase = get_config(lowerCAmelCase__ ) # load original model from timm lowercase = create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ) timm_model.eval() # load state_dict of original model lowercase = timm_model.state_dict() for key in state_dict.copy().keys(): lowercase = state_dict.pop(lowerCAmelCase__ ) lowercase = val.squeeze() if '''head''' in key else val # load HuggingFace model lowercase = BitForImageClassification(lowerCAmelCase__ ) model.eval() model.load_state_dict(lowerCAmelCase__ ) # create image processor lowercase = create_transform(**resolve_data_config({} , model=lowerCAmelCase__ ) ) lowercase = transform.transforms lowercase = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } lowercase = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowerCAmelCase__ , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=lowerCAmelCase__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowercase = prepare_img() lowercase = transform(lowerCAmelCase__ ).unsqueeze(0 ) lowercase = processor(lowerCAmelCase__ , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ) # verify logits with torch.no_grad(): lowercase = model(lowerCAmelCase__ ) lowercase = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) lowercase = timm_model(lowerCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase__ , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) print(f'Saving model {model_name} and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(f'Pushing model {model_name} and processor to the hub' ) model.push_to_hub(f'ybelkada/{model_name}' ) processor.push_to_hub(f'ybelkada/{model_name}' ) if __name__ == "__main__": lowercase__ :List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="resnetv2_50x1_bitm", type=str, help="Name of the BiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model to the hub.", ) lowercase__ :List[str] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
101
0
'''simple docstring''' from math import factorial lowerCAmelCase_ : Any = {str(d): factorial(d) for d in range(10)} def _lowerCamelCase ( lowercase : List[str] ) -> Dict: return sum(DIGIT_FACTORIAL[d] for d in str(lowercase ) ) def _lowerCamelCase ( ) -> Optional[int]: _a = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , lowercase ) if sum_of_digit_factorial(lowercase ) == i ) if __name__ == "__main__": print(f"""{solution() = }""")
367
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format='%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=os.environ.get('LOGLEVEL', 'INFO').upper(), stream=sys.stdout, ) lowerCAmelCase_ : List[Any] = logging.getLogger(__name__) lowerCAmelCase_ : List[Any] = {'facebook/bart-base': BartForConditionalGeneration} lowerCAmelCase_ : int = {'facebook/bart-base': BartTokenizer} def _lowerCamelCase ( ) -> Union[str, Any]: _a = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=lowercase , default=lowercase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=lowercase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=lowercase , default=lowercase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=lowercase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=lowercase , ) parser.add_argument( "--config_name" , type=lowercase , default=lowercase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=lowercase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=lowercase , default=lowercase , help="Where to store the final ONNX file." ) _a = parser.parse_args() return args def _lowerCamelCase ( lowercase : Any , lowercase : Tuple="cpu" ) -> Optional[Any]: _a = model_dict[model_name].from_pretrained(lowercase ).to(lowercase ) _a = tokenizer_dict[model_name].from_pretrained(lowercase ) if model_name in ["facebook/bart-base"]: _a = 0 _a = None _a = 0 return huggingface_model, tokenizer def _lowerCamelCase ( lowercase : List[str] , lowercase : Tuple , lowercase : int , lowercase : Any , lowercase : Dict ) -> Any: model.eval() _a = None _a = torch.jit.script(BARTBeamSearchGenerator(lowercase ) ) with torch.no_grad(): _a = "My friends are cool but they eat too many carbs." _a = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) _a = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=lowercase , max_length=lowercase , early_stopping=lowercase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( lowercase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , lowercase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=lowercase , ) logger.info("Model exported to {}".format(lowercase ) ) _a = remove_dup_initializers(os.path.abspath(lowercase ) ) logger.info("Deduplicated and optimized model written to {}".format(lowercase ) ) _a = onnxruntime.InferenceSession(lowercase ) _a = ort_sess.run( lowercase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(lowercase ), "max_length": np.array(lowercase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1E-3 , atol=1E-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def _lowerCamelCase ( ) -> Any: _a = parse_args() _a = 5 _a = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() _a = torch.device(args.device ) _a , _a = load_model_tokenizer(args.model_name_or_path , lowercase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(lowercase ) if args.max_length: _a = args.max_length if args.num_beams: _a = args.num_beams if args.output_file_path: _a = args.output_file_path else: _a = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(lowercase , lowercase , lowercase , lowercase , lowercase ) if __name__ == "__main__": main()
346
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_ ( ) -> List[Any]: """simple docstring""" _lowercase =ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=__snake_case ) _lowercase =parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=__snake_case ) env_command_parser(subparsers=__snake_case ) launch_command_parser(subparsers=__snake_case ) tpu_command_parser(subparsers=__snake_case ) test_command_parser(subparsers=__snake_case ) # Let's go _lowercase =parser.parse_args() if not hasattr(__snake_case , '''func''' ): parser.print_help() exit(1 ) # Run args.func(__snake_case ) if __name__ == "__main__": main()
5
import datasets from .evaluate import evaluate lowerCAmelCase__ = """\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } """ lowerCAmelCase__ = """ This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. """ lowerCAmelCase__ = """ Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair as given in the references (see below) - 'prediction_text': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair (see above), - 'answers': a Dict in the CUAD dataset format { 'text': list of possible texts for the answer, as a list of strings 'answer_start': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: 'exact_match': Exact match (the normalized answer exactly match the gold answer) 'f1': The F-score of predicted tokens versus the gold answer 'aupr': Area Under the Precision-Recall curve 'prec_at_80_recall': Precision at 80% recall 'prec_at_90_recall': Precision at 90% recall Examples: >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' A__ = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} A__ = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] A__ = evaluate(dataset=lowercase , predictions=lowercase ) return score
68
0
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : str ) -> str: '''simple docstring''' __snake_case : int = len(UpperCAmelCase_ ) __snake_case : int = len(UpperCAmelCase_ ) __snake_case : int = ( first_str_length if first_str_length > second_str_length else second_str_length ) __snake_case : list = [] for char_count in range(UpperCAmelCase_ ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(UpperCAmelCase_ ) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
95
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int: '''simple docstring''' while a != 0: __snake_case , __snake_case : Union[str, Any] = b % a, a return b def __UpperCAmelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int: '''simple docstring''' if gcd(UpperCAmelCase_ , UpperCAmelCase_ ) != 1: __snake_case : Union[str, Any] = F"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(UpperCAmelCase_ ) __snake_case , __snake_case , __snake_case : List[str] = 1, 0, a __snake_case , __snake_case , __snake_case : Dict = 0, 1, m while va != 0: __snake_case : List[str] = ua // va __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : List[str] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
95
1
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def __lowerCamelCase ( UpperCAmelCase_ : Union[str, Any] ): """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def __lowerCamelCase ( UpperCAmelCase_ : Tuple ): """simple docstring""" a :str = np.max(_outputs , axis=-1 , keepdims=UpperCAmelCase_ ) a :Optional[int] = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=UpperCAmelCase_ ) class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = 'sigmoid' SCREAMING_SNAKE_CASE__ = 'softmax' SCREAMING_SNAKE_CASE__ = 'none' @add_end_docstrings( _snake_case , r'\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `"default"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `"sigmoid"`: Applies the sigmoid function on the output.\n - `"softmax"`: Applies the softmax function on the output.\n - `"none"`: Does not apply any function on the output.\n ' , ) class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = ClassificationFunction.NONE def __init__( self , **_lowerCamelCase ): super().__init__(**_lowerCamelCase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="" , **_lowerCamelCase ): # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" a :int = tokenizer_kwargs a :Optional[int] = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: a :List[Any] = self.model.config.return_all_scores if isinstance(_lowerCamelCase , _lowerCamelCase ) or top_k is None: a :List[str] = top_k a :int = False elif return_all_scores is not None: warnings.warn( '''`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of''' ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.''' , _lowerCamelCase , ) if return_all_scores: a :int = None else: a :Optional[Any] = 1 if isinstance(_lowerCamelCase , _lowerCamelCase ): a :Any = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: a :Dict = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *_lowerCamelCase , **_lowerCamelCase ): a :str = super().__call__(*_lowerCamelCase , **_lowerCamelCase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. a :Union[str, Any] = '''top_k''' not in kwargs if isinstance(args[0] , _lowerCamelCase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , **_lowerCamelCase ): a :Optional[Any] = self.framework if isinstance(_lowerCamelCase , _lowerCamelCase ): return self.tokenizer(**_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ) and len(_lowerCamelCase ) == 1 and isinstance(inputs[0] , _lowerCamelCase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=_lowerCamelCase , **_lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a''' ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.''' ) return self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ): return self.model(**_lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=1 , _lowerCamelCase=True ): # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: a :Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: a :Tuple = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: a :List[Any] = self.model.config.function_to_apply else: a :Any = ClassificationFunction.NONE a :List[Any] = model_outputs['''logits'''][0] a :Dict = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: a :List[Any] = sigmoid(_lowerCamelCase ) elif function_to_apply == ClassificationFunction.SOFTMAX: a :Optional[Any] = softmax(_lowerCamelCase ) elif function_to_apply == ClassificationFunction.NONE: a :List[str] = outputs else: raise ValueError(F'''Unrecognized `function_to_apply` argument: {function_to_apply}''' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} a :List[str] = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(_lowerCamelCase ) ] if not _legacy: dict_scores.sort(key=lambda _lowerCamelCase : x["score"] , reverse=_lowerCamelCase ) if top_k is not None: a :Any = dict_scores[:top_k] return dict_scores
94
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_ : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any]="attention" ): """simple docstring""" a :Optional[int] = params[F'''{prefix}/layers_{i}/{layer_name}/key/kernel'''] a :Optional[Any] = params[F'''{prefix}/layers_{i}/{layer_name}/out/kernel'''] a :int = params[F'''{prefix}/layers_{i}/{layer_name}/query/kernel'''] a :Optional[Any] = params[F'''{prefix}/layers_{i}/{layer_name}/value/kernel'''] return k, o, q, v def __lowerCamelCase ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=False ): """simple docstring""" if split_mlp_wi: a :int = params[F'''{prefix}/layers_{i}/mlp/wi_0/kernel'''] a :Optional[Any] = params[F'''{prefix}/layers_{i}/mlp/wi_1/kernel'''] a :Dict = (wi_a, wi_a) else: a :Optional[Any] = params[F'''{prefix}/layers_{i}/mlp/wi/kernel'''] a :Dict = params[F'''{prefix}/layers_{i}/mlp/wo/kernel'''] return wi, wo def __lowerCamelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] ): """simple docstring""" return params[F'''{prefix}/layers_{i}/{layer_name}/scale'''] def __lowerCamelCase ( UpperCAmelCase_ : dict , *, UpperCAmelCase_ : int , UpperCAmelCase_ : bool ): """simple docstring""" a :str = traverse_util.flatten_dict(variables['''target'''] ) a :Any = {'''/'''.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 a :Any = '''encoder/layers_0/mlp/wi_0/kernel''' in old print('''Split MLP:''' , UpperCAmelCase_ ) a :Optional[Any] = collections.OrderedDict() # Shared embeddings. a :Union[str, Any] = old['''token_embedder/embedding'''] # Encoder. for i in range(UpperCAmelCase_ ): # Block i, layer 0 (Self Attention). a :Optional[Any] = tax_layer_norm_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''encoder''' , '''pre_attention_layer_norm''' ) a , a , a , a :Optional[int] = tax_attention_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''encoder''' , '''attention''' ) a :List[Any] = layer_norm a :str = k.T a :Dict = o.T a :int = q.T a :Optional[Any] = v.T # Block i, layer 1 (MLP). a :Tuple = tax_layer_norm_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''encoder''' , '''pre_mlp_layer_norm''' ) a , a :List[Any] = tax_mlp_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''encoder''' , UpperCAmelCase_ ) a :Any = layer_norm if split_mlp_wi: a :Any = wi[0].T a :Tuple = wi[1].T else: a :List[str] = wi.T a :List[Any] = wo.T a :Union[str, Any] = old[ '''encoder/relpos_bias/rel_embedding''' ].T a :Optional[Any] = old['''encoder/encoder_norm/scale'''] if not is_encoder_only: # Decoder. for i in range(UpperCAmelCase_ ): # Block i, layer 0 (Self Attention). a :List[str] = tax_layer_norm_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''decoder''' , '''pre_self_attention_layer_norm''' ) a , a , a , a :List[Any] = tax_attention_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''decoder''' , '''self_attention''' ) a :List[Any] = layer_norm a :Tuple = k.T a :int = o.T a :Any = q.T a :Optional[int] = v.T # Block i, layer 1 (Cross Attention). a :str = tax_layer_norm_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''decoder''' , '''pre_cross_attention_layer_norm''' ) a , a , a , a :Any = tax_attention_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''decoder''' , '''encoder_decoder_attention''' ) a :str = layer_norm a :Optional[Any] = k.T a :Any = o.T a :Dict = q.T a :Optional[Any] = v.T # Block i, layer 2 (MLP). a :Optional[int] = tax_layer_norm_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''decoder''' , '''pre_mlp_layer_norm''' ) a , a :List[Any] = tax_mlp_lookup(UpperCAmelCase_ , UpperCAmelCase_ , '''decoder''' , UpperCAmelCase_ ) a :Optional[int] = layer_norm if split_mlp_wi: a :int = wi[0].T a :Tuple = wi[1].T else: a :str = wi.T a :Dict = wo.T a :Any = old['''decoder/decoder_norm/scale'''] a :Optional[Any] = 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: a :Union[str, Any] = old['''decoder/logits_dense/kernel'''].T return new def __lowerCamelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : bool ): """simple docstring""" a :List[Any] = 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: a :Optional[Any] = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: a :Tuple = 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.''' ) a :Optional[Any] = state_dict['''shared.weight'''] return state_dict def __lowerCamelCase ( UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] ): """simple docstring""" a :Tuple = checkpoints.load_tax_checkpoint(UpperCAmelCase_ ) a :Optional[int] = convert_tax_to_pytorch(UpperCAmelCase_ , num_layers=config.num_layers , is_encoder_only=UpperCAmelCase_ ) a :Tuple = make_state_dict(UpperCAmelCase_ , UpperCAmelCase_ ) model.load_state_dict(UpperCAmelCase_ , strict=UpperCAmelCase_ ) def __lowerCamelCase ( UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool = False ): """simple docstring""" a :List[Any] = 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: a :Any = TaEncoderModel(UpperCAmelCase_ ) else: a :List[str] = 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__": snake_case : 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 ) snake_case : Optional[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
94
1
from sklearn.metrics import matthews_corrcoef import datasets __A = "\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n" __A = "\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results['matthews_correlation'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results['matthews_correlation'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results['matthews_correlation'], 2))\n -0.25\n" __A = "\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): """simple docstring""" def lowercase_ ( self ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=[ 'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html' ] , ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None ) -> Optional[Any]: '''simple docstring''' return { "matthews_correlation": float(matthews_corrcoef(lowerCamelCase__ , lowerCamelCase__ , sample_weight=lowerCamelCase__ ) ), }
350
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __lowerCAmelCase ( __magic_name__ , unittest.TestCase ): """simple docstring""" snake_case_ = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def lowercase_ ( self , lowerCamelCase__=0 ) -> int: '''simple docstring''' __lowerCamelCase = floats_tensor((1, 3, 128, 128) , rng=random.Random(lowerCamelCase__ ) ) __lowerCamelCase = np.random.RandomState(lowerCamelCase__ ) __lowerCamelCase = { '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 lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = self.get_dummy_inputs() __lowerCamelCase = pipe(**lowerCamelCase__ ).images __lowerCamelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __lowerCamelCase = 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 lowercase_ ( self ) -> Tuple: '''simple docstring''' __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = self.get_dummy_inputs() __lowerCamelCase = pipe(**lowerCamelCase__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase = 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 lowercase_ ( self ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) # warmup pass to apply optimizations __lowerCamelCase = pipe(**self.get_dummy_inputs() ) __lowerCamelCase = self.get_dummy_inputs() __lowerCamelCase = pipe(**lowerCamelCase__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase = 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 lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = self.get_dummy_inputs() __lowerCamelCase = pipe(**lowerCamelCase__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase = 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 lowercase_ ( self ) -> List[str]: '''simple docstring''' __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = self.get_dummy_inputs() __lowerCamelCase = pipe(**lowerCamelCase__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase = 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 lowercase_ ( self ) -> List[Any]: '''simple docstring''' __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = self.get_dummy_inputs() __lowerCamelCase = pipe(**lowerCamelCase__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @property def lowercase_ ( self ) -> int: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowercase_ ( self ) -> Tuple: '''simple docstring''' __lowerCamelCase = ort.SessionOptions() __lowerCamelCase = False return options def lowercase_ ( self ) -> Any: '''simple docstring''' __lowerCamelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __lowerCamelCase = init_image.resize((768, 512) ) # using the PNDM scheduler by default __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = 'A fantasy landscape, trending on artstation' __lowerCamelCase = np.random.RandomState(0 ) __lowerCamelCase = pipe( prompt=lowerCamelCase__ , image=lowerCamelCase__ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=lowerCamelCase__ , output_type='np' , ) __lowerCamelCase = output.images __lowerCamelCase = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __lowerCamelCase = 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 lowercase_ ( self ) -> int: '''simple docstring''' __lowerCamelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __lowerCamelCase = init_image.resize((768, 512) ) __lowerCamelCase = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) __lowerCamelCase = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=lowerCamelCase__ , safety_checker=lowerCamelCase__ , feature_extractor=lowerCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __lowerCamelCase = 'A fantasy landscape, trending on artstation' __lowerCamelCase = np.random.RandomState(0 ) __lowerCamelCase = pipe( prompt=lowerCamelCase__ , image=lowerCamelCase__ , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=lowerCamelCase__ , output_type='np' , ) __lowerCamelCase = output.images __lowerCamelCase = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __lowerCamelCase = 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
348
0
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib SCREAMING_SNAKE_CASE :Union[str, Any] = get_logger() SCREAMING_SNAKE_CASE :Optional[dict] = None class UpperCAmelCase ( TensorFormatter[Mapping, "jax.Array", Mapping] ): '''simple docstring''' def __init__( self : List[str] ,A : Tuple=None ,A : List[Any]=None ,**A : str ): super().__init__(features=A ) import jax from jaxlib.xla_client import Device if isinstance(A ,A ): raise ValueError( f'''Expected {device} to be a `str` not {type(A )}, as `jaxlib.xla_extension.Device` ''' "is not serializable neither with `pickle` nor with `dill`. Instead you can surround " "the device with `str()` to get its string identifier that will be internally mapped " "to the actual `jaxlib.xla_extension.Device`." ) __A = device if isinstance(A ,A ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: __A = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'''Device with string identifier {self.device} not listed among the available ''' f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' f'''device: {str(jax.devices()[0] )}.''' ) __A = str(jax.devices()[0] ) __A = jnp_array_kwargs @staticmethod def UpperCamelCase_ ( ): import jax return {str(A ): device for device in jax.devices()} def UpperCamelCase_ ( self : Any ,A : Tuple ): import jax import jax.numpy as jnp if isinstance(A ,A ) and column: if all( isinstance(A ,jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(A ,axis=0 ) return column def UpperCamelCase_ ( self : int ,A : int ): import jax import jax.numpy as jnp if isinstance(A ,(str, bytes, type(A )) ): return value elif isinstance(A ,(np.character, np.ndarray) ) and np.issubdtype(value.dtype ,np.character ): return value.tolist() __A = {} if isinstance(A ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: __A = {"dtype": jnp.intaa} else: __A = {"dtype": jnp.intaa} elif isinstance(A ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.floating ): __A = {"dtype": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(A ,PIL.Image.Image ): __A = np.asarray(A ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: __A = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(A ,**{**default_dtype, **self.jnp_array_kwargs} ) def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, Any] ): import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(A ,torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(A ,"__array__" ) and not isinstance(A ,jax.Array ): __A = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(A ,np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(A ) for substruct in data_struct] ) elif isinstance(A ,(list, tuple) ): return self._consolidate([self.recursive_tensorize(A ) for substruct in data_struct] ) return self._tensorize(A ) def UpperCamelCase_ ( self : Any ,A : dict ): return map_nested(self._recursive_tensorize ,A ,map_list=A ) def UpperCamelCase_ ( self : List[str] ,A : pa.Table ): __A = self.numpy_arrow_extractor().extract_row(A ) __A = self.python_features_decoder.decode_row(A ) return self.recursive_tensorize(A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : pa.Table ): __A = self.numpy_arrow_extractor().extract_column(A ) __A = self.python_features_decoder.decode_column(A ,pa_table.column_names[0] ) __A = self.recursive_tensorize(A ) __A = self._consolidate(A ) return column def UpperCamelCase_ ( self : Dict ,A : pa.Table ): __A = self.numpy_arrow_extractor().extract_batch(A ) __A = self.python_features_decoder.decode_batch(A ) __A = self.recursive_tensorize(A ) for column_name in batch: __A = self._consolidate(batch[column_name] ) return batch
15
def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = [0] * len(a_ ) __A = [] __A = [1] * len(a_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(a_ ) ): if indegree[i] == 0: queue.append(a_ ) while queue: __A = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(a_ ) print(max(a_ ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE :List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
15
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : int ) -> Dict: """simple docstring""" self.test() def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False while not completed: if counter == 1: self.reset() __SCREAMING_SNAKE_CASE = self.advance() if not self.does_advance(__SCREAMING_SNAKE_CASE ): raise Exception( """Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.update(__SCREAMING_SNAKE_CASE ) counter += 1 if counter > 10_000: raise Exception("""update() does not fulfill the constraint.""" ) if self.remaining() != 0: raise Exception("""Custom Constraint is not defined correctly.""" ) @abstractmethod def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : int ) -> Union[str, Any]: """simple docstring""" raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def UpperCAmelCase__ ( self : List[str] , __SCREAMING_SNAKE_CASE : int ) -> List[str]: """simple docstring""" raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : List[str]=False ) -> Any: """simple docstring""" raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[int] ) -> Optional[int]: """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError(f'`token_ids` has to be a non-empty list, but is {token_ids}.' ) if any((not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or token_id < 0) for token_id in token_ids ): raise ValueError(f'Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.' ) __SCREAMING_SNAKE_CASE = token_ids __SCREAMING_SNAKE_CASE = len(self.token_ids ) __SCREAMING_SNAKE_CASE = -1 # the index of the currently fulfilled step __SCREAMING_SNAKE_CASE = False def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def UpperCAmelCase__ ( self : Optional[Any] , __SCREAMING_SNAKE_CASE : int ) -> Optional[Any]: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(f'`token_id` has to be an `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : int ) -> int: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(f'`token_id` has to be an `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}' ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False if self.does_advance(__SCREAMING_SNAKE_CASE ): self.fulfilled_idx += 1 __SCREAMING_SNAKE_CASE = True if self.fulfilled_idx == (self.seqlen - 1): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = completed else: # failed to make progress. __SCREAMING_SNAKE_CASE = True self.reset() return stepped, completed, reset def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Tuple=False ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = PhrasalConstraint(self.token_ids ) if stateful: __SCREAMING_SNAKE_CASE = self.seqlen __SCREAMING_SNAKE_CASE = self.fulfilled_idx __SCREAMING_SNAKE_CASE = self.completed return new_constraint class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[Any] , __SCREAMING_SNAKE_CASE : List[List[int]] , __SCREAMING_SNAKE_CASE : int=True ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = max([len(__SCREAMING_SNAKE_CASE ) for one in nested_token_ids] ) __SCREAMING_SNAKE_CASE = {} for token_ids in nested_token_ids: __SCREAMING_SNAKE_CASE = root for tidx, token_id in enumerate(__SCREAMING_SNAKE_CASE ): if token_id not in level: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = level[token_id] if no_subsets and self.has_subsets(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError( """Each list in `nested_token_ids` can't be a complete subset of another list, but is""" f' {nested_token_ids}.' ) __SCREAMING_SNAKE_CASE = root def UpperCAmelCase__ ( self : Tuple , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.trie for current_token in current_seq: __SCREAMING_SNAKE_CASE = start[current_token] __SCREAMING_SNAKE_CASE = list(start.keys() ) return next_tokens def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.next_tokens(__SCREAMING_SNAKE_CASE ) return len(__SCREAMING_SNAKE_CASE ) == 0 def UpperCAmelCase__ ( self : Dict , __SCREAMING_SNAKE_CASE : Optional[int] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = list(root.values() ) if len(__SCREAMING_SNAKE_CASE ) == 0: return 1 else: return sum([self.count_leaves(__SCREAMING_SNAKE_CASE ) for nn in next_nodes] ) def UpperCAmelCase__ ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Tuple ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.count_leaves(__SCREAMING_SNAKE_CASE ) return len(__SCREAMING_SNAKE_CASE ) != leaf_count class lowerCAmelCase__ ( a ): """simple docstring""" def __init__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : List[List[int]] ) -> int: """simple docstring""" super(__SCREAMING_SNAKE_CASE , self ).__init__() if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or len(__SCREAMING_SNAKE_CASE ) == 0: raise ValueError(f'`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.' ) if any(not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for token_ids in nested_token_ids ): raise ValueError(f'`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.' ) if any( any((not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f'Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.' ) __SCREAMING_SNAKE_CASE = DisjunctiveTrie(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = nested_token_ids __SCREAMING_SNAKE_CASE = self.trie.max_height __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = False def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.trie.next_tokens(self.current_seq ) if len(__SCREAMING_SNAKE_CASE ) == 0: return None else: return token_list def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : int ) -> Optional[Any]: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(f'`token_id` is supposed to be type `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}' ) __SCREAMING_SNAKE_CASE = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def UpperCAmelCase__ ( self : str , __SCREAMING_SNAKE_CASE : int ) -> str: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(f'`token_id` is supposed to be type `int`, but is {token_id} of type {type(__SCREAMING_SNAKE_CASE )}' ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False if self.does_advance(__SCREAMING_SNAKE_CASE ): self.current_seq.append(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = True else: __SCREAMING_SNAKE_CASE = True self.reset() __SCREAMING_SNAKE_CASE = self.trie.reached_leaf(self.current_seq ) __SCREAMING_SNAKE_CASE = completed return stepped, completed, reset def UpperCAmelCase__ ( self : Optional[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = [] def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def UpperCAmelCase__ ( self : int , __SCREAMING_SNAKE_CASE : Optional[Any]=False ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(self.token_ids ) if stateful: __SCREAMING_SNAKE_CASE = self.seqlen __SCREAMING_SNAKE_CASE = self.current_seq __SCREAMING_SNAKE_CASE = self.completed return new_constraint class lowerCAmelCase__ : """simple docstring""" def __init__( self : Any , __SCREAMING_SNAKE_CASE : List[Constraint] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = constraints # max # of steps required to fulfill a given constraint __SCREAMING_SNAKE_CASE = max([c.seqlen for c in constraints] ) __SCREAMING_SNAKE_CASE = len(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = False self.init_state() def UpperCAmelCase__ ( self : Dict ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = [constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) for constraint in self.constraints] def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" __SCREAMING_SNAKE_CASE = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" __SCREAMING_SNAKE_CASE = constraint.advance() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.append(__SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.extend(__SCREAMING_SNAKE_CASE ) else: __SCREAMING_SNAKE_CASE = self.inprogress_constraint.advance() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.append(__SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): token_list.extend(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) == 0: return None else: return token_list def UpperCAmelCase__ ( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : Optional[List[int]] ) -> str: """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.add(__SCREAMING_SNAKE_CASE ) # the entire list of constraints are fulfilled if self.completed: break def UpperCAmelCase__ ( self : Any , __SCREAMING_SNAKE_CASE : int ) -> Dict: """simple docstring""" if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise ValueError(f'`token_id` should be an `int`, but is `{token_id}`.' ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = False, False if self.completed: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.inprogress_constraint.update(__SCREAMING_SNAKE_CASE ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) __SCREAMING_SNAKE_CASE = None if len(self.pending_constraints ) == 0: # we're done! __SCREAMING_SNAKE_CASE = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__SCREAMING_SNAKE_CASE ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = pending_constraint.update(__SCREAMING_SNAKE_CASE ) if not stepped: raise Exception( """`constraint.update(token_id)` is not yielding incremental progress, """ """even though `constraint.does_advance(token_id)` is true.""" ) if complete: self.complete_constraints.append(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = None if not complete and stepped: __SCREAMING_SNAKE_CASE = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". __SCREAMING_SNAKE_CASE = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. __SCREAMING_SNAKE_CASE = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def UpperCAmelCase__ ( self : List[Any] , __SCREAMING_SNAKE_CASE : List[str]=True ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: __SCREAMING_SNAKE_CASE = [ constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: __SCREAMING_SNAKE_CASE = self.inprogress_constraint.copy(stateful=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [constraint.copy() for constraint in self.pending_constraints] return new_state
331
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase : Tuple = {'configuration_reformer': ['REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ReformerConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = ['ReformerTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Tuple = ['ReformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[Any] = [ 'REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ReformerAttention', 'ReformerForMaskedLM', 'ReformerForQuestionAnswering', 'ReformerForSequenceClassification', 'ReformerLayer', 'ReformerModel', 'ReformerModelWithLMHead', 'ReformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys UpperCAmelCase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
331
1
'''simple docstring''' from __future__ import annotations import numpy as np def _A ( snake_case ) -> str: _lowercase , _lowercase : Optional[int] = np.shape(lowercase__ ) if rows != columns: _lowercase : str = ( "\'table\' has to be of square shaped array but got a " F'''{rows}x{columns} array:\n{table}''' ) raise ValueError(lowercase__ ) _lowercase : Optional[Any] = np.zeros((rows, columns) ) _lowercase : int = np.zeros((rows, columns) ) for i in range(lowercase__ ): for j in range(lowercase__ ): _lowercase : Any = sum(lower[i][k] * upper[k][j] for k in range(lowercase__ ) ) if upper[j][j] == 0: raise ArithmeticError("No LU decomposition exists" ) _lowercase : Tuple = (table[i][j] - total) / upper[j][j] _lowercase : Dict = 1 for j in range(lowercase__ , lowercase__ ): _lowercase : Union[str, Any] = sum(lower[i][k] * upper[k][j] for k in range(lowercase__ ) ) _lowercase : Tuple = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
250
'''simple docstring''' import copy import random from transformers import CLIPTokenizer class lowerCAmelCase ( A ): def __init__( self : Optional[Any] , *__lowercase : str , **__lowercase : Union[str, Any] ): """simple docstring""" super().__init__(*__lowercase , **__lowercase ) __lowercase ={} def snake_case ( self : Union[str, Any] , __lowercase : List[Any] , *__lowercase : Optional[int] , **__lowercase : int ): """simple docstring""" __lowercase =super().add_tokens(__lowercase , *__lowercase , **__lowercase ) if num_added_tokens == 0: raise ValueError( f'''The tokenizer already contains the token {placeholder_token}. Please pass a different''' ' `placeholder_token` that is not already in the tokenizer.' ) def snake_case ( self : int , __lowercase : List[Any] , *__lowercase : Union[str, Any] , __lowercase : Dict=1 , **__lowercase : Dict ): """simple docstring""" __lowercase =[] if num_vec_per_token == 1: self.try_adding_tokens(__lowercase , *__lowercase , **__lowercase ) output.append(__lowercase ) else: __lowercase =[] for i in range(__lowercase ): __lowercase =placeholder_token + f'''_{i}''' self.try_adding_tokens(__lowercase , *__lowercase , **__lowercase ) output.append(__lowercase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( f'''The tokenizer already has placeholder token {token} that can get confused with''' f''' {placeholder_token}keep placeholder tokens independent''' ) __lowercase =output def snake_case ( self : Tuple , __lowercase : Optional[int] , __lowercase : Optional[int]=False , __lowercase : Optional[int]=1.0 ): """simple docstring""" if isinstance(__lowercase , __lowercase ): __lowercase =[] for i in range(len(__lowercase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=__lowercase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: __lowercase =self.token_map[placeholder_token] __lowercase =tokens[: 1 + int(len(__lowercase ) * prop_tokens_to_load )] if vector_shuffle: __lowercase =copy.copy(__lowercase ) random.shuffle(__lowercase ) __lowercase =text.replace(__lowercase , ' '.join(__lowercase ) ) return text def __call__( self : int , __lowercase : List[Any] , *__lowercase : Tuple , __lowercase : Optional[Any]=False , __lowercase : Dict=1.0 , **__lowercase : List[Any] ): """simple docstring""" return super().__call__( self.replace_placeholder_tokens_in_text( __lowercase , vector_shuffle=__lowercase , prop_tokens_to_load=__lowercase ) , *__lowercase , **__lowercase , ) def snake_case ( self : Dict , __lowercase : List[str] , *__lowercase : Tuple , __lowercase : Dict=False , __lowercase : List[str]=1.0 , **__lowercase : Optional[int] ): """simple docstring""" return super().encode( self.replace_placeholder_tokens_in_text( __lowercase , vector_shuffle=__lowercase , prop_tokens_to_load=__lowercase ) , *__lowercase , **__lowercase , )
141
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def lowerCAmelCase_ (lowerCAmelCase__: List[Any] ): """simple docstring""" UpperCAmelCase_: int = 3_8_4 if "tiny" in model_name: UpperCAmelCase_: Optional[Any] = [3, 3, 9, 3] UpperCAmelCase_: Any = [9_6, 1_9_2, 3_8_4, 7_6_8] if "small" in model_name: UpperCAmelCase_: Any = [3, 3, 2_7, 3] UpperCAmelCase_: Dict = [9_6, 1_9_2, 3_8_4, 7_6_8] if "base" in model_name: UpperCAmelCase_: int = [3, 3, 2_7, 3] UpperCAmelCase_: Optional[int] = [1_2_8, 2_5_6, 5_1_2, 1_0_2_4] UpperCAmelCase_: Any = 5_1_2 if "large" in model_name: UpperCAmelCase_: List[Any] = [3, 3, 2_7, 3] UpperCAmelCase_: Tuple = [1_9_2, 3_8_4, 7_6_8, 1_5_3_6] UpperCAmelCase_: Optional[int] = 7_6_8 if "xlarge" in model_name: UpperCAmelCase_: Dict = [3, 3, 2_7, 3] UpperCAmelCase_: Tuple = [2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] UpperCAmelCase_: Dict = 1_0_2_4 # set label information UpperCAmelCase_: Dict = 1_5_0 UpperCAmelCase_: str = """huggingface/label-files""" UpperCAmelCase_: int = """ade20k-id2label.json""" UpperCAmelCase_: int = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) ) UpperCAmelCase_: Optional[Any] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} UpperCAmelCase_: Union[str, Any] = {v: k for k, v in idalabel.items()} UpperCAmelCase_: List[Any] = ConvNextConfig( depths=lowerCAmelCase__ , hidden_sizes=lowerCAmelCase__ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) UpperCAmelCase_: Optional[Any] = UperNetConfig( backbone_config=lowerCAmelCase__ , auxiliary_in_channels=lowerCAmelCase__ , num_labels=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , ) return config def lowerCAmelCase_ (lowerCAmelCase__: Optional[int] ): """simple docstring""" UpperCAmelCase_: Tuple = [] # fmt: off # stem rename_keys.append(("""backbone.downsample_layers.0.0.weight""", """backbone.embeddings.patch_embeddings.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.0.bias""", """backbone.embeddings.patch_embeddings.bias""") ) rename_keys.append(("""backbone.downsample_layers.0.1.weight""", """backbone.embeddings.layernorm.weight""") ) rename_keys.append(("""backbone.downsample_layers.0.1.bias""", """backbone.embeddings.layernorm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'backbone.stages.{i}.{j}.gamma', F'backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter') ) rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.weight', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.bias', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.bias') ) rename_keys.append((F'backbone.stages.{i}.{j}.norm.weight', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.norm.bias', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.bias') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight') ) rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias') ) if i > 0: rename_keys.append((F'backbone.downsample_layers.{i}.0.weight', F'backbone.encoder.stages.{i}.downsampling_layer.0.weight') ) rename_keys.append((F'backbone.downsample_layers.{i}.0.bias', F'backbone.encoder.stages.{i}.downsampling_layer.0.bias') ) rename_keys.append((F'backbone.downsample_layers.{i}.1.weight', F'backbone.encoder.stages.{i}.downsampling_layer.1.weight') ) rename_keys.append((F'backbone.downsample_layers.{i}.1.bias', F'backbone.encoder.stages.{i}.downsampling_layer.1.bias') ) rename_keys.append((F'backbone.norm{i}.weight', F'backbone.hidden_states_norms.stage{i+1}.weight') ) rename_keys.append((F'backbone.norm{i}.bias', F'backbone.hidden_states_norms.stage{i+1}.bias') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def lowerCAmelCase_ (lowerCAmelCase__: Dict , lowerCAmelCase__: int , lowerCAmelCase__: int ): """simple docstring""" UpperCAmelCase_: Tuple = dct.pop(lowerCAmelCase__ ) UpperCAmelCase_: int = val def lowerCAmelCase_ (lowerCAmelCase__: int , lowerCAmelCase__: Optional[Any] , lowerCAmelCase__: int ): """simple docstring""" UpperCAmelCase_: str = { """upernet-convnext-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth""", """upernet-convnext-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth""", """upernet-convnext-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth""", """upernet-convnext-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth""", """upernet-convnext-xlarge""": """https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth""", } UpperCAmelCase_: List[str] = model_name_to_url[model_name] UpperCAmelCase_: Any = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location="""cpu""" )["""state_dict"""] UpperCAmelCase_: Any = get_upernet_config(lowerCAmelCase__ ) UpperCAmelCase_: int = UperNetForSemanticSegmentation(lowerCAmelCase__ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): UpperCAmelCase_: Optional[int] = state_dict.pop(lowerCAmelCase__ ) if "bn" in key: UpperCAmelCase_: str = key.replace("""bn""" , """batch_norm""" ) UpperCAmelCase_: Dict = val # rename keys UpperCAmelCase_: Optional[int] = create_rename_keys(lowerCAmelCase__ ) for src, dest in rename_keys: rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) # verify on image UpperCAmelCase_: List[str] = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" UpperCAmelCase_: Any = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ).convert("""RGB""" ) UpperCAmelCase_: Tuple = SegformerImageProcessor() UpperCAmelCase_: List[Any] = processor(lowerCAmelCase__ , return_tensors="""pt""" ).pixel_values with torch.no_grad(): UpperCAmelCase_: List[str] = model(lowerCAmelCase__ ) if model_name == "upernet-convnext-tiny": UpperCAmelCase_: List[Any] = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": UpperCAmelCase_: Optional[Any] = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": UpperCAmelCase_: int = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": UpperCAmelCase_: Union[str, Any] = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": UpperCAmelCase_: List[str] = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print("""Logits:""" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , lowerCAmelCase__ , atol=1e-4 ) 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(lowerCAmelCase__ ) print(F'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(F'Pushing model and processor for {model_name} to hub' ) model.push_to_hub(F'openmmlab/{model_name}' ) processor.push_to_hub(F'openmmlab/{model_name}' ) if __name__ == "__main__": a : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-convnext-tiny', type=str, choices=[F'''upernet-convnext-{size}''' for size in ['tiny', 'small', 'base', 'large', 'xlarge']], help='Name of the ConvNext UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a : str = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
362
from __future__ import annotations def lowerCAmelCase_ (lowerCAmelCase__: list[float] ): """simple docstring""" UpperCAmelCase_: Union[str, Any] = 0.00 UpperCAmelCase_: List[str] = 0 for resistor in resistors: if resistor <= 0: UpperCAmelCase_: Dict = F'Resistor at index {index} has a negative or zero value!' raise ValueError(lowerCAmelCase__ ) first_sum += 1 / float(lowerCAmelCase__ ) index += 1 return 1 / first_sum def lowerCAmelCase_ (lowerCAmelCase__: list[float] ): """simple docstring""" UpperCAmelCase_: Any = 0.00 UpperCAmelCase_: int = 0 for resistor in resistors: sum_r += resistor if resistor < 0: UpperCAmelCase_: int = F'Resistor at index {index} has a negative value!' raise ValueError(lowerCAmelCase__ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
82
0
from queue import Queue from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from ..models.auto import AutoTokenizer class lowerCamelCase__ : def __A (self , UpperCAmelCase ) -> Dict: raise NotImplementedError() def __A (self ) -> Optional[int]: raise NotImplementedError() class lowerCamelCase__ ( lowerCAmelCase): def __init__(self , UpperCAmelCase , UpperCAmelCase = False , **UpperCAmelCase ) -> Any: _lowercase =tokenizer _lowercase =skip_prompt _lowercase =decode_kwargs # variables used in the streaming process _lowercase =[] _lowercase =0 _lowercase =True def __A (self , UpperCAmelCase ) -> int: if len(value.shape ) > 1 and value.shape[0] > 1: raise ValueError('''TextStreamer only supports batch size 1''' ) elif len(value.shape ) > 1: _lowercase =value[0] if self.skip_prompt and self.next_tokens_are_prompt: _lowercase =False return # Add the new token to the cache and decodes the entire thing. self.token_cache.extend(value.tolist() ) _lowercase =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) # After the symbol for a new line, we flush the cache. if text.endswith('''\n''' ): _lowercase =text[self.print_len :] _lowercase =[] _lowercase =0 # If the last token is a CJK character, we print the characters. elif len(UpperCAmelCase ) > 0 and self._is_chinese_char(ord(text[-1] ) ): _lowercase =text[self.print_len :] self.print_len += len(UpperCAmelCase ) # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, # which may change with the subsequent token -- there are probably smarter ways to do this!) else: _lowercase =text[self.print_len : text.rfind(''' ''' ) + 1] self.print_len += len(UpperCAmelCase ) self.on_finalized_text(UpperCAmelCase ) def __A (self ) -> Any: # Flush the cache, if it exists if len(self.token_cache ) > 0: _lowercase =self.tokenizer.decode(self.token_cache , **self.decode_kwargs ) _lowercase =text[self.print_len :] _lowercase =[] _lowercase =0 else: _lowercase ='''''' _lowercase =True self.on_finalized_text(UpperCAmelCase , stream_end=UpperCAmelCase ) def __A (self , UpperCAmelCase , UpperCAmelCase = False ) -> Union[str, Any]: print(UpperCAmelCase , flush=UpperCAmelCase , end='''''' if not stream_end else None ) def __A (self , UpperCAmelCase ) -> Optional[int]: # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. if ( (cp >= 0X4_e_0_0 and cp <= 0X9_f_f_f) or (cp >= 0X3_4_0_0 and cp <= 0X4_d_b_f) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_a_6_d_f) # or (cp >= 0X2_a_7_0_0 and cp <= 0X2_b_7_3_f) # or (cp >= 0X2_b_7_4_0 and cp <= 0X2_b_8_1_f) # or (cp >= 0X2_b_8_2_0 and cp <= 0X2_c_e_a_f) # or (cp >= 0Xf_9_0_0 and cp <= 0Xf_a_f_f) or (cp >= 0X2_f_8_0_0 and cp <= 0X2_f_a_1_f) # ): # return True return False class lowerCamelCase__ ( lowerCAmelCase): def __init__(self , UpperCAmelCase , UpperCAmelCase = False , UpperCAmelCase = None , **UpperCAmelCase ) -> List[str]: super().__init__(UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ) _lowercase =Queue() _lowercase =None _lowercase =timeout def __A (self , UpperCAmelCase , UpperCAmelCase = False ) -> Any: self.text_queue.put(UpperCAmelCase , timeout=self.timeout ) if stream_end: self.text_queue.put(self.stop_signal , timeout=self.timeout ) def __iter__(self ) -> List[str]: return self def __A (self ) -> Dict: _lowercase =self.text_queue.get(timeout=self.timeout ) if value == self.stop_signal: raise StopIteration() else: return value
5
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase__ ( nn.Module): def __init__(self , UpperCAmelCase = 1_6 , UpperCAmelCase = 8_8 , UpperCAmelCase = None , UpperCAmelCase = 1 , UpperCAmelCase = 0.0 , UpperCAmelCase = 3_2 , UpperCAmelCase = None , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = "geglu" , UpperCAmelCase = None , ) -> Any: super().__init__() _lowercase =nn.ModuleList( [ TransformeraDModel( num_attention_heads=UpperCAmelCase , attention_head_dim=UpperCAmelCase , in_channels=UpperCAmelCase , num_layers=UpperCAmelCase , dropout=UpperCAmelCase , norm_num_groups=UpperCAmelCase , cross_attention_dim=UpperCAmelCase , attention_bias=UpperCAmelCase , sample_size=UpperCAmelCase , num_vector_embeds=UpperCAmelCase , activation_fn=UpperCAmelCase , num_embeds_ada_norm=UpperCAmelCase , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference _lowercase =0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` _lowercase =[7_7, 2_5_7] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` _lowercase =[1, 0] def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase = True , ) -> str: _lowercase =hidden_states _lowercase =[] _lowercase =0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens _lowercase =encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] _lowercase =self.transformer_index_for_condition[i] _lowercase =self.transformers[transformer_index]( UpperCAmelCase , encoder_hidden_states=UpperCAmelCase , timestep=UpperCAmelCase , cross_attention_kwargs=UpperCAmelCase , return_dict=UpperCAmelCase , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] _lowercase =encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) _lowercase =output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=UpperCAmelCase )
5
1
import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowercase ( snake_case__ , unittest.TestCase): """simple docstring""" a__ : Union[str, Any] = BlenderbotSmallTokenizer a__ : Union[str, Any] = False def _SCREAMING_SNAKE_CASE ( self : int ) -> int: super().setUp() UpperCAmelCase_= ["""__start__""", """adapt""", """act""", """ap@@""", """te""", """__end__""", """__unk__"""] UpperCAmelCase_= dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) UpperCAmelCase_= ["""#version: 0.2""", """a p""", """t e</w>""", """ap t</w>""", """a d""", """ad apt</w>""", """a c""", """ac t</w>""", """"""] UpperCAmelCase_= {"""unk_token""": """__unk__""", """bos_token""": """__start__""", """eos_token""": """__end__"""} UpperCAmelCase_= os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCAmelCase_= os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__UpperCAmelCase ) ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **__UpperCAmelCase : Optional[Any] ) -> str: kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , __UpperCAmelCase : Any ) -> Union[str, Any]: UpperCAmelCase_= """adapt act apte""" UpperCAmelCase_= """adapt act apte""" return input_text, output_text def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: UpperCAmelCase_= BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase_= """adapt act apte""" UpperCAmelCase_= ["""adapt""", """act""", """ap@@""", """te"""] UpperCAmelCase_= tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase_= [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCAmelCase_= [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , __UpperCAmelCase ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]: UpperCAmelCase_= BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) assert tok("""sam""" ).input_ids == [1_384] UpperCAmelCase_= """I am a small frog.""" UpperCAmelCase_= tok([src_text] , padding=__UpperCAmelCase , truncation=__UpperCAmelCase )["""input_ids"""] UpperCAmelCase_= tok.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: UpperCAmelCase_= BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) UpperCAmelCase_= """I am a small frog .""" UpperCAmelCase_= """.""" UpperCAmelCase_= tok(__UpperCAmelCase )["""input_ids"""] UpperCAmelCase_= tok(__UpperCAmelCase )["""input_ids"""] assert encoded[-1] == encoded_dot[0]
277
import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def __a ( ) -> str: '''simple docstring''' UpperCAmelCase_= torch.nn.Linear(2 ,4 ) UpperCAmelCase_= torch.optim.AdamW(model.parameters() ,lr=1.0 ) UpperCAmelCase_= torch.optim.lr_scheduler.OneCycleLR(lowerCAmelCase_ ,max_lr=0.01 ,steps_per_epoch=2 ,epochs=1 ) UpperCAmelCase_= DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) UpperCAmelCase_= DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def __a ( lowerCAmelCase_ : Any ) -> Union[str, Any]: '''simple docstring''' return (model.weight.abs().sum() + model.bias.abs().sum()).item() def __a ( lowerCAmelCase_ : Tuple ) -> Tuple: '''simple docstring''' UpperCAmelCase_= torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(lowerCAmelCase_ ) class lowercase ( snake_case__): """simple docstring""" @require_cuda def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[Any]: UpperCAmelCase_= Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(__UpperCAmelCase ): UpperCAmelCase_= Accelerator(cpu=__UpperCAmelCase ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> Union[str, Any]: UpperCAmelCase_= Accelerator() UpperCAmelCase_= GradientState() assert state.num_steps == 1 UpperCAmelCase_= 4 assert state.num_steps == 4 assert state.sync_gradients is True UpperCAmelCase_= False assert state.sync_gradients is False GradientState._reset_state() def _SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: UpperCAmelCase_= Accelerator() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= create_components() ( ( UpperCAmelCase_ ), ( UpperCAmelCase_ ), ( UpperCAmelCase_ ), ( UpperCAmelCase_ ), ( UpperCAmelCase_ ), )= accelerator.prepare(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def _SCREAMING_SNAKE_CASE ( self : int ) -> Dict: UpperCAmelCase_= Accelerator() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= create_components() accelerator.prepare(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*__UpperCAmelCase : Dict , **__UpperCAmelCase : Tuple ): pass with patch("""torch.cuda.set_device""" , __UpperCAmelCase ), patch_environment(ACCELERATE_TORCH_DEVICE="""cuda:64""" ): UpperCAmelCase_= Accelerator() self.assertEqual(str(accelerator.state.device ) , """cuda:64""" ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: UpperCAmelCase_= Accelerator() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= create_components() accelerator.prepare(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase_= get_signature(__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(__UpperCAmelCase ) # make sure random weights don't match load_random_weights(__UpperCAmelCase ) self.assertTrue(abs(model_signature - get_signature(__UpperCAmelCase ) ) > 1E-3 ) # make sure loaded weights match accelerator.load_state(__UpperCAmelCase ) self.assertTrue(abs(model_signature - get_signature(__UpperCAmelCase ) ) < 1E-3 ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[Any]: UpperCAmelCase_= Accelerator() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= create_components() accelerator.prepare(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase_= get_signature(__UpperCAmelCase ) # saving hook def save_config(__UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] , __UpperCAmelCase : Tuple ): UpperCAmelCase_= {"""class_name""": models[0].__class__.__name__} with open(os.path.join(__UpperCAmelCase , """data.json""" ) , """w""" ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) # loading hook def load_config(__UpperCAmelCase : Tuple , __UpperCAmelCase : Union[str, Any] ): with open(os.path.join(__UpperCAmelCase , """data.json""" ) , """r""" ) as f: UpperCAmelCase_= json.load(__UpperCAmelCase ) UpperCAmelCase_= config["""class_name"""] UpperCAmelCase_= accelerator.register_save_state_pre_hook(__UpperCAmelCase ) UpperCAmelCase_= accelerator.register_load_state_pre_hook(__UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(__UpperCAmelCase ) # make sure random weights don't match with hooks load_random_weights(__UpperCAmelCase ) self.assertTrue(abs(model_signature - get_signature(__UpperCAmelCase ) ) > 1E-3 ) # random class name to verify correct one is loaded UpperCAmelCase_= """random""" # make sure loaded weights match with hooks accelerator.load_state(__UpperCAmelCase ) self.assertTrue(abs(model_signature - get_signature(__UpperCAmelCase ) ) < 1E-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(__UpperCAmelCase ) # make sure random weights don't match with hooks removed load_random_weights(__UpperCAmelCase ) self.assertTrue(abs(model_signature - get_signature(__UpperCAmelCase ) ) > 1E-3 ) # random class name to verify correct one is loaded UpperCAmelCase_= """random""" # make sure loaded weights match with hooks removed accelerator.load_state(__UpperCAmelCase ) self.assertTrue(abs(model_signature - get_signature(__UpperCAmelCase ) ) < 1E-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: UpperCAmelCase_= Accelerator() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= create_components() UpperCAmelCase_= None # This should work UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= accelerator.prepare( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) self.assertTrue(dummy_obj is None ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Any: UpperCAmelCase_= Accelerator() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= create_components() UpperCAmelCase_= [1, 2, 3] # This should work UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_= accelerator.prepare( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) self.assertEqual( getattr(__UpperCAmelCase , """_is_accelerate_prepared""" , __UpperCAmelCase ) , __UpperCAmelCase , """Dummy object should have `_is_accelerate_prepared` set to `True`""" , ) self.assertEqual( getattr(__UpperCAmelCase , """_is_accelerate_prepared""" , __UpperCAmelCase ) , __UpperCAmelCase , """Model is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__UpperCAmelCase , """_is_accelerate_prepared""" , __UpperCAmelCase ) , __UpperCAmelCase , """Optimizer is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__UpperCAmelCase , """_is_accelerate_prepared""" , __UpperCAmelCase ) , __UpperCAmelCase , """Scheduler is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__UpperCAmelCase , """_is_accelerate_prepared""" , __UpperCAmelCase ) , __UpperCAmelCase , """Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__UpperCAmelCase , """_is_accelerate_prepared""" , __UpperCAmelCase ) , __UpperCAmelCase , """Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`""" , ) @slow @require_bnb def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: from transformers import AutoModelForCausalLM UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , load_in_abit=__UpperCAmelCase , device_map={"""""": 0} , ) UpperCAmelCase_= Accelerator() # This should work UpperCAmelCase_= accelerator.prepare(__UpperCAmelCase ) @slow @require_bnb def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: from transformers import AutoModelForCausalLM UpperCAmelCase_= Accelerator() with init_empty_weights(): UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , ) model.tie_weights() UpperCAmelCase_= infer_auto_device_map(__UpperCAmelCase ) UpperCAmelCase_= """cpu""" UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , device_map=__UpperCAmelCase , load_in_abit=__UpperCAmelCase , llm_inta_enable_fpaa_cpu_offload=__UpperCAmelCase ) # This should not work and get value error with self.assertRaises(__UpperCAmelCase ): UpperCAmelCase_= accelerator.prepare(__UpperCAmelCase ) @slow @require_bnb @require_multi_gpu def _SCREAMING_SNAKE_CASE ( self : int ) -> Tuple: from transformers import AutoModelForCausalLM UpperCAmelCase_= {"""distributed_type""": DistributedType.MULTI_GPU} with init_empty_weights(): UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , ) model.tie_weights() UpperCAmelCase_= infer_auto_device_map(__UpperCAmelCase ) UpperCAmelCase_= 1 UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , load_in_abit=__UpperCAmelCase , device_map=__UpperCAmelCase , ) UpperCAmelCase_= Accelerator() # This should not work and get value error with self.assertRaises(__UpperCAmelCase ): UpperCAmelCase_= accelerator.prepare(__UpperCAmelCase ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def _SCREAMING_SNAKE_CASE ( self : Any ) -> Dict: from transformers import AutoModelForCausalLM with init_empty_weights(): UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , ) UpperCAmelCase_= infer_auto_device_map(__UpperCAmelCase ) UpperCAmelCase_= 1 UpperCAmelCase_= AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , load_in_abit=__UpperCAmelCase , device_map=__UpperCAmelCase , ) UpperCAmelCase_= Accelerator() # This should work UpperCAmelCase_= accelerator.prepare(__UpperCAmelCase ) @require_cuda def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[int]: UpperCAmelCase_= torch.nn.Linear(10 , 10 ) UpperCAmelCase_= torch.optim.SGD(model.parameters() , lr=0.01 ) UpperCAmelCase_= Accelerator(cpu=__UpperCAmelCase ) UpperCAmelCase_= accelerator.prepare(__UpperCAmelCase )
277
1
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva import numpy as np # Parrameters lowercase : Optional[int] = (7_20, 12_80) # Height, Width lowercase : List[str] = (0.4, 0.6) # if height or width lower than this scale, drop it. lowercase : List[Any] = 1 / 1_00 lowercase : Optional[Any] = '' lowercase : Dict = '' lowercase : str = '' lowercase : str = 2_50 def lowerCAmelCase_ ( ): '''simple docstring''' A, A : Dict = get_dataset(snake_case__ , snake_case__ ) for index in range(snake_case__ ): A : Tuple = random.sample(range(len(snake_case__ ) ) , 4 ) A, A, A : List[str] = update_image_and_anno( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , filter_scale=snake_case__ , ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' A : Union[str, Any] = random_chars(32 ) A : Any = path.split(os.sep )[-1].rsplit('''.''' , 1 )[0] A : Union[str, Any] = F'{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}' cva.imwrite(F'{file_root}.jpg' , snake_case__ , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}' ) A : Dict = [] for anno in new_annos: A : Optional[int] = anno[3] - anno[1] A : int = anno[4] - anno[2] A : str = anno[1] + width / 2 A : List[str] = anno[2] + height / 2 A : Dict = F'{anno[0]} {x_center} {y_center} {width} {height}' annos_list.append(snake_case__ ) with open(F'{file_root}.txt' , '''w''' ) as outfile: outfile.write('''\n'''.join(line for line in annos_list ) ) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : Dict = [] A : Dict = [] for label_file in glob.glob(os.path.join(snake_case__ , '''*.txt''' ) ): A : List[str] = label_file.split(os.sep )[-1].rsplit('''.''' , 1 )[0] with open(snake_case__ ) as in_file: A : Optional[Any] = in_file.readlines() A : Optional[Any] = os.path.join(snake_case__ , F'{label_name}.jpg' ) A : Tuple = [] for obj_list in obj_lists: A : List[Any] = obj_list.rstrip('''\n''' ).split(''' ''' ) A : str = float(obj[1] ) - float(obj[3] ) / 2 A : List[Any] = float(obj[2] ) - float(obj[4] ) / 2 A : int = float(obj[1] ) + float(obj[3] ) / 2 A : Optional[Any] = float(obj[2] ) + float(obj[4] ) / 2 boxes.append([int(obj[0] ), xmin, ymin, xmax, ymax] ) if not boxes: continue img_paths.append(snake_case__ ) labels.append(snake_case__ ) return img_paths, labels def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ = 0.0 , ): '''simple docstring''' A : List[str] = np.zeros([output_size[0], output_size[1], 3] , dtype=np.uinta ) A : List[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) A : Optional[Any] = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) A : Optional[Any] = int(scale_x * output_size[1] ) A : Union[str, Any] = int(scale_y * output_size[0] ) A : Union[str, Any] = [] A : Union[str, Any] = [] for i, index in enumerate(snake_case__ ): A : List[Any] = all_img_list[index] path_list.append(snake_case__ ) A : Tuple = all_annos[index] A : Optional[Any] = cva.imread(snake_case__ ) if i == 0: # top-left A : Optional[Any] = cva.resize(snake_case__ , (divid_point_x, divid_point_y) ) A : Optional[Any] = img for bbox in img_annos: A : Union[str, Any] = bbox[1] * scale_x A : Optional[Any] = bbox[2] * scale_y A : int = bbox[3] * scale_x A : Optional[int] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 1: # top-right A : Any = cva.resize(snake_case__ , (output_size[1] - divid_point_x, divid_point_y) ) A : Optional[Any] = img for bbox in img_annos: A : Optional[Any] = scale_x + bbox[1] * (1 - scale_x) A : Tuple = bbox[2] * scale_y A : Any = scale_x + bbox[3] * (1 - scale_x) A : List[str] = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) elif i == 2: # bottom-left A : Optional[Any] = cva.resize(snake_case__ , (divid_point_x, output_size[0] - divid_point_y) ) A : Any = img for bbox in img_annos: A : Optional[Any] = bbox[1] * scale_x A : List[str] = scale_y + bbox[2] * (1 - scale_y) A : Optional[Any] = bbox[3] * scale_x A : Any = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) else: # bottom-right A : List[str] = cva.resize( snake_case__ , (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) A : str = img for bbox in img_annos: A : Dict = scale_x + bbox[1] * (1 - scale_x) A : int = scale_y + bbox[2] * (1 - scale_y) A : List[Any] = scale_x + bbox[3] * (1 - scale_x) A : Any = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax] ) # Remove bounding box small than scale of filter if filter_scale > 0: A : List[str] = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' assert number_char > 1, "The number of character should greater than 1" A : int = ascii_lowercase + digits return "".join(random.choice(snake_case__ ) for _ in range(snake_case__ ) ) if __name__ == "__main__": main() print('DONE ✅')
3
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) lowercase : Dict = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'], 'processing_speech_to_text': ['Speech2TextProcessor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : List[Any] = ['Speech2TextTokenizer'] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : List[str] = ['Speech2TextFeatureExtractor'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = [ 'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSpeech2TextForConditionalGeneration', 'TFSpeech2TextModel', 'TFSpeech2TextPreTrainedModel', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Any = [ 'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Speech2TextForConditionalGeneration', 'Speech2TextModel', 'Speech2TextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
3
1
'''simple docstring''' from torch import nn class A_ ( nn.Module ): '''simple docstring''' def __init__( self : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : List[Any] ) -> int: super().__init__() UpperCAmelCase : Optional[int] = class_size UpperCAmelCase : Optional[int] = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) UpperCAmelCase : Dict = nn.Linear(lowercase_ , lowercase_ ) def UpperCAmelCase_ ( self : List[Any] , lowercase_ : Any ) -> Union[str, Any]: # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) UpperCAmelCase : Optional[int] = self.mlp(lowercase_ ) return logits
280
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowercase__ = logging.get_logger(__name__) def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ ): UpperCAmelCase : Optional[Any] = b.T UpperCAmelCase : Optional[int] = np.sum(np.square(UpperCAmelCase_ ) , axis=1 ) UpperCAmelCase : List[Any] = np.sum(np.square(UpperCAmelCase_ ) , axis=0 ) UpperCAmelCase : List[str] = np.matmul(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCAmelCase : Union[str, Any] = aa[:, None] - 2 * ab + ba[None, :] return d def UpperCamelCase( UpperCAmelCase_ , UpperCAmelCase_ ): UpperCAmelCase : int = x.reshape(-1 , 3 ) UpperCAmelCase : Optional[int] = squared_euclidean_distance(UpperCAmelCase_ , UpperCAmelCase_ ) return np.argmin(UpperCAmelCase_ , axis=1 ) class A_ ( _snake_case ): '''simple docstring''' UpperCAmelCase_ : List[Any] = ["""pixel_values"""] def __init__( self : List[Any] , lowercase_ : Optional[Union[List[List[int]], np.ndarray]] = None , lowercase_ : bool = True , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : bool = True , lowercase_ : bool = True , **lowercase_ : Optional[Any] , ) -> None: super().__init__(**lowercase_ ) UpperCAmelCase : Any = size if size is not None else {'height': 256, 'width': 256} UpperCAmelCase : List[Any] = get_size_dict(lowercase_ ) UpperCAmelCase : str = np.array(lowercase_ ) if clusters is not None else None UpperCAmelCase : Any = do_resize UpperCAmelCase : List[Any] = size UpperCAmelCase : Any = resample UpperCAmelCase : Dict = do_normalize UpperCAmelCase : List[Any] = do_color_quantize def UpperCAmelCase_ ( self : int , lowercase_ : np.ndarray , lowercase_ : Dict[str, int] , lowercase_ : PILImageResampling = PILImageResampling.BILINEAR , lowercase_ : Optional[Union[str, ChannelDimension]] = None , **lowercase_ : Any , ) -> np.ndarray: UpperCAmelCase : Dict = get_size_dict(lowercase_ ) if "height" not in size or "width" not in size: raise ValueError(f"""Size dictionary must contain both height and width keys. Got {size.keys()}""" ) return resize( lowercase_ , size=(size['height'], size['width']) , resample=lowercase_ , data_format=lowercase_ , **lowercase_ ) def UpperCAmelCase_ ( self : Optional[int] , lowercase_ : np.ndarray , lowercase_ : Optional[Union[str, ChannelDimension]] = None , ) -> np.ndarray: UpperCAmelCase : int = rescale(image=lowercase_ , scale=1 / 127.5 , data_format=lowercase_ ) UpperCAmelCase : Dict = image - 1 return image def UpperCAmelCase_ ( self : str , lowercase_ : ImageInput , lowercase_ : bool = None , lowercase_ : Dict[str, int] = None , lowercase_ : PILImageResampling = None , lowercase_ : bool = None , lowercase_ : Optional[bool] = None , lowercase_ : Optional[Union[List[List[int]], np.ndarray]] = None , lowercase_ : Optional[Union[str, TensorType]] = None , lowercase_ : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **lowercase_ : List[str] , ) -> PIL.Image.Image: UpperCAmelCase : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCAmelCase : Optional[Any] = size if size is not None else self.size UpperCAmelCase : Optional[int] = get_size_dict(lowercase_ ) UpperCAmelCase : Any = resample if resample is not None else self.resample UpperCAmelCase : Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase : str = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCAmelCase : Optional[int] = clusters if clusters is not None else self.clusters UpperCAmelCase : List[str] = np.array(lowercase_ ) UpperCAmelCase : int = make_list_of_images(lowercase_ ) if not valid_images(lowercase_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. UpperCAmelCase : Dict = [to_numpy_array(lowercase_ ) for image in images] if do_resize: UpperCAmelCase : List[Any] = [self.resize(image=lowercase_ , size=lowercase_ , resample=lowercase_ ) for image in images] if do_normalize: UpperCAmelCase : Tuple = [self.normalize(image=lowercase_ ) for image in images] if do_color_quantize: UpperCAmelCase : List[str] = [to_channel_dimension_format(lowercase_ , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCAmelCase : int = np.array(lowercase_ ) UpperCAmelCase : str = color_quantize(lowercase_ , lowercase_ ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCAmelCase : Optional[int] = images.shape[0] UpperCAmelCase : Union[str, Any] = images.reshape(lowercase_ , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCAmelCase : int = list(lowercase_ ) else: UpperCAmelCase : Dict = [to_channel_dimension_format(lowercase_ , lowercase_ ) for image in images] UpperCAmelCase : Any = {'input_ids': images} return BatchFeature(data=lowercase_ , tensor_type=lowercase_ )
280
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class UpperCamelCase__ (unittest.TestCase ): '''simple docstring''' def _lowercase ( self ) -> List[Any]: lowerCamelCase : Any = "ZinengTang/tvlt-base" lowerCamelCase : Dict = tempfile.mkdtemp() def _lowercase ( self , **UpperCamelCase__ ) -> int: return TvltImageProcessor.from_pretrained(self.checkpoint , **UpperCAmelCase_ ) def _lowercase ( self , **UpperCamelCase__ ) -> Any: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **UpperCAmelCase_ ) def _lowercase ( self ) -> Any: shutil.rmtree(self.tmpdirname ) def _lowercase ( self ) -> List[Any]: lowerCamelCase : Union[str, Any] = self.get_image_processor() lowerCamelCase : Any = self.get_feature_extractor() lowerCamelCase : Tuple = TvltProcessor(image_processor=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase : Any = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase_ ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def _lowercase ( self ) -> Dict: lowerCamelCase : Union[str, Any] = self.get_image_processor() lowerCamelCase : Tuple = self.get_feature_extractor() lowerCamelCase : int = TvltProcessor(image_processor=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ ) lowerCamelCase : List[Any] = np.ones([1_2000] ) lowerCamelCase : Optional[Any] = feature_extractor(UpperCAmelCase_ , return_tensors="np" ) lowerCamelCase : Dict = processor(audio=UpperCAmelCase_ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _lowercase ( self ) -> List[Any]: lowerCamelCase : Dict = self.get_image_processor() lowerCamelCase : List[Any] = self.get_feature_extractor() lowerCamelCase : Any = TvltProcessor(image_processor=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ ) lowerCamelCase : str = np.ones([3, 224, 224] ) lowerCamelCase : Optional[int] = image_processor(UpperCAmelCase_ , return_tensors="np" ) lowerCamelCase : Union[str, Any] = processor(images=UpperCAmelCase_ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _lowercase ( self ) -> Any: lowerCamelCase : Dict = self.get_image_processor() lowerCamelCase : Union[str, Any] = self.get_feature_extractor() lowerCamelCase : Union[str, Any] = TvltProcessor(image_processor=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ ) lowerCamelCase : Any = np.ones([1_2000] ) lowerCamelCase : Any = np.ones([3, 224, 224] ) lowerCamelCase : Union[str, Any] = processor(audio=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase_ ): processor() def _lowercase ( self ) -> Tuple: lowerCamelCase : Dict = self.get_image_processor() lowerCamelCase : Any = self.get_feature_extractor() lowerCamelCase : Tuple = TvltProcessor(image_processor=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
48
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "microsoft/unispeech-large-1500h-cv": ( "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json" ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "unispeech" def __init__(self : Any , UpperCAmelCase_ : Any=32 , UpperCAmelCase_ : List[str]=768 , UpperCAmelCase_ : Any=12 , UpperCAmelCase_ : Union[str, Any]=12 , UpperCAmelCase_ : Optional[Any]=3_072 , UpperCAmelCase_ : List[Any]="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Any=0.0 , UpperCAmelCase_ : str=0.0 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Optional[Any]=0.02 , UpperCAmelCase_ : Union[str, Any]=1E-5 , UpperCAmelCase_ : str="group" , UpperCAmelCase_ : List[Any]="gelu" , UpperCAmelCase_ : Tuple=(512, 512, 512, 512, 512, 512, 512) , UpperCAmelCase_ : str=(5, 2, 2, 2, 2, 2, 2) , UpperCAmelCase_ : Any=(10, 3, 3, 3, 3, 2, 2) , UpperCAmelCase_ : Optional[Any]=False , UpperCAmelCase_ : str=128 , UpperCAmelCase_ : int=16 , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Dict=0.05 , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Union[str, Any]=0.0 , UpperCAmelCase_ : int=10 , UpperCAmelCase_ : List[Any]=0 , UpperCAmelCase_ : Optional[Any]=320 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : str=100 , UpperCAmelCase_ : Any=256 , UpperCAmelCase_ : int=256 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : str="mean" , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]=256 , UpperCAmelCase_ : Optional[int]=80 , UpperCAmelCase_ : Optional[int]=0 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Dict=0.5 , **UpperCAmelCase_ : Optional[int] , ) ->str: '''simple docstring''' super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =hidden_size lowerCamelCase__: List[str] =feat_extract_norm lowerCamelCase__: Dict =feat_extract_activation lowerCamelCase__: Optional[Any] =list(UpperCAmelCase_) lowerCamelCase__: Any =list(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =list(UpperCAmelCase_) lowerCamelCase__: Dict =conv_bias lowerCamelCase__: Optional[Any] =num_conv_pos_embeddings lowerCamelCase__: Dict =num_conv_pos_embedding_groups lowerCamelCase__: int =len(self.conv_dim) lowerCamelCase__: Union[str, Any] =num_hidden_layers lowerCamelCase__: Union[str, Any] =intermediate_size lowerCamelCase__: Dict =hidden_act lowerCamelCase__: List[Any] =num_attention_heads lowerCamelCase__: Dict =hidden_dropout lowerCamelCase__: Optional[Any] =attention_dropout lowerCamelCase__: Optional[Any] =activation_dropout lowerCamelCase__: Tuple =feat_proj_dropout lowerCamelCase__: int =final_dropout lowerCamelCase__: Optional[Any] =layerdrop lowerCamelCase__: Dict =layer_norm_eps lowerCamelCase__: Optional[Any] =initializer_range lowerCamelCase__: int =num_ctc_classes lowerCamelCase__: Tuple =vocab_size lowerCamelCase__: Dict =do_stable_layer_norm lowerCamelCase__: List[Any] =use_weighted_layer_sum lowerCamelCase__: Dict =classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==" " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =" F""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,""" F""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowerCamelCase__: int =apply_spec_augment lowerCamelCase__: List[str] =mask_time_prob lowerCamelCase__: Union[str, Any] =mask_time_length lowerCamelCase__: List[Any] =mask_time_min_masks lowerCamelCase__: Any =mask_feature_prob lowerCamelCase__: Optional[Any] =mask_feature_length lowerCamelCase__: List[str] =mask_feature_min_masks # parameters for pretraining with codevector quantized representations lowerCamelCase__: Optional[Any] =num_codevectors_per_group lowerCamelCase__: str =num_codevector_groups lowerCamelCase__: Tuple =contrastive_logits_temperature lowerCamelCase__: int =feat_quantizer_dropout lowerCamelCase__: Any =num_negatives lowerCamelCase__: List[str] =codevector_dim lowerCamelCase__: Union[str, Any] =proj_codevector_dim lowerCamelCase__: Any =diversity_loss_weight # ctc loss lowerCamelCase__: Any =ctc_loss_reduction lowerCamelCase__: Dict =ctc_zero_infinity # pretraining loss lowerCamelCase__: Dict =replace_prob @property def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->Optional[Any]: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1)
10
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart __UpperCAmelCase = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } __UpperCAmelCase = { '''facebook/bart-base''': 1_024, '''facebook/bart-large''': 1_024, '''facebook/bart-large-mnli''': 1_024, '''facebook/bart-large-cnn''': 1_024, '''facebook/bart-large-xsum''': 1_024, '''yjernite/bart_eli5''': 1_024, } class a__ ( snake_case_ ): '''simple docstring''' lowercase__ : List[str] = VOCAB_FILES_NAMES lowercase__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP lowercase__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ : Union[str, Any] = ["input_ids", "attention_mask"] lowercase__ : Any = BartTokenizer def __init__( self , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_="replace" , lowerCamelCase_="<s>" , lowerCamelCase_="</s>" , lowerCamelCase_="</s>" , lowerCamelCase_="<s>" , lowerCamelCase_="<unk>" , lowerCamelCase_="<pad>" , lowerCamelCase_="<mask>" , lowerCamelCase_=False , lowerCamelCase_=True , **lowerCamelCase_ , ) -> Dict: super().__init__( _A , _A , tokenizer_file=_A , errors=_A , bos_token=_A , eos_token=_A , sep_token=_A , cls_token=_A , unk_token=_A , pad_token=_A , mask_token=_A , add_prefix_space=_A , trim_offsets=_A , **_A , ) lowerCAmelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , _A ) != add_prefix_space: lowerCAmelCase__ = getattr(_A , pre_tok_state.pop('''type''' ) ) lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = pre_tok_class(**_A ) lowerCAmelCase__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` lowerCAmelCase__ = 'post_processor' lowerCAmelCase__ = getattr(self.backend_tokenizer , _A , _A ) if tokenizer_component_instance: lowerCAmelCase__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: lowerCAmelCase__ = tuple(state['''sep'''] ) if "cls" in state: lowerCAmelCase__ = tuple(state['''cls'''] ) lowerCAmelCase__ = False if state.get('''add_prefix_space''' , _A ) != add_prefix_space: lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = True if state.get('''trim_offsets''' , _A ) != trim_offsets: lowerCAmelCase__ = trim_offsets lowerCAmelCase__ = True if changes_to_apply: lowerCAmelCase__ = getattr(_A , state.pop('''type''' ) ) lowerCAmelCase__ = component_class(**_A ) setattr(self.backend_tokenizer , _A , _A ) @property def __SCREAMING_SNAKE_CASE ( self ) -> str: if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> Tuple: lowerCAmelCase__ = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else value lowerCAmelCase__ = value def __SCREAMING_SNAKE_CASE ( self , *lowerCamelCase_ , **lowerCamelCase_ ) -> BatchEncoding: lowerCAmelCase__ = kwargs.get('''is_split_into_words''' , _A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*_A , **_A ) def __SCREAMING_SNAKE_CASE ( self , *lowerCamelCase_ , **lowerCamelCase_ ) -> BatchEncoding: lowerCAmelCase__ = kwargs.get('''is_split_into_words''' , _A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*_A , **_A ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ = None ) -> Tuple[str]: lowerCAmelCase__ = self._tokenizer.model.save(_A , name=_A ) return tuple(_A ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_=None ) -> Optional[Any]: lowerCAmelCase__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
350
'''simple docstring''' from __future__ import annotations def _snake_case ( A , A ) -> float: lowerCAmelCase__ = sorted(numsa + numsa ) lowerCAmelCase__ , lowerCAmelCase__ = divmod(len(A ) , 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase = [float(x) for x in input('''Enter the elements of first array: ''').split()] __UpperCAmelCase = [float(x) for x in input('''Enter the elements of second array: ''').split()] print(f"""The median of two arrays is: {median_of_two_arrays(array_a, array_a)}""")
228
0
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 lowercase_ = ( '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 _snake_case( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: '''simple docstring''' warnings.warn(__snake_case , __snake_case ) requires_backends(__snake_case , 'sklearn' ) return (preds == labels).mean() def _snake_case( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: '''simple docstring''' warnings.warn(__snake_case , __snake_case ) requires_backends(__snake_case , 'sklearn' ) A__ = simple_accuracy(__snake_case , __snake_case ) A__ = fa_score(y_true=__snake_case , y_pred=__snake_case ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def _snake_case( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> str: '''simple docstring''' warnings.warn(__snake_case , __snake_case ) requires_backends(__snake_case , 'sklearn' ) A__ = pearsonr(__snake_case , __snake_case )[0] A__ = spearmanr(__snake_case , __snake_case )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def _snake_case( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> List[Any]: '''simple docstring''' warnings.warn(__snake_case , __snake_case ) requires_backends(__snake_case , 'sklearn' ) assert len(__snake_case ) == len(__snake_case ), f'Predictions and labels have mismatched lengths {len(__snake_case )} and {len(__snake_case )}' if task_name == "cola": return {"mcc": matthews_corrcoef(__snake_case , __snake_case )} elif task_name == "sst-2": return {"acc": simple_accuracy(__snake_case , __snake_case )} elif task_name == "mrpc": return acc_and_fa(__snake_case , __snake_case ) elif task_name == "sts-b": return pearson_and_spearman(__snake_case , __snake_case ) elif task_name == "qqp": return acc_and_fa(__snake_case , __snake_case ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(__snake_case , __snake_case )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(__snake_case , __snake_case )} elif task_name == "qnli": return {"acc": simple_accuracy(__snake_case , __snake_case )} elif task_name == "rte": return {"acc": simple_accuracy(__snake_case , __snake_case )} elif task_name == "wnli": return {"acc": simple_accuracy(__snake_case , __snake_case )} elif task_name == "hans": return {"acc": simple_accuracy(__snake_case , __snake_case )} else: raise KeyError(__snake_case ) def _snake_case( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ) -> List[Any]: '''simple docstring''' warnings.warn(__snake_case , __snake_case ) requires_backends(__snake_case , 'sklearn' ) if len(__snake_case ) != len(__snake_case ): raise ValueError(f'Predictions and labels have mismatched lengths {len(__snake_case )} and {len(__snake_case )}' ) if task_name == "xnli": return {"acc": simple_accuracy(__snake_case , __snake_case )} else: raise KeyError(__snake_case )
7
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case : Union[str, Any] = logging.get_logger(__name__) __snake_case : List[str] = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class lowerCamelCase ( lowercase_ ): '''simple docstring''' __snake_case = 'camembert' def __init__( self : int , lowerCAmelCase_ : Tuple=3_05_22 , lowerCAmelCase_ : Tuple=7_68 , lowerCAmelCase_ : List[str]=12 , lowerCAmelCase_ : Any=12 , lowerCAmelCase_ : Tuple=30_72 , lowerCAmelCase_ : Dict="gelu" , lowerCAmelCase_ : Dict=0.1 , lowerCAmelCase_ : Tuple=0.1 , lowerCAmelCase_ : Tuple=5_12 , lowerCAmelCase_ : Optional[Any]=2 , lowerCAmelCase_ : Tuple=0.02 , lowerCAmelCase_ : Tuple=1e-12 , lowerCAmelCase_ : int=1 , lowerCAmelCase_ : Optional[Any]=0 , lowerCAmelCase_ : List[str]=2 , lowerCAmelCase_ : Dict="absolute" , lowerCAmelCase_ : List[str]=True , lowerCAmelCase_ : Union[str, Any]=None , **lowerCAmelCase_ : Union[str, Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) A__ : Optional[int] =vocab_size A__ : Any =hidden_size A__ : Optional[Any] =num_hidden_layers A__ : Optional[int] =num_attention_heads A__ : Optional[int] =hidden_act A__ : Optional[Any] =intermediate_size A__ : Tuple =hidden_dropout_prob A__ : Union[str, Any] =attention_probs_dropout_prob A__ : List[str] =max_position_embeddings A__ : int =type_vocab_size A__ : int =initializer_range A__ : Tuple =layer_norm_eps A__ : Dict =position_embedding_type A__ : List[str] =use_cache A__ : Dict =classifier_dropout class lowerCamelCase ( lowercase_ ): '''simple docstring''' @property def lowercase__ ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": A__ : Optional[int] ={0: """batch""", 1: """choice""", 2: """sequence"""} else: A__ : List[str] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
134
0
import json import unittest import numpy as np from huggingface_hub import hf_hub_download 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 transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Any , __UpperCamelCase : Tuple="shi-labs/oneformer_demo" ) -> Tuple: """simple docstring""" with open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type="""dataset""" ) , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.load(__UpperCamelCase ) SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for key, info in class_info.items(): SCREAMING_SNAKE_CASE__ = info["""name"""] class_names.append(info["""name"""] ) if info["isthing"]: thing_ids.append(int(__UpperCamelCase ) ) SCREAMING_SNAKE_CASE__ = thing_ids SCREAMING_SNAKE_CASE__ = class_names return metadata class __snake_case ( unittest.TestCase ): def __init__( self : List[Any] , _lowercase : Optional[Any] , _lowercase : int=7 , _lowercase : Any=3 , _lowercase : int=30 , _lowercase : List[Any]=4_00 , _lowercase : Union[str, Any]=None , _lowercase : Dict=True , _lowercase : Tuple=True , _lowercase : int=[0.5, 0.5, 0.5] , _lowercase : List[str]=[0.5, 0.5, 0.5] , _lowercase : str=10 , _lowercase : Union[str, Any]=False , _lowercase : int=2_55 , _lowercase : List[str]="shi-labs/oneformer_demo" , _lowercase : Any="ade20k_panoptic.json" , _lowercase : Any=10 , ): """simple docstring""" 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__ = {"""shortest_edge""": 32, """longest_edge""": 13_33} if size is None else size SCREAMING_SNAKE_CASE__ = do_normalize SCREAMING_SNAKE_CASE__ = image_mean SCREAMING_SNAKE_CASE__ = image_std SCREAMING_SNAKE_CASE__ = class_info_file SCREAMING_SNAKE_CASE__ = prepare_metadata(_lowercase , _lowercase ) SCREAMING_SNAKE_CASE__ = num_text SCREAMING_SNAKE_CASE__ = repo_path # for the post_process_functions SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 10 SCREAMING_SNAKE_CASE__ = 10 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = do_reduce_labels SCREAMING_SNAKE_CASE__ = ignore_index def __a ( self : Optional[int] ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def __a ( self : List[Any] , _lowercase : Any , _lowercase : Optional[Any]=False ): """simple docstring""" if not batched: SCREAMING_SNAKE_CASE__ = image_inputs[0] if isinstance(_lowercase , 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(_lowercase , key=lambda _lowercase : item[0] )[0] SCREAMING_SNAKE_CASE__ = max(_lowercase , key=lambda _lowercase : item[1] )[1] return expected_height, expected_width def __a ( self : Dict ): """simple docstring""" return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) , masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) , ) @require_torch @require_vision class __snake_case ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string lowerCAmelCase_ = image_processing_class def __a ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE__ = OneFormerImageProcessorTester(self ) @property def __a ( self : str ): """simple docstring""" return self.image_processing_tester.prepare_image_processor_dict() def __a ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowercase , """image_mean""" ) ) self.assertTrue(hasattr(_lowercase , """image_std""" ) ) self.assertTrue(hasattr(_lowercase , """do_normalize""" ) ) self.assertTrue(hasattr(_lowercase , """do_resize""" ) ) self.assertTrue(hasattr(_lowercase , """size""" ) ) self.assertTrue(hasattr(_lowercase , """ignore_index""" ) ) self.assertTrue(hasattr(_lowercase , """class_info_file""" ) ) self.assertTrue(hasattr(_lowercase , """num_text""" ) ) self.assertTrue(hasattr(_lowercase , """repo_path""" ) ) self.assertTrue(hasattr(_lowercase , """metadata""" ) ) self.assertTrue(hasattr(_lowercase , """do_reduce_labels""" ) ) def __a ( self : Any ): """simple docstring""" pass def __a ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowercase ) for image in image_inputs: self.assertIsInstance(_lowercase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_expected_values(_lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_expected_values(_lowercase , batched=_lowercase ) SCREAMING_SNAKE_CASE__ = image_processor( _lowercase , ["""semantic"""] * len(_lowercase ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __a ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowercase , numpify=_lowercase ) for image in image_inputs: self.assertIsInstance(_lowercase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE__ = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_expected_values(_lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_expected_values(_lowercase , batched=_lowercase ) SCREAMING_SNAKE_CASE__ = image_processor( _lowercase , ["""semantic"""] * len(_lowercase ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __a ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowercase , torchify=_lowercase ) for image in image_inputs: self.assertIsInstance(_lowercase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ = image_processor(image_inputs[0] , ["""semantic"""] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_expected_values(_lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processing_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_expected_values(_lowercase , batched=_lowercase ) SCREAMING_SNAKE_CASE__ = image_processor( _lowercase , ["""semantic"""] * len(_lowercase ) , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) , ) def __a ( self : Tuple , _lowercase : Optional[int]=False , _lowercase : Any=False , _lowercase : List[str]="np" ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # prepare image and target SCREAMING_SNAKE_CASE__ = self.image_processing_tester.num_labels SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processing_tester , equal_resolution=_lowercase ) if with_segmentation_maps: SCREAMING_SNAKE_CASE__ = num_labels if is_instance_map: SCREAMING_SNAKE_CASE__ = list(range(_lowercase ) ) * 2 SCREAMING_SNAKE_CASE__ = dict(enumerate(_lowercase ) ) SCREAMING_SNAKE_CASE__ = [ np.random.randint(0 , high * 2 , (img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": SCREAMING_SNAKE_CASE__ = [Image.fromarray(_lowercase ) for annotation in annotations] SCREAMING_SNAKE_CASE__ = image_processor( _lowercase , ["""semantic"""] * len(_lowercase ) , _lowercase , return_tensors="""pt""" , instance_id_to_semantic_id=_lowercase , pad_and_return_pixel_mask=_lowercase , ) return inputs def __a ( self : str ): """simple docstring""" pass def __a ( self : Tuple ): """simple docstring""" def common(_lowercase : Optional[int]=False , _lowercase : Union[str, Any]=None ): SCREAMING_SNAKE_CASE__ = self.comm_get_image_processor_inputs( with_segmentation_maps=_lowercase , is_instance_map=_lowercase , segmentation_type=_lowercase ) SCREAMING_SNAKE_CASE__ = inputs["""mask_labels"""] SCREAMING_SNAKE_CASE__ = inputs["""class_labels"""] SCREAMING_SNAKE_CASE__ = inputs["""pixel_values"""] SCREAMING_SNAKE_CASE__ = inputs["""text_inputs"""] # check the batch_size for mask_label, class_label, text_input in zip(_lowercase , _lowercase , _lowercase ): self.assertEqual(mask_label.shape[0] , class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] , pixel_values.shape[2:] ) self.assertEqual(len(_lowercase ) , self.image_processing_tester.num_text ) common() common(is_instance_map=_lowercase ) common(is_instance_map=_lowercase , segmentation_type="""pil""" ) common(is_instance_map=_lowercase , segmentation_type="""pil""" ) def __a ( self : Any ): """simple docstring""" SCREAMING_SNAKE_CASE__ = np.zeros((20, 50) ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = binary_mask_to_rle(_lowercase ) self.assertEqual(len(_lowercase ) , 4 ) self.assertEqual(rle[0] , 21 ) self.assertEqual(rle[1] , 45 ) def __a ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_fake_oneformer_outputs() SCREAMING_SNAKE_CASE__ = fature_extractor.post_process_semantic_segmentation(_lowercase ) self.assertEqual(len(_lowercase ) , self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape , ( self.image_processing_tester.height, self.image_processing_tester.width, ) , ) SCREAMING_SNAKE_CASE__ = [(1, 4) for i in range(self.image_processing_tester.batch_size )] SCREAMING_SNAKE_CASE__ = fature_extractor.post_process_semantic_segmentation(_lowercase , target_sizes=_lowercase ) self.assertEqual(segmentation[0].shape , target_sizes[0] ) def __a ( self : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_fake_oneformer_outputs() SCREAMING_SNAKE_CASE__ = image_processor.post_process_instance_segmentation(_lowercase , threshold=0 ) self.assertTrue(len(_lowercase ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , _lowercase ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) ) def __a ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.image_processing_class( num_labels=self.image_processing_tester.num_classes , max_seq_length=77 , task_seq_length=77 , class_info_file="""ade20k_panoptic.json""" , num_text=self.image_processing_tester.num_text , repo_path="""shi-labs/oneformer_demo""" , ) SCREAMING_SNAKE_CASE__ = self.image_processing_tester.get_fake_oneformer_outputs() SCREAMING_SNAKE_CASE__ = image_processor.post_process_panoptic_segmentation(_lowercase , threshold=0 ) self.assertTrue(len(_lowercase ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("""segmentation""" in el ) self.assertTrue("""segments_info""" in el ) self.assertEqual(type(el["""segments_info"""] ) , _lowercase ) self.assertEqual( el["""segmentation"""].shape , (self.image_processing_tester.height, self.image_processing_tester.width) )
355
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification __lowerCamelCase : Tuple = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co __lowerCamelCase : Optional[Any] = '''main''' # Default branch name __lowerCamelCase : Optional[int] = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) __lowerCamelCase : Any = '''aaaaaaa''' # This commit does not exist, so we should 404. __lowerCamelCase : List[str] = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes __lowerCamelCase : List[Any] = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def __SCREAMING_SNAKE_CASE ( ) -> str: """simple docstring""" print("""Welcome!""" ) yield print("""Bye!""" ) @contextlib.contextmanager def __SCREAMING_SNAKE_CASE ( ) -> Any: """simple docstring""" print("""Bonjour!""" ) yield print("""Au revoir!""" ) class __snake_case ( unittest.TestCase ): def __a ( self : List[Any] ): """simple docstring""" assert transformers.__spec__ is not None assert importlib.util.find_spec("""transformers""" ) is not None class __snake_case ( unittest.TestCase ): @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __a ( self : List[str] , _lowercase : str ): """simple docstring""" with ContextManagers([] ): print("""Transformers are awesome!""" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , """Transformers are awesome!\n""" ) @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __a ( self : Optional[Any] , _lowercase : str ): """simple docstring""" with ContextManagers([context_en()] ): print("""Transformers are awesome!""" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , """Welcome!\nTransformers are awesome!\nBye!\n""" ) @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __a ( self : Tuple , _lowercase : Dict ): """simple docstring""" with ContextManagers([context_fr(), context_en()] ): print("""Transformers are awesome!""" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , """Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n""" ) @require_torch def __a ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(find_labels(_lowercase ) , ["""labels"""] ) self.assertEqual(find_labels(_lowercase ) , ["""labels""", """next_sentence_label"""] ) self.assertEqual(find_labels(_lowercase ) , ["""start_positions""", """end_positions"""] ) class __snake_case ( lowerCamelCase_ ): pass self.assertEqual(find_labels(_lowercase ) , ["""labels"""] ) @require_tf def __a ( self : Any ): """simple docstring""" self.assertEqual(find_labels(_lowercase ) , ["""labels"""] ) self.assertEqual(find_labels(_lowercase ) , ["""labels""", """next_sentence_label"""] ) self.assertEqual(find_labels(_lowercase ) , ["""start_positions""", """end_positions"""] ) class __snake_case ( lowerCamelCase_ ): pass self.assertEqual(find_labels(_lowercase ) , ["""labels"""] ) @require_flax def __a ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(find_labels(_lowercase ) , [] ) self.assertEqual(find_labels(_lowercase ) , [] ) self.assertEqual(find_labels(_lowercase ) , [] ) class __snake_case ( lowerCamelCase_ ): pass self.assertEqual(find_labels(_lowercase ) , [] )
204
0
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class A ( UpperCAmelCase_ ): __UpperCAmelCase : torch.FloatTensor class A ( nn.Module ): def __init__(self : Union[str, Any] , __UpperCAmelCase : int=3 , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : Optional[Any]=("DownEncoderBlock2D",) , __UpperCAmelCase : int=(6_4,) , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : Any=3_2 , __UpperCAmelCase : str="silu" , __UpperCAmelCase : Any=True , ) -> Dict: """simple docstring""" super().__init__() UpperCAmelCase__ = layers_per_block UpperCAmelCase__ = torch.nn.Convad( __UpperCAmelCase , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) UpperCAmelCase__ = None UpperCAmelCase__ = nn.ModuleList([] ) # down UpperCAmelCase__ = block_out_channels[0] for i, down_block_type in enumerate(__UpperCAmelCase ): UpperCAmelCase__ = output_channel UpperCAmelCase__ = block_out_channels[i] UpperCAmelCase__ = i == len(__UpperCAmelCase ) - 1 UpperCAmelCase__ = get_down_block( __UpperCAmelCase , num_layers=self.layers_per_block , in_channels=__UpperCAmelCase , out_channels=__UpperCAmelCase , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=__UpperCAmelCase , resnet_groups=__UpperCAmelCase , attention_head_dim=__UpperCAmelCase , temb_channels=__UpperCAmelCase , ) self.down_blocks.append(__UpperCAmelCase ) # mid UpperCAmelCase__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__UpperCAmelCase , output_scale_factor=1 , resnet_time_scale_shift="default" , attention_head_dim=block_out_channels[-1] , resnet_groups=__UpperCAmelCase , temb_channels=__UpperCAmelCase , ) # out UpperCAmelCase__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__UpperCAmelCase , eps=1E-6 ) UpperCAmelCase__ = nn.SiLU() UpperCAmelCase__ = 2 * out_channels if double_z else out_channels UpperCAmelCase__ = nn.Convad(block_out_channels[-1] , __UpperCAmelCase , 3 , padding=1 ) UpperCAmelCase__ = False def lowercase_ (self : List[Any] , __UpperCAmelCase : int ) -> str: """simple docstring""" UpperCAmelCase__ = x UpperCAmelCase__ = self.conv_in(__UpperCAmelCase ) if self.training and self.gradient_checkpointing: def create_custom_forward(__UpperCAmelCase : int ): def custom_forward(*__UpperCAmelCase : Optional[Any] ): return module(*__UpperCAmelCase ) return custom_forward # down if is_torch_version(">=" , "1.11.0" ): for down_block in self.down_blocks: UpperCAmelCase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__UpperCAmelCase ) , __UpperCAmelCase , use_reentrant=__UpperCAmelCase ) # middle UpperCAmelCase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __UpperCAmelCase , use_reentrant=__UpperCAmelCase ) else: for down_block in self.down_blocks: UpperCAmelCase__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase ) , __UpperCAmelCase ) # middle UpperCAmelCase__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __UpperCAmelCase ) else: # down for down_block in self.down_blocks: UpperCAmelCase__ = down_block(__UpperCAmelCase ) # middle UpperCAmelCase__ = self.mid_block(__UpperCAmelCase ) # post-process UpperCAmelCase__ = self.conv_norm_out(__UpperCAmelCase ) UpperCAmelCase__ = self.conv_act(__UpperCAmelCase ) UpperCAmelCase__ = self.conv_out(__UpperCAmelCase ) return sample class A ( nn.Module ): def __init__(self : List[Any] , __UpperCAmelCase : str=3 , __UpperCAmelCase : Union[str, Any]=3 , __UpperCAmelCase : Optional[int]=("UpDecoderBlock2D",) , __UpperCAmelCase : str=(6_4,) , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : Tuple=3_2 , __UpperCAmelCase : Any="silu" , __UpperCAmelCase : Any="group" , ) -> Dict: """simple docstring""" super().__init__() UpperCAmelCase__ = layers_per_block UpperCAmelCase__ = nn.Convad( __UpperCAmelCase , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) UpperCAmelCase__ = None UpperCAmelCase__ = nn.ModuleList([] ) UpperCAmelCase__ = in_channels if norm_type == "spatial" else None # mid UpperCAmelCase__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__UpperCAmelCase , output_scale_factor=1 , resnet_time_scale_shift="default" if norm_type == "group" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__UpperCAmelCase , temb_channels=__UpperCAmelCase , ) # up UpperCAmelCase__ = list(reversed(__UpperCAmelCase ) ) UpperCAmelCase__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(__UpperCAmelCase ): UpperCAmelCase__ = output_channel UpperCAmelCase__ = reversed_block_out_channels[i] UpperCAmelCase__ = i == len(__UpperCAmelCase ) - 1 UpperCAmelCase__ = get_up_block( __UpperCAmelCase , num_layers=self.layers_per_block + 1 , in_channels=__UpperCAmelCase , out_channels=__UpperCAmelCase , prev_output_channel=__UpperCAmelCase , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=__UpperCAmelCase , resnet_groups=__UpperCAmelCase , attention_head_dim=__UpperCAmelCase , temb_channels=__UpperCAmelCase , resnet_time_scale_shift=__UpperCAmelCase , ) self.up_blocks.append(__UpperCAmelCase ) UpperCAmelCase__ = output_channel # out if norm_type == "spatial": UpperCAmelCase__ = SpatialNorm(block_out_channels[0] , __UpperCAmelCase ) else: UpperCAmelCase__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__UpperCAmelCase , eps=1E-6 ) UpperCAmelCase__ = nn.SiLU() UpperCAmelCase__ = nn.Convad(block_out_channels[0] , __UpperCAmelCase , 3 , padding=1 ) UpperCAmelCase__ = False def lowercase_ (self : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict=None ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = z UpperCAmelCase__ = self.conv_in(__UpperCAmelCase ) UpperCAmelCase__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__UpperCAmelCase : str ): def custom_forward(*__UpperCAmelCase : List[str] ): return module(*__UpperCAmelCase ) return custom_forward if is_torch_version(">=" , "1.11.0" ): # middle UpperCAmelCase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __UpperCAmelCase , __UpperCAmelCase , use_reentrant=__UpperCAmelCase ) UpperCAmelCase__ = sample.to(__UpperCAmelCase ) # up for up_block in self.up_blocks: UpperCAmelCase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__UpperCAmelCase ) , __UpperCAmelCase , __UpperCAmelCase , use_reentrant=__UpperCAmelCase ) else: # middle UpperCAmelCase__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase__ = sample.to(__UpperCAmelCase ) # up for up_block in self.up_blocks: UpperCAmelCase__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase ) , __UpperCAmelCase , __UpperCAmelCase ) else: # middle UpperCAmelCase__ = self.mid_block(__UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase__ = sample.to(__UpperCAmelCase ) # up for up_block in self.up_blocks: UpperCAmelCase__ = up_block(__UpperCAmelCase , __UpperCAmelCase ) # post-process if latent_embeds is None: UpperCAmelCase__ = self.conv_norm_out(__UpperCAmelCase ) else: UpperCAmelCase__ = self.conv_norm_out(__UpperCAmelCase , __UpperCAmelCase ) UpperCAmelCase__ = self.conv_act(__UpperCAmelCase ) UpperCAmelCase__ = self.conv_out(__UpperCAmelCase ) return sample class A ( nn.Module ): def __init__(self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Union[str, Any]="random" , __UpperCAmelCase : Dict=False , __UpperCAmelCase : Union[str, Any]=True ) -> Dict: """simple docstring""" super().__init__() UpperCAmelCase__ = n_e UpperCAmelCase__ = vq_embed_dim UpperCAmelCase__ = beta UpperCAmelCase__ = legacy UpperCAmelCase__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) UpperCAmelCase__ = remap if self.remap is not None: self.register_buffer("used" , torch.tensor(np.load(self.remap ) ) ) UpperCAmelCase__ = self.used.shape[0] UpperCAmelCase__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": UpperCAmelCase__ = self.re_embed UpperCAmelCase__ = self.re_embed + 1 print( f"""Remapping {self.n_e} indices to {self.re_embed} indices. """ f"""Using {self.unknown_index} for unknown indices.""" ) else: UpperCAmelCase__ = n_e UpperCAmelCase__ = sane_index_shape def lowercase_ (self : str , __UpperCAmelCase : str ) -> List[str]: """simple docstring""" UpperCAmelCase__ = inds.shape assert len(__UpperCAmelCase ) > 1 UpperCAmelCase__ = inds.reshape(ishape[0] , -1 ) UpperCAmelCase__ = self.used.to(__UpperCAmelCase ) UpperCAmelCase__ = (inds[:, :, None] == used[None, None, ...]).long() UpperCAmelCase__ = match.argmax(-1 ) UpperCAmelCase__ = match.sum(2 ) < 1 if self.unknown_index == "random": UpperCAmelCase__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: UpperCAmelCase__ = self.unknown_index return new.reshape(__UpperCAmelCase ) def lowercase_ (self : Tuple , __UpperCAmelCase : Optional[int] ) -> Dict: """simple docstring""" UpperCAmelCase__ = inds.shape assert len(__UpperCAmelCase ) > 1 UpperCAmelCase__ = inds.reshape(ishape[0] , -1 ) UpperCAmelCase__ = self.used.to(__UpperCAmelCase ) if self.re_embed > self.used.shape[0]: # extra token UpperCAmelCase__ = 0 # simply set to zero UpperCAmelCase__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __UpperCAmelCase ) return back.reshape(__UpperCAmelCase ) def lowercase_ (self : Optional[Any] , __UpperCAmelCase : Dict ) -> List[str]: """simple docstring""" UpperCAmelCase__ = z.permute(0 , 2 , 3 , 1 ).contiguous() UpperCAmelCase__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z UpperCAmelCase__ = torch.argmin(torch.cdist(__UpperCAmelCase , self.embedding.weight ) , dim=1 ) UpperCAmelCase__ = self.embedding(__UpperCAmelCase ).view(z.shape ) UpperCAmelCase__ = None UpperCAmelCase__ = None # compute loss for embedding if not self.legacy: UpperCAmelCase__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: UpperCAmelCase__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients UpperCAmelCase__ = z + (z_q - z).detach() # reshape back to match original input shape UpperCAmelCase__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: UpperCAmelCase__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis UpperCAmelCase__ = self.remap_to_used(__UpperCAmelCase ) UpperCAmelCase__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: UpperCAmelCase__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def lowercase_ (self : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] ) -> Any: """simple docstring""" if self.remap is not None: UpperCAmelCase__ = indices.reshape(shape[0] , -1 ) # add batch axis UpperCAmelCase__ = self.unmap_to_all(__UpperCAmelCase ) UpperCAmelCase__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors UpperCAmelCase__ = self.embedding(__UpperCAmelCase ) if shape is not None: UpperCAmelCase__ = z_q.view(__UpperCAmelCase ) # reshape back to match original input shape UpperCAmelCase__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class A ( UpperCAmelCase_ ): def __init__(self : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : str=False ) -> Tuple: """simple docstring""" UpperCAmelCase__ = parameters UpperCAmelCase__ , UpperCAmelCase__ = torch.chunk(__UpperCAmelCase , 2 , dim=1 ) UpperCAmelCase__ = torch.clamp(self.logvar , -30.0 , 20.0 ) UpperCAmelCase__ = deterministic UpperCAmelCase__ = torch.exp(0.5 * self.logvar ) UpperCAmelCase__ = torch.exp(self.logvar ) if self.deterministic: UpperCAmelCase__ = UpperCAmelCase__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" UpperCAmelCase__ = randn_tensor( self.mean.shape , generator=__UpperCAmelCase , device=self.parameters.device , dtype=self.parameters.dtype ) UpperCAmelCase__ = self.mean + self.std * sample return x def lowercase_ (self : str , __UpperCAmelCase : int=None ) -> Any: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def lowercase_ (self : Dict , __UpperCAmelCase : Tuple , __UpperCAmelCase : Any=[1, 2, 3] ) -> Dict: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) UpperCAmelCase__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__UpperCAmelCase ) def lowercase_ (self : Tuple ) -> Optional[Any]: """simple docstring""" return self.mean
65
def lowerCAmelCase_ ( __A, __A ) -> float: '''simple docstring''' def get_matched_characters(__A, __A ) -> str: UpperCAmelCase__ = [] UpperCAmelCase__ = min(len(_stra ), len(_stra ) ) // 2 for i, l in enumerate(_stra ): UpperCAmelCase__ = int(max(0, i - limit ) ) UpperCAmelCase__ = int(min(i + limit + 1, len(_stra ) ) ) if l in _stra[left:right]: matched.append(__A ) UpperCAmelCase__ = f"""{_stra[0:_stra.index(__A )]} {_stra[_stra.index(__A ) + 1:]}""" return "".join(__A ) # matching characters UpperCAmelCase__ = get_matched_characters(__A, __A ) UpperCAmelCase__ = get_matched_characters(__A, __A ) UpperCAmelCase__ = len(__A ) # transposition UpperCAmelCase__ = ( len([(ca, ca) for ca, ca in zip(__A, __A ) if ca != ca] ) // 2 ) if not match_count: UpperCAmelCase__ = 0.0 else: UpperCAmelCase__ = ( 1 / 3 * ( match_count / len(__A ) + match_count / len(__A ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters UpperCAmelCase__ = 0 for ca, ca in zip(stra[:4], stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
65
1
"""simple docstring""" import math import os import sys def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : Union[str, Any] = """""" try: with open(snake_case_ ,"""rb""" ) as binary_file: UpperCamelCase : Any = binary_file.read() for dat in data: UpperCamelCase : int = f'{dat:08b}' result += curr_byte return result except OSError: print("""File not accessible""" ) sys.exit() def A_ ( snake_case_ : dict[str, str] ,snake_case_ : str ,snake_case_ : int ,snake_case_ : str ): '''simple docstring''' lexicon.pop(snake_case_ ) UpperCamelCase : Union[str, Any] = last_match_id if math.loga(snake_case_ ).is_integer(): for curr_key in lexicon: UpperCamelCase : Any = """0""" + lexicon[curr_key] UpperCamelCase : int = bin(snake_case_ )[2:] def A_ ( snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = {"""0""": """0""", """1""": """1"""} UpperCamelCase : Dict = """""", """""" UpperCamelCase : Optional[int] = len(snake_case_ ) for i in range(len(snake_case_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue UpperCamelCase : Tuple = lexicon[curr_string] result += last_match_id add_key_to_lexicon(snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ) index += 1 UpperCamelCase : Any = """""" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": UpperCamelCase : Dict = lexicon[curr_string] result += last_match_id return result def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : str = os.path.getsize(snake_case_ ) UpperCamelCase : Union[str, Any] = bin(snake_case_ )[2:] UpperCamelCase : List[str] = len(snake_case_ ) return "0" * (length_length - 1) + file_length_binary + compressed def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : int = 8 try: with open(snake_case_ ,"""wb""" ) as opened_file: UpperCamelCase : Dict = [ to_write[i : i + byte_length] for i in range(0 ,len(snake_case_ ) ,snake_case_ ) ] 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: opened_file.write(int(snake_case_ ,2 ).to_bytes(1 ,byteorder="""big""" ) ) except OSError: print("""File not accessible""" ) sys.exit() def A_ ( snake_case_ : str ,snake_case_ : str ): '''simple docstring''' UpperCamelCase : List[str] = read_file_binary(snake_case_ ) UpperCamelCase : Optional[int] = compress_data(snake_case_ ) UpperCamelCase : Any = add_file_length(snake_case_ ,snake_case_ ) write_file_binary(snake_case_ ,snake_case_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
360
"""simple docstring""" from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class lowerCamelCase ( nn.Module ): def __init__( self , SCREAMING_SNAKE_CASE_ = 16 , SCREAMING_SNAKE_CASE_ = 88 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "geglu" , SCREAMING_SNAKE_CASE_ = None , ): super().__init__() UpperCamelCase : int = nn.ModuleList( [ TransformeraDModel( num_attention_heads=SCREAMING_SNAKE_CASE_ , attention_head_dim=SCREAMING_SNAKE_CASE_ , in_channels=SCREAMING_SNAKE_CASE_ , num_layers=SCREAMING_SNAKE_CASE_ , dropout=SCREAMING_SNAKE_CASE_ , norm_num_groups=SCREAMING_SNAKE_CASE_ , cross_attention_dim=SCREAMING_SNAKE_CASE_ , attention_bias=SCREAMING_SNAKE_CASE_ , sample_size=SCREAMING_SNAKE_CASE_ , num_vector_embeds=SCREAMING_SNAKE_CASE_ , activation_fn=SCREAMING_SNAKE_CASE_ , num_embeds_ada_norm=SCREAMING_SNAKE_CASE_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCamelCase : Optional[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCamelCase : List[Any] = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCamelCase : int = [1, 0] def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_ = True , ): UpperCamelCase : Dict = hidden_states UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCamelCase : Optional[int] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCamelCase : str = self.transformer_index_for_condition[i] UpperCamelCase : Any = self.transformers[transformer_index]( SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , cross_attention_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCamelCase : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCamelCase : List[str] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=SCREAMING_SNAKE_CASE_ )
27
0
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase ( UpperCamelCase__ ): def __init__( self :Dict , lowercase_ :VQModel , lowercase_ :UNetaDModel , lowercase_ :DDIMScheduler )-> List[Any]: super().__init__() self.register_modules(vqvae=lowercase_ , unet=lowercase_ , scheduler=lowercase_ ) @torch.no_grad() def __call__( self :str , lowercase_ :int = 1 , lowercase_ :Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowercase_ :float = 0.0 , lowercase_ :int = 50 , lowercase_ :Optional[str] = "pil" , lowercase_ :bool = True , **lowercase_ :Dict , )-> Union[Tuple, ImagePipelineOutput]: A__ = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=lowercase_ , ) A__ = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler A__ = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(lowercase_ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature A__ = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) A__ = {} if accepts_eta: A__ = eta for t in self.progress_bar(self.scheduler.timesteps ): A__ = self.scheduler.scale_model_input(lowercase_ , lowercase_ ) # predict the noise residual A__ = self.unet(lowercase_ , lowercase_ ).sample # compute the previous noisy sample x_t -> x_t-1 A__ = self.scheduler.step(lowercase_ , lowercase_ , lowercase_ , **lowercase_ ).prev_sample # decode the image latents with the VAE A__ = self.vqvae.decode(lowercase_ ).sample A__ = (image / 2 + 0.5).clamp(0 , 1 ) A__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": A__ = self.numpy_to_pil(lowercase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase_ )
237
'''simple docstring''' import math import time from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class UpperCAmelCase ( UpperCamelCase__ ): def __init__( self :Optional[Any] , *lowercase_ :int , lowercase_ :Any=None , lowercase_ :List[str]=None , **lowercase_ :Any )-> Any: super().__init__(*lowercase_ , **lowercase_ ) A__ = eval_examples A__ = post_process_function def UpperCAmelCase_ ( self :str , lowercase_ :str=None , lowercase_ :Optional[int]=None , lowercase_ :Optional[int]=None , lowercase_ :str = "eval" )-> Union[str, Any]: A__ = self.eval_dataset if eval_dataset is None else eval_dataset A__ = self.get_eval_dataloader(lowercase_ ) A__ = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. A__ = self.compute_metrics A__ = None A__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop A__ = time.time() try: A__ = eval_loop( lowercase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=lowercase_ , metric_key_prefix=lowercase_ , ) finally: A__ = compute_metrics A__ = self.args.eval_batch_size * self.args.world_size if F"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[F"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( lowercase_ , lowercase_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default A__ = self.post_process_function(lowercase_ , lowercase_ , output.predictions ) A__ = self.compute_metrics(lowercase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"{metric_key_prefix}_" ): A__ = metrics.pop(lowercase_ ) metrics.update(output.metrics ) else: A__ = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(lowercase_ ) 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() ) A__ = self.callback_handler.on_evaluate(self.args , self.state , self.control , lowercase_ ) return metrics def UpperCAmelCase_ ( self :List[str] , lowercase_ :List[Any] , lowercase_ :str , lowercase_ :Any=None , lowercase_ :str = "test" )-> List[Any]: A__ = self.get_test_dataloader(lowercase_ ) # Temporarily disable metric computation, we will do it in the loop here. A__ = self.compute_metrics A__ = None A__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop A__ = time.time() try: A__ = eval_loop( lowercase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=lowercase_ , metric_key_prefix=lowercase_ , ) finally: A__ = compute_metrics A__ = self.args.eval_batch_size * self.args.world_size if F"{metric_key_prefix}_jit_compilation_time" in output.metrics: start_time += output.metrics[F"{metric_key_prefix}_jit_compilation_time"] output.metrics.update( speed_metrics( lowercase_ , lowercase_ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output A__ = self.post_process_function(lowercase_ , lowercase_ , output.predictions , "predict" ) A__ = self.compute_metrics(lowercase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F"{metric_key_prefix}_" ): A__ = metrics.pop(lowercase_ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=lowercase_ )
237
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json""" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowercase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = '''roformer''' def __init__( self : str , _UpperCAmelCase : str=50000 , _UpperCAmelCase : Any=None , _UpperCAmelCase : Dict=768 , _UpperCAmelCase : Optional[int]=12 , _UpperCAmelCase : str=12 , _UpperCAmelCase : Optional[Any]=3072 , _UpperCAmelCase : Union[str, Any]="gelu" , _UpperCAmelCase : Any=0.1 , _UpperCAmelCase : int=0.1 , _UpperCAmelCase : Optional[Any]=1536 , _UpperCAmelCase : str=2 , _UpperCAmelCase : Any=0.02 , _UpperCAmelCase : int=1e-12 , _UpperCAmelCase : List[str]=0 , _UpperCAmelCase : Any=False , _UpperCAmelCase : Tuple=True , **_UpperCAmelCase : str , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=_UpperCAmelCase , **_UpperCAmelCase ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size if embedding_size is None else embedding_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = hidden_act UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = type_vocab_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = rotary_value UpperCAmelCase_ = use_cache class lowercase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def lowercase__ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
354
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py lowerCamelCase = """src/diffusers""" lowerCamelCase = """.""" # This is to make sure the diffusers module imported is the one in the repo. lowerCamelCase = importlib.util.spec_from_file_location( """diffusers""", os.path.join(DIFFUSERS_PATH, """__init__.py"""), submodule_search_locations=[DIFFUSERS_PATH], ) lowerCamelCase = spec.loader.load_module() def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): return line.startswith(lowerCAmelCase__ ) or len(lowerCAmelCase__ ) <= 1 or re.search(r"^\s*\)(\s*->.*:|:)\s*$" , lowerCAmelCase__ ) is not None def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = object_name.split("." ) UpperCAmelCase_ = 0 # First let's find the module where our object lives. UpperCAmelCase_ = parts[i] while i < len(lowerCAmelCase__ ) and not os.path.isfile(os.path.join(lowerCAmelCase__ , f"""{module}.py""" ) ): i += 1 if i < len(lowerCAmelCase__ ): UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , parts[i] ) if i >= len(lowerCAmelCase__ ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(lowerCAmelCase__ , f"""{module}.py""" ) , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCAmelCase_ = f.readlines() # Now let's find the class / func in the code! UpperCAmelCase_ = "" UpperCAmelCase_ = 0 for name in parts[i + 1 :]: while ( line_index < len(lowerCAmelCase__ ) and re.search(rf"""^{indent}(class|def)\s+{name}(\(|\:)""" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(lowerCAmelCase__ ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). UpperCAmelCase_ = line_index while line_index < len(lowerCAmelCase__ ) and _should_continue(lines[line_index] , lowerCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCAmelCase_ = lines[start_index:line_index] return "".join(lowerCAmelCase__ ) lowerCamelCase = re.compile(r"""^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)""") lowerCamelCase = re.compile(r"""^\s*(\S+)->(\S+)(\s+.*|$)""") lowerCamelCase = re.compile(r"""<FILL\s+[^>]*>""") def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = code.split("\n" ) UpperCAmelCase_ = 0 while idx < len(lowerCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(lowerCAmelCase__ ): return re.search(r"^(\s*)\S" , lines[idx] ).groups()[0] return "" def a__ ( lowerCAmelCase__ ): UpperCAmelCase_ = len(get_indent(lowerCAmelCase__ ) ) > 0 if has_indent: UpperCAmelCase_ = f"""class Bla:\n{code}""" UpperCAmelCase_ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=lowerCAmelCase__ ) UpperCAmelCase_ = black.format_str(lowerCAmelCase__ , mode=lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = style_docstrings_in_code(lowerCAmelCase__ ) return result[len("class Bla:\n" ) :] if has_indent else result def a__ ( lowerCAmelCase__ , lowerCAmelCase__=False ): with open(lowerCAmelCase__ , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = [] UpperCAmelCase_ = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(lowerCAmelCase__ ): UpperCAmelCase_ = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = search.groups() UpperCAmelCase_ = find_code_in_diffusers(lowerCAmelCase__ ) UpperCAmelCase_ = get_indent(lowerCAmelCase__ ) UpperCAmelCase_ = line_index + 1 if indent == theoretical_indent else line_index + 2 UpperCAmelCase_ = theoretical_indent UpperCAmelCase_ = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. UpperCAmelCase_ = True while line_index < len(lowerCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(lowerCAmelCase__ ): break UpperCAmelCase_ = lines[line_index] UpperCAmelCase_ = _should_continue(lowerCAmelCase__ , lowerCAmelCase__ ) and re.search(f"""^{indent}# End copy""" , lowerCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 UpperCAmelCase_ = lines[start_index:line_index] UpperCAmelCase_ = "".join(lowerCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies UpperCAmelCase_ = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(lowerCAmelCase__ ) is None] UpperCAmelCase_ = "\n".join(lowerCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(lowerCAmelCase__ ) > 0: UpperCAmelCase_ = replace_pattern.replace("with" , "" ).split("," ) UpperCAmelCase_ = [_re_replace_pattern.search(lowerCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = pattern.groups() UpperCAmelCase_ = re.sub(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if option.strip() == "all-casing": UpperCAmelCase_ = re.sub(obja.lower() , obja.lower() , lowerCAmelCase__ ) UpperCAmelCase_ = re.sub(obja.upper() , obja.upper() , lowerCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line UpperCAmelCase_ = blackify(lines[start_index - 1] + theoretical_code ) UpperCAmelCase_ = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: UpperCAmelCase_ = lines[:start_index] + [theoretical_code] + lines[line_index:] UpperCAmelCase_ = start_index + 1 if overwrite and len(lowerCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(lowerCAmelCase__ ) return diffs def a__ ( lowerCAmelCase__ = False ): UpperCAmelCase_ = glob.glob(os.path.join(lowerCAmelCase__ , "**/*.py" ) , recursive=lowerCAmelCase__ ) UpperCAmelCase_ = [] for filename in all_files: UpperCAmelCase_ = is_copy_consistent(lowerCAmelCase__ , lowerCAmelCase__ ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(lowerCAmelCase__ ) > 0: UpperCAmelCase_ = "\n".join(lowerCAmelCase__ ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") lowerCamelCase = parser.parse_args() check_copies(args.fix_and_overwrite)
241
0
lowercase__ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase__ : Tuple = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase__ : str = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def A_ ( snake_case : int , snake_case : int , snake_case : int ) -> str: '''simple docstring''' assert len(str(snake_case ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __UpperCamelCase = year // 100 __UpperCamelCase = (5 * (century % 4) + 2) % 7 __UpperCamelCase = year % 100 __UpperCamelCase = centurian % 12 __UpperCamelCase = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __UpperCamelCase = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __UpperCamelCase = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
328
from math import factorial def A_ ( snake_case : int = 100 ) -> int: '''simple docstring''' return sum(int(snake_case ) for x in str(factorial(snake_case ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
328
1
UpperCAmelCase_ : Optional[Any] = {'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []} UpperCAmelCase_ : Tuple = ['''a''', '''b''', '''c''', '''d''', '''e'''] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : List[str] ) -> List[Any]: """simple docstring""" UpperCamelCase :Any = start # add current to visited visited.append(__magic_name__ ) UpperCamelCase :Optional[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: UpperCamelCase :Optional[Any] = topological_sort(__magic_name__ , __magic_name__ , __magic_name__ ) # if all neighbors visited add current to sort sort.append(__magic_name__ ) # if all vertices haven't been visited select a new one to visit if len(__magic_name__ ) != len(__magic_name__ ): for vertice in vertices: if vertice not in visited: UpperCamelCase :List[str] = topological_sort(__magic_name__ , __magic_name__ , __magic_name__ ) # return sort return sort if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = topological_sort('''a''', [], []) print(sort)
62
from math import pi def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int , __magic_name__ : int ) -> float: """simple docstring""" return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
62
1
from graphs.minimum_spanning_tree_kruskal import kruskal def _A ( ) -> int: """simple docstring""" __UpperCamelCase = 9 __UpperCamelCase = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] __UpperCamelCase = kruskal(__snake_case , __snake_case ) __UpperCamelCase = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(__snake_case ) == sorted(__snake_case )
310
'''simple docstring''' import requests from bsa import BeautifulSoup def __lowerCamelCase ( __snake_case : str, __snake_case : dict ) -> str: """simple docstring""" A__ : Optional[Any] =BeautifulSoup(requests.get(__snake_case, params=__snake_case ).content, """html.parser""" ) A__ : List[str] =soup.find("""div""", attrs={"""class""": """gs_ri"""} ) A__ : Tuple =div.find("""div""", attrs={"""class""": """gs_fl"""} ).find_all("""a""" ) return anchors[2].get_text() if __name__ == "__main__": __snake_case : Optional[Any] = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 30, 'pages': '3979-3990', 'year': 2018, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
134
0
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase : """simple docstring""" def __init__( self ,UpperCAmelCase_ ,UpperCAmelCase_=3 ,UpperCAmelCase_=32 ,UpperCAmelCase_=3 ,UpperCAmelCase_=10 ,UpperCAmelCase_=[10, 20, 30, 40] ,UpperCAmelCase_=[1, 1, 2, 1] ,UpperCAmelCase_=True ,UpperCAmelCase_=True ,UpperCAmelCase_="relu" ,UpperCAmelCase_=3 ,UpperCAmelCase_=None ,): _lowercase : List[str] = parent _lowercase : str = batch_size _lowercase : Tuple = image_size _lowercase : Dict = num_channels _lowercase : List[str] = embeddings_size _lowercase : str = hidden_sizes _lowercase : List[Any] = depths _lowercase : Optional[Any] = is_training _lowercase : int = use_labels _lowercase : List[Any] = hidden_act _lowercase : Optional[Any] = num_labels _lowercase : str = scope _lowercase : Tuple = len(UpperCAmelCase_ ) def lowerCamelCase__ ( self ): _lowercase : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowercase : List[Any] = None if self.use_labels: _lowercase : Dict = ids_tensor([self.batch_size] ,self.num_labels ) _lowercase : List[Any] = self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self ): return RegNetConfig( num_channels=self.num_channels ,embeddings_size=self.embeddings_size ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,hidden_act=self.hidden_act ,num_labels=self.num_labels ,) def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ): _lowercase : Dict = TFRegNetModel(config=UpperCAmelCase_ ) _lowercase : Union[str, Any] = model(UpperCAmelCase_ ,training=UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def lowerCamelCase__ ( self ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ): _lowercase : Union[str, Any] = self.num_labels _lowercase : Optional[int] = TFRegNetForImageClassification(UpperCAmelCase_ ) _lowercase : Dict = model(UpperCAmelCase_ ,labels=UpperCAmelCase_ ,training=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self ): _lowercase : Optional[int] = self.prepare_config_and_inputs() _lowercase , _lowercase , _lowercase : Optional[int] = config_and_inputs _lowercase : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCamelCase ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () SCREAMING_SNAKE_CASE_ : List[Any] = ( {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ : Optional[Any] = False SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : Optional[int] = False SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : Any = False def lowerCamelCase__ ( self ): _lowercase : Dict = TFRegNetModelTester(self ) _lowercase : List[Any] = ConfigTester(self ,config_class=UpperCAmelCase_ ,has_text_modality=UpperCAmelCase_ ) def lowerCamelCase__ ( self ): return @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def lowerCamelCase__ ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 ,reason="""TF does not support backprop for grouped convolutions on CPU.""" ,) @slow def lowerCamelCase__ ( self ): super().test_keras_fit() @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def lowerCamelCase__ ( self ): pass def lowerCamelCase__ ( self ): _lowercase , _lowercase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : Optional[int] = model_class(UpperCAmelCase_ ) _lowercase : Optional[int] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : Optional[Any] = [*signature.parameters.keys()] _lowercase : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] ,UpperCAmelCase_ ) def lowerCamelCase__ ( self ): _lowercase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCamelCase__ ( self ): def check_hidden_states_output(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ): _lowercase : List[Any] = model_class(UpperCAmelCase_ ) _lowercase : Optional[Any] = model(**self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ) ,training=UpperCAmelCase_ ) _lowercase : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowercase : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) ,expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 2, self.model_tester.image_size // 2] ,) _lowercase , _lowercase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : Optional[int] = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _lowercase : List[Any] = layer_type _lowercase : List[str] = True check_hidden_states_output(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowercase : List[str] = True check_hidden_states_output(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) def lowerCamelCase__ ( self ): _lowercase , _lowercase : int = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_={} ): _lowercase : Dict = model(UpperCAmelCase_ ,return_dict=UpperCAmelCase_ ,**UpperCAmelCase_ ) _lowercase : Tuple = model(UpperCAmelCase_ ,return_dict=UpperCAmelCase_ ,**UpperCAmelCase_ ).to_tuple() def recursive_check(UpperCAmelCase_ ,UpperCAmelCase_ ): if isinstance(UpperCAmelCase_ ,(List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_ ,UpperCAmelCase_ ): recursive_check(UpperCAmelCase_ ,UpperCAmelCase_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(UpperCAmelCase_ ,UpperCAmelCase_ ) ) ,msg=( """Tuple and dict output are not equal. Difference:""" f""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}""" ) ,) recursive_check(UpperCAmelCase_ ,UpperCAmelCase_ ) for model_class in self.all_model_classes: _lowercase : Any = model_class(UpperCAmelCase_ ) _lowercase : int = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ) _lowercase : Any = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) _lowercase : Union[str, Any] = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ,return_labels=UpperCAmelCase_ ) _lowercase : Dict = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ,return_labels=UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) _lowercase : Union[str, Any] = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ) _lowercase : Any = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,{"""output_hidden_states""": True} ) _lowercase : Tuple = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ,return_labels=UpperCAmelCase_ ) _lowercase : Dict = self._prepare_for_class(UpperCAmelCase_ ,UpperCAmelCase_ ,return_labels=UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,{"""output_hidden_states""": True} ) def lowerCamelCase__ ( self ): _lowercase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCamelCase__ ( self ): for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : List[str] = TFRegNetModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def __SCREAMING_SNAKE_CASE ( ): _lowercase : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCamelCase__ ( self ): return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCamelCase__ ( self ): _lowercase : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) _lowercase : int = self.default_image_processor _lowercase : List[str] = prepare_img() _lowercase : Union[str, Any] = image_processor(images=UpperCAmelCase_ ,return_tensors="""tf""" ) # forward pass _lowercase : List[str] = model(**UpperCAmelCase_ ,training=UpperCAmelCase_ ) # verify the logits _lowercase : Tuple = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,UpperCAmelCase_ ) _lowercase : Union[str, Any] = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] ,UpperCAmelCase_ ,atol=1E-4 )
336
"""simple docstring""" import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCAmelCase: Optional[Any] = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). UpperCAmelCase: Tuple = [0, 25, 50] UpperCAmelCase: List[Any] = [25, 50, 75] UpperCAmelCase: Optional[int] = fuzz.membership.trimf(X, abca) UpperCAmelCase: Any = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCAmelCase: List[Any] = np.ones(75) UpperCAmelCase: Any = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) UpperCAmelCase: str = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCAmelCase: Optional[int] = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCAmelCase: List[Any] = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCAmelCase: Optional[int] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCAmelCase: int = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCAmelCase: int = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCAmelCase: List[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCAmelCase: int = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("""Young""") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("""Middle aged""") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("""union""") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("""intersection""") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("""complement_a""") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("""difference a/b""") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("""alg_sum""") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("""alg_product""") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("""bdd_sum""") plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title("""bdd_difference""") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
336
1
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase = [ '''word_embeddings_layernorm.weight''', '''word_embeddings_layernorm.bias''', '''input_layernorm.weight''', '''input_layernorm.bias''', '''post_attention_layernorm.weight''', '''post_attention_layernorm.bias''', '''self_attention.dense.bias''', '''mlp.dense_4h_to_h.bias''', '''ln_f.weight''', '''ln_f.bias''', ] lowerCAmelCase = [ '''mlp.dense_4h_to_h.weight''', '''self_attention.dense.weight''', ] def _lowerCamelCase( lowercase__ , lowercase__ ) -> str: '''simple docstring''' __lowercase= { 'word_embeddings.weight': 'word_embeddings.weight', 'word_embeddings.norm.weight': 'word_embeddings_layernorm.weight', 'word_embeddings.norm.bias': 'word_embeddings_layernorm.bias', 'weight': 'ln_f.weight', 'bias': 'ln_f.bias', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks __lowercase= int(re.match(R'.*layer_(\d*).*' , lowercase__ )[1] ) layer_number -= 3 return F'h.{layer_number}.' + key def _lowerCamelCase( lowercase__ ) -> List[str]: '''simple docstring''' if dtype == torch.bool: return 1 / 8 __lowercase= re.search(R'[^\d](\d+)$' , str(lowercase__ ) ) if bit_search is None: raise ValueError(F'`dtype` is not a valid dtype: {dtype}.' ) __lowercase= int(bit_search.groups()[0] ) return bit_size // 8 def _lowerCamelCase( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) -> Optional[Any]: '''simple docstring''' if bloom_config_file == "": __lowercase= BloomConfig() else: __lowercase= BloomConfig.from_json_file(lowercase__ ) if shard_model: __lowercase= os.listdir(lowercase__ ) __lowercase= sorted(filter(lambda lowercase__ : s.startswith('layer' ) and "model_00" in s , lowercase__ ) ) __lowercase= {'weight_map': {}, 'metadata': {}} __lowercase= 0 __lowercase= None __lowercase= BloomConfig() for j, file in enumerate(lowercase__ ): print('Processing file: {}'.format(lowercase__ ) ) __lowercase= None for i in range(lowercase__ ): # load all TP files __lowercase= file.replace('model_00' , F'model_0{i}' ) __lowercase= torch.load(os.path.join(lowercase__ , lowercase__ ) , map_location='cpu' ) # Rename keys in the transformers names __lowercase= list(temp.keys() ) for key in keys: __lowercase= temp.pop(lowercase__ ) if tensors is None: __lowercase= temp else: for key in tensors.keys(): if any(key.endswith(lowercase__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel __lowercase= 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks __lowercase= torch.cat([tensors[key], temp[key]] , dim=lowercase__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(lowercase__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): __lowercase= tensors[key] / pretraining_tp torch.save( lowercase__ , os.path.join( lowercase__ , 'pytorch_model_{}-of-{}.bin'.format(str(j + 1 ).zfill(5 ) , str(len(lowercase__ ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): __lowercase= tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: __lowercase= 'pytorch_model_{}-of-{}.bin'.format( str(j + 1 ).zfill(5 ) , str(len(lowercase__ ) ).zfill(5 ) ) __lowercase= BloomConfig() __lowercase= pytorch_dump_folder_path + '/' + CONFIG_NAME __lowercase= total_size with open(lowercase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) with open(os.path.join(lowercase__ , WEIGHTS_NAME + '.index.json' ) , 'w' , encoding='utf-8' ) as f: __lowercase= json.dumps(lowercase__ , indent=2 , sort_keys=lowercase__ ) + '\n' f.write(lowercase__ ) else: __lowercase= BloomModel(lowercase__ ) __lowercase= os.listdir(lowercase__ ) __lowercase= sorted(filter(lambda lowercase__ : s.startswith('layer' ) and "model_00" in s , lowercase__ ) ) __lowercase= None for i, file in enumerate(lowercase__ ): __lowercase= None for i in range(lowercase__ ): # load all TP files __lowercase= file.replace('model_00' , F'model_0{i}' ) __lowercase= torch.load(os.path.join(lowercase__ , lowercase__ ) , map_location='cpu' ) # Rename keys in the transformers names __lowercase= list(temp.keys() ) for key in keys: __lowercase= temp.pop(lowercase__ ) if tensors is None: __lowercase= temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(lowercase__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel __lowercase= 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks __lowercase= torch.cat([tensors[key], temp[key]] , dim=lowercase__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(lowercase__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): __lowercase= tensors[key] / pretraining_tp __lowercase= model.load_state_dict(lowercase__ , strict=lowercase__ ) assert not other_keys.unexpected_keys, F'The keys {other_keys.unexpected_keys} are unexpected' if missing_keys is None: __lowercase= set(other_keys.missing_keys ) else: __lowercase= missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, F'The keys {missing_keys} are missing' # Save pytorch-model os.makedirs(lowercase__ , exist_ok=lowercase__ ) __lowercase= pytorch_dump_folder_path + '/' + WEIGHTS_NAME __lowercase= pytorch_dump_folder_path + '/' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}' ) if config.torch_dtype is not None: __lowercase= model.to(config.torch_dtype ) torch.save(model.state_dict() , lowercase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowercase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bloom_checkpoint_path''', default=None, type=str, required=True, help='''Path to the Megatron-LM checkpoint path.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--bloom_config_file''', default='''''', type=str, help=( '''An optional config json file corresponding to the pre-trained model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--shard_model''', action='''store_true''', help='''An optional setting to shard the output model \nThis enables sharding the converted checkpoint''', ) parser.add_argument( '''--pretraining_tp''', default=4, type=int, help='''Pretraining TP rank that has been used when training the model in Megatron-LM \n''', ) lowerCAmelCase = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
295
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase = '''▁''' lowerCAmelCase = {'''vocab_file''': '''spiece.model'''} lowerCAmelCase = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } lowerCAmelCase = { '''google/pegasus-xsum''': 5_1_2, } lowerCAmelCase = logging.get_logger(__name__) class A ( A_ ): UpperCamelCase_ : Union[str, Any] =VOCAB_FILES_NAMES UpperCamelCase_ : List[Any] =VOCAB_FILES_NAMES UpperCamelCase_ : int =PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : int =['''input_ids''', '''attention_mask'''] def __init__(self , lowerCAmelCase , lowerCAmelCase="<pad>" , lowerCAmelCase="</s>" , lowerCAmelCase="<unk>" , lowerCAmelCase="<mask_2>" , lowerCAmelCase="<mask_1>" , lowerCAmelCase=None , lowerCAmelCase=1_0_3 , lowerCAmelCase = None , **lowerCAmelCase , ): __lowercase= offset if additional_special_tokens is not None: if not isinstance(lowerCAmelCase , lowerCAmelCase ): raise TypeError( f'additional_special_tokens should be of type {type(lowerCAmelCase )}, but is' f' {type(lowerCAmelCase )}' ) __lowercase= ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'<unk_{i}>' for i in range(len(lowerCAmelCase ) , self.offset - 1 ) ] if len(set(lowerCAmelCase ) ) != len(lowerCAmelCase ): raise ValueError( 'Please make sure that the provided additional_special_tokens do not contain an incorrectly' f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) __lowercase= additional_special_tokens_extended else: __lowercase= [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'<unk_{i}>' for i in range(2 , self.offset )] __lowercase= {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowerCAmelCase , unk_token=lowerCAmelCase , mask_token=lowerCAmelCase , pad_token=lowerCAmelCase , mask_token_sent=lowerCAmelCase , offset=lowerCAmelCase , additional_special_tokens=lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase , ) __lowercase= mask_token_sent __lowercase= vocab_file __lowercase= spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase ) # add special tokens to encoder dict __lowercase= { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) __lowercase= {v: k for k, v in self.encoder.items()} @property def _A (self ): return len(self.sp_model ) + self.offset def _A (self ): __lowercase= {self.convert_ids_to_tokens(lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__(self ): __lowercase= self.__dict__.copy() __lowercase= None return state def __setstate__(self , lowerCAmelCase ): __lowercase= d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __lowercase= {} __lowercase= spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _A (self , lowerCAmelCase ): return self.sp_model.encode(lowerCAmelCase , out_type=lowerCAmelCase ) def _A (self , lowerCAmelCase ): if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] __lowercase= self.sp_model.piece_to_id(lowerCAmelCase ) return sp_id + self.offset def _A (self , lowerCAmelCase ): if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: __lowercase= self.sp_model.IdToPiece(index - self.offset ) return token def _A (self , lowerCAmelCase ): __lowercase= [] __lowercase= '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowerCAmelCase ) + token __lowercase= [] else: current_sub_tokens.append(lowerCAmelCase ) out_string += self.sp_model.decode(lowerCAmelCase ) return out_string.strip() def _A (self , lowerCAmelCase=False ): return 1 def _A (self , lowerCAmelCase ): __lowercase= set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def _A (self , lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = False ): if already_has_special_tokens: return self._special_token_mask(lowerCAmelCase ) elif token_ids_a is None: return self._special_token_mask(lowerCAmelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def _A (self , lowerCAmelCase , lowerCAmelCase=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _A (self , lowerCAmelCase , lowerCAmelCase = None ): if not os.path.isdir(lowerCAmelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __lowercase= os.path.join( lowerCAmelCase , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(lowerCAmelCase , 'wb' ) as fi: __lowercase= self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase ) return (out_vocab_file,)
295
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class lowercase ( UpperCamelCase__ ): _a = "char" _a = "bpe" _a = "wp" _snake_case = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "char_tokenizer"] _a = "ViTImageProcessor" _a = "MgpstrTokenizer" def __init__( self , _a=None , _a=None , **_a ) -> Union[str, Any]: _A : Dict = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCamelCase_ , ) _A : int = kwargs.pop("""feature_extractor""" ) _A : Optional[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) _A : List[str] = tokenizer _A : List[Any] = AutoTokenizer.from_pretrained("""gpt2""" ) _A : List[Any] = AutoTokenizer.from_pretrained("""bert-base-uncased""" ) super().__init__(lowerCamelCase_ , lowerCamelCase_ ) def __call__( self , _a=None , _a=None , _a=None , **_a ) -> int: if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: _A : Union[str, Any] = self.image_processor(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if text is not None: _A : List[Any] = self.char_tokenizer(lowerCamelCase_ , return_tensors=lowerCamelCase_ , **lowerCamelCase_ ) if text is None: return inputs elif images is None: return encodings else: _A : int = encodings["""input_ids"""] return inputs def a__ ( self , _a ) -> List[Any]: _A , _A , _A : Optional[int] = sequences _A : Dict = char_preds.size(0 ) _A , _A : Tuple = self._decode_helper(lowerCamelCase_ , """char""" ) _A , _A : Dict = self._decode_helper(lowerCamelCase_ , """bpe""" ) _A , _A : List[str] = self._decode_helper(lowerCamelCase_ , """wp""" ) _A : List[str] = [] _A : str = [] for i in range(lowerCamelCase_ ): _A : Optional[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] _A : int = [char_strs[i], bpe_strs[i], wp_strs[i]] _A : Dict = scores.index(max(lowerCamelCase_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) _A : Union[str, Any] = {} _A : int = final_strs _A : Union[str, Any] = final_scores _A : Optional[Any] = char_strs _A : Any = bpe_strs _A : List[Any] = wp_strs return out def a__ ( self , _a , _a ) -> List[str]: if format == DecodeType.CHARACTER: _A : Optional[int] = self.char_decode _A : Any = 1 _A : Optional[int] = """[s]""" elif format == DecodeType.BPE: _A : Optional[int] = self.bpe_decode _A : Any = 2 _A : str = """#""" elif format == DecodeType.WORDPIECE: _A : str = self.wp_decode _A : str = 102 _A : Dict = """[SEP]""" else: raise ValueError(F'''Format {format} is not supported.''' ) _A , _A : List[Any] = [], [] _A : Optional[Any] = pred_logits.size(0 ) _A : int = pred_logits.size(1 ) _A , _A : int = pred_logits.topk(1 , dim=-1 , largest=lowerCamelCase_ , sorted=lowerCamelCase_ ) _A : Union[str, Any] = preds_index.view(-1 , lowerCamelCase_ )[:, 1:] _A : Optional[Any] = decoder(lowerCamelCase_ ) _A , _A : List[Any] = torch.nn.functional.softmax(lowerCamelCase_ , dim=2 ).max(dim=2 ) _A : str = preds_max_prob[:, 1:] for index in range(lowerCamelCase_ ): _A : List[Any] = preds_str[index].find(lowerCamelCase_ ) _A : List[str] = preds_str[index][:pred_eos] _A : int = preds_index[index].cpu().tolist() _A : Optional[Any] = pred_index.index(lowerCamelCase_ ) if eos_token in pred_index else -1 _A : Union[str, Any] = preds_max_prob[index][: pred_eos_index + 1] _A : str = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(lowerCamelCase_ ) conf_scores.append(lowerCamelCase_ ) return dec_strs, conf_scores def a__ ( self , _a ) -> Any: _A : str = [seq.replace(""" """ , """""" ) for seq in self.char_tokenizer.batch_decode(lowerCamelCase_ )] return decode_strs def a__ ( self , _a ) -> List[Any]: return self.bpe_tokenizer.batch_decode(lowerCamelCase_ ) def a__ ( self , _a ) -> List[Any]: _A : Optional[Any] = [seq.replace(""" """ , """""" ) for seq in self.wp_tokenizer.batch_decode(lowerCamelCase_ )] return decode_strs
355
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) _snake_case = logging.getLogger() def lowerCAmelCase_ ( ): _A : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""-f""" ) _A : Optional[Any] = parser.parse_args() return args.f class lowercase ( UpperCamelCase__ ): def a__ ( self ) -> None: _A : List[Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(_a ) def a__ ( self , _a ) -> Dict: _A : Tuple = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , """run_glue_deebert.py""" ) with patch.object(_a , """argv""" , _a ): _A : Optional[Any] = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(_a , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ) -> Optional[int]: _A : Tuple = """ --model_type roberta --model_name_or_path roberta-base --task_name MRPC --do_train --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --max_seq_length 128 --per_gpu_eval_batch_size=1 --per_gpu_train_batch_size=8 --learning_rate 2e-4 --num_train_epochs 3 --overwrite_output_dir --seed 42 --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --save_steps 0 --overwrite_cache --eval_after_first_stage """.split() self.run_and_check(_a ) _A : Optional[Any] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --eval_each_highway --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a ) _A : List[str] = """ --model_type roberta --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --task_name MRPC --do_eval --do_lower_case --data_dir ./tests/fixtures/tests_samples/MRPC/ --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage --plot_data_dir ./examples/deebert/results/ --max_seq_length 128 --early_exit_entropy 0.1 --eval_highway --overwrite_cache --per_gpu_eval_batch_size=1 """.split() self.run_and_check(_a )
343
0
def lowerCAmelCase ( lowerCAmelCase_ )-> int: assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and number_of_steps > 0 ), f"""number_of_steps needs to be positive integer, your input {number_of_steps}""" if number_of_steps == 1: return 1 lowerCAmelCase_ , lowerCAmelCase_ : str = 1, 1 for _ in range(number_of_steps - 1 ): lowerCAmelCase_ , lowerCAmelCase_ : Union[str, Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
262
import inspect import unittest class snake_case__( unittest.TestCase ): '''simple docstring''' def lowercase_ ( self ) -> int: try: import diffusers # noqa: F401 except ImportError: assert False def lowercase_ ( self ) -> List[str]: import diffusers from diffusers.dependency_versions_table import deps lowerCAmelCase_ : Any = inspect.getmembers(__lowercase , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": lowerCAmelCase_ : Optional[int] = '''k-diffusion''' elif backend == "invisible_watermark": lowerCAmelCase_ : Dict = '''invisible-watermark''' assert backend in deps, f"""{backend} is not in the deps table!"""
262
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __A =logging.get_logger(__name__) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__=False ): lowerCamelCase_ = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token") ) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings") ) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias") ) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight') ) rename_keys.append((F'patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias', F'vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowerCamelCase_ = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ): for i in range(config.num_hidden_layers ): if base_model: lowerCamelCase_ = "" else: lowerCamelCase_ = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowerCamelCase_ = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) lowerCamelCase_ = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict lowerCamelCase_ = in_proj_weight[ : config.hidden_size, : ] lowerCamelCase_ = in_proj_bias[: config.hidden_size] lowerCamelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCamelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowerCamelCase_ = in_proj_weight[ -config.hidden_size :, : ] lowerCamelCase_ = in_proj_bias[-config.hidden_size :] def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(lowerCamelCase__ , lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = dct.pop(lowerCamelCase__ ) lowerCamelCase_ = val def lowerCamelCase_ ( ): lowerCamelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCamelCase_ = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw ) return im @torch.no_grad() def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ): lowerCamelCase_ = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=lowerCamelCase__ , ) lowerCamelCase_ = ViTHybridConfig(backbone_config=lowerCamelCase__ , image_size=3_8_4 , num_labels=1_0_0_0 ) lowerCamelCase_ = False # load original model from timm lowerCamelCase_ = timm.create_model(lowerCamelCase__ , pretrained=lowerCamelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowerCamelCase_ = timm_model.state_dict() if base_model: remove_classification_head_(lowerCamelCase__ ) lowerCamelCase_ = create_rename_keys(lowerCamelCase__ , lowerCamelCase__ ) for src, dest in rename_keys: rename_key(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) read_in_q_k_v(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_ = "huggingface/label-files" lowerCamelCase_ = "imagenet-1k-id2label.json" lowerCamelCase_ = json.load(open(hf_hub_download(lowerCamelCase__ , lowerCamelCase__ , repo_type="dataset" ) , "r" ) ) lowerCamelCase_ = {int(lowerCamelCase__ ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": lowerCamelCase_ = ViTHybridModel(lowerCamelCase__ ).eval() else: lowerCamelCase_ = ViTHybridForImageClassification(lowerCamelCase__ ).eval() model.load_state_dict(lowerCamelCase__ ) # create image processor lowerCamelCase_ = create_transform(**resolve_data_config({} , model=lowerCamelCase__ ) ) lowerCamelCase_ = transform.transforms lowerCamelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } lowerCamelCase_ = ViTHybridImageProcessor( do_resize=lowerCamelCase__ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowerCamelCase__ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=lowerCamelCase__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowerCamelCase_ = prepare_img() lowerCamelCase_ = transform(lowerCamelCase__ ).unsqueeze(0 ) lowerCamelCase_ = processor(lowerCamelCase__ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(lowerCamelCase__ , lowerCamelCase__ ) # verify logits with torch.no_grad(): lowerCamelCase_ = model(lowerCamelCase__ ) lowerCamelCase_ = outputs.logits print("Predicted class:" , logits.argmax(-1 ).item() ) if base_model: lowerCamelCase_ = timm_model.forward_features(lowerCamelCase__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowerCamelCase__ , outputs.pooler_output , atol=1e-3 ) else: lowerCamelCase_ = timm_model(lowerCamelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCamelCase__ , outputs.logits , atol=1e-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) print(F'Saving model {vit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCamelCase__ ) print(F'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(lowerCamelCase__ ) if push_to_hub: print(F'Pushing model and processor to the hub {vit_name}' ) model.push_to_hub(F'ybelkada/{vit_name}' ) processor.push_to_hub(F'ybelkada/{vit_name}' ) if __name__ == "__main__": __A =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--vit_name''', default='''vit_base_r50_s16_384''', type=str, help='''Name of the hybrid ViT timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to upload the model to the HuggingFace hub.''' ) __A =parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
47
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() __A =logging.get_logger(__name__) __A ={ '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''encoder.layer_norm_for_extract''': '''layer_norm_for_extract''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''label_embs_concat''': '''label_embeddings_concat''', '''mask_emb''': '''masked_spec_embed''', '''spk_proj''': '''speaker_proj''', } __A =[ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', '''label_embeddings_concat''', '''speaker_proj''', '''layer_norm_for_extract''', ] def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): for attribute in key.split("." ): lowerCamelCase_ = getattr(lowerCamelCase__ , lowerCamelCase__ ) if weight_type is not None: lowerCamelCase_ = getattr(lowerCamelCase__ , lowerCamelCase__ ).shape else: lowerCamelCase_ = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": lowerCamelCase_ = value elif weight_type == "weight_g": lowerCamelCase_ = value elif weight_type == "weight_v": lowerCamelCase_ = value elif weight_type == "bias": lowerCamelCase_ = value else: lowerCamelCase_ = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = [] lowerCamelCase_ = fairseq_model.state_dict() lowerCamelCase_ = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): lowerCamelCase_ = False if "conv_layers" in name: load_conv_layer( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , hf_model.config.feat_extract_norm == "group" , ) lowerCamelCase_ = True else: for key, mapped_key in MAPPING.items(): lowerCamelCase_ = "unispeech_sat." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: if "layer_norm_for_extract" in name and (".".join(name.split("." )[:-1] ) != key): # special case since naming is very similar continue lowerCamelCase_ = True if "*" in mapped_key: lowerCamelCase_ = name.split(lowerCamelCase__ )[0].split("." )[-2] lowerCamelCase_ = mapped_key.replace("*" , lowerCamelCase__ ) if "weight_g" in name: lowerCamelCase_ = "weight_g" elif "weight_v" in name: lowerCamelCase_ = "weight_v" elif "bias" in name: lowerCamelCase_ = "bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj lowerCamelCase_ = "weight" else: lowerCamelCase_ = None set_recursively(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) continue if not is_used: unused_weights.append(lowerCamelCase__ ) logger.warning(F'Unused weights: {unused_weights}' ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = full_name.split("conv_layers." )[-1] lowerCamelCase_ = name.split("." ) lowerCamelCase_ = int(items[0] ) lowerCamelCase_ = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) lowerCamelCase_ = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) lowerCamelCase_ = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.' ) lowerCamelCase_ = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) lowerCamelCase_ = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(lowerCamelCase__ ) @torch.no_grad() def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=True ): if config_path is not None: lowerCamelCase_ = UniSpeechSatConfig.from_pretrained(lowerCamelCase__ ) else: lowerCamelCase_ = UniSpeechSatConfig() lowerCamelCase_ = "" if is_finetuned: lowerCamelCase_ = UniSpeechSatForCTC(lowerCamelCase__ ) else: lowerCamelCase_ = UniSpeechSatForPreTraining(lowerCamelCase__ ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) lowerCamelCase_ = model[0].eval() recursively_load_weights(lowerCamelCase__ , lowerCamelCase__ ) hf_wavavec.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": __A =argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) __A =parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
47
1
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase : str = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class __UpperCAmelCase ( A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = PegasusTokenizer __lowerCAmelCase = PegasusTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True def A (self : Optional[Any] ): super().setUp() # We have a SentencePiece fixture for testing A = PegasusTokenizer(_lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A (self : str ): return PegasusTokenizer.from_pretrained("""google/pegasus-large""" ) def A (self : Optional[Any] , **_lowerCAmelCase : Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def A (self : Optional[int] , _lowerCAmelCase : Dict ): return ("This is a test", "This is a test") def A (self : Dict ): A = """</s>""" A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : List[Any] ): A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<pad>""" ) self.assertEqual(vocab_keys[1] , """</s>""" ) self.assertEqual(vocab_keys[-1] , """v""" ) self.assertEqual(len(_lowerCAmelCase ) , 1103 ) def A (self : Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def A (self : Optional[int] ): A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) A = self.tokenizer_class.from_pretrained(self.tmpdirname ) A = ( """Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important""" """ </s> <pad> <pad> <pad>""" ) A = rust_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] A = py_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def A (self : str ): A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word A = """<mask_1> To ensure a <mask_2> flow of bank resolutions.""" A = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] A = tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def A (self : Tuple ): A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 A = """To ensure a smooth flow of bank resolutions.""" A = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] A = tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def A (self : str ): A = ["""This is going to be way too long.""" * 150, """short example"""] A = ["""not super long but more than 5 tokens""", """tiny"""] A = self._large_tokenizer(_lowerCAmelCase , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors="""pt""" ) A = self._large_tokenizer( text_target=_lowerCAmelCase , max_length=5 , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCAmelCase ) == 2 # input_ids, attention_mask. @slow def A (self : Union[str, Any] ): # fmt: off A = {"""input_ids""": [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCAmelCase , model_name="""google/bigbird-pegasus-large-arxiv""" , revision="""ba85d0851d708441f91440d509690f1ab6353415""" , ) @require_sentencepiece @require_tokenizers class __UpperCAmelCase ( A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = PegasusTokenizer __lowerCAmelCase = PegasusTokenizerFast __lowerCAmelCase = True __lowerCAmelCase = True def A (self : Tuple ): super().setUp() # We have a SentencePiece fixture for testing A = PegasusTokenizer(_lowerCAmelCase , offset=0 , mask_token_sent=_lowerCAmelCase , mask_token="""[MASK]""" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A (self : int ): return PegasusTokenizer.from_pretrained("""google/bigbird-pegasus-large-arxiv""" ) def A (self : Optional[int] , **_lowerCAmelCase : List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def A (self : Optional[int] , _lowerCAmelCase : Union[str, Any] ): return ("This is a test", "This is a test") def A (self : Union[str, Any] ): A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) A = self.tokenizer_class.from_pretrained(self.tmpdirname ) A = ( """Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>""" """ <pad> <pad> <pad>""" ) A = rust_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] A = py_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) @require_torch def A (self : Optional[int] ): A = ["""This is going to be way too long.""" * 1000, """short example"""] A = ["""not super long but more than 5 tokens""", """tiny"""] A = self._large_tokenizer(_lowerCAmelCase , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors="""pt""" ) A = self._large_tokenizer( text_target=_lowerCAmelCase , max_length=5 , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCAmelCase ) == 2 # input_ids, attention_mask. def A (self : List[str] ): A = ( """This is an example string that is used to test the original TF implementation against the HF""" """ implementation""" ) A = self._large_tokenizer(_lowerCAmelCase ).input_ids self.assertListEqual( _lowerCAmelCase , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
258
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' __lowerCAmelCase = None class __UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' __lowerCAmelCase = PandasConfig def A (self : Tuple ): return datasets.DatasetInfo(features=self.config.features ) def A (self : Optional[int] , _lowerCAmelCase : List[Any] ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCAmelCase , (str, list, tuple) ): A = data_files if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A = [] for split_name, files in data_files.items(): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCAmelCase , gen_kwargs={"""files""": files} ) ) return splits def A (self : Dict , _lowerCAmelCase : pa.Table ): if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example A = table_cast(_lowerCAmelCase , self.config.features.arrow_schema ) return pa_table def A (self : List[Any] , _lowerCAmelCase : Optional[Any] ): for i, file in enumerate(itertools.chain.from_iterable(_lowerCAmelCase ) ): with open(_lowerCAmelCase , """rb""" ) as f: A = pa.Table.from_pandas(pd.read_pickle(_lowerCAmelCase ) ) yield i, self._cast_table(_lowerCAmelCase )
258
1
'''simple docstring''' import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def snake_case__ ( lowerCamelCase__ : str , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] ) -> int: # Initialise PyTorch model A_ : int = AlbertConfig.from_json_file(lowerCamelCase__ ) print(f'Building PyTorch model from configuration: {config}' ) A_ : List[Any] = AlbertForPreTraining(lowerCamelCase__ ) # Load weights from tf checkpoint load_tf_weights_in_albert(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Save pytorch-model print(f'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , lowerCamelCase__ ) if __name__ == "__main__": snake_case__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--albert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained ALBERT 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.""" ) snake_case__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
363
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case__ = logging.get_logger(__name__) snake_case__ = { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class UpperCamelCase_ (a__ ): """simple docstring""" _lowerCAmelCase = 'speech_to_text_2' _lowerCAmelCase = ['past_key_values'] _lowerCAmelCase = {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Optional[Any] , _lowerCamelCase : Optional[Any]=10000 , _lowerCamelCase : List[Any]=6 , _lowerCamelCase : int=2048 , _lowerCamelCase : Dict=4 , _lowerCamelCase : str=0.0 , _lowerCamelCase : int=True , _lowerCamelCase : int="relu" , _lowerCamelCase : Any=256 , _lowerCamelCase : List[Any]=0.1 , _lowerCamelCase : Tuple=0.0 , _lowerCamelCase : Union[str, Any]=0.0 , _lowerCamelCase : Optional[Any]=0.02 , _lowerCamelCase : int=2 , _lowerCamelCase : List[str]=True , _lowerCamelCase : str=1 , _lowerCamelCase : List[Any]=0 , _lowerCamelCase : Optional[int]=2 , _lowerCamelCase : Tuple=1024 , **_lowerCamelCase : int , ): """simple docstring""" A_ : Optional[int] = vocab_size A_ : Tuple = d_model A_ : List[str] = decoder_ffn_dim A_ : str = decoder_layers A_ : Any = decoder_attention_heads A_ : int = dropout A_ : str = attention_dropout A_ : Optional[int] = activation_dropout A_ : str = activation_function A_ : List[Any] = init_std A_ : Union[str, Any] = decoder_layerdrop A_ : Any = use_cache A_ : Optional[Any] = decoder_layers A_ : Optional[int] = scale_embedding # scale factor will be sqrt(d_model) if True A_ : Optional[Any] = max_target_positions super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , )
4
0
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class snake_case__ ( lowerCAmelCase_ ): """simple docstring""" def lowercase_ ( self : List[Any] ) ->str: snake_case__ : List[str] = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type, pa.intaa() ) def lowercase_ ( self : Dict ) ->str: with self.assertRaises(_snake_case ): snake_case__ : Optional[int] = pa.array(TypedSequence([1, 2, 3] ), type=pa.intaa() ) def lowercase_ ( self : List[Any] ) ->Dict: with self.assertRaises(_snake_case ): snake_case__ : Any = pa.array(TypedSequence([1, 2, 3], try_type=Value('bool' ), type=Value('int64' ) ) ) def lowercase_ ( self : int ) ->Optional[int]: snake_case__ : Union[str, Any] = pa.array(TypedSequence([1, 2, 3], type=Value('int32' ) ) ) self.assertEqual(arr.type, pa.intaa() ) def lowercase_ ( self : List[str] ) ->Optional[Any]: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): snake_case__ : int = pa.array(TypedSequence(['foo', 'bar'], type=Value('int64' ) ) ) def lowercase_ ( self : Tuple ) ->Any: snake_case__ : List[str] = pa.array(TypedSequence([1, 2, 3], try_type=Value('int32' ) ) ) self.assertEqual(arr.type, pa.intaa() ) def lowercase_ ( self : Optional[int] ) ->List[str]: snake_case__ : str = pa.array(TypedSequence(['foo', 'bar'], try_type=Value('int64' ) ) ) self.assertEqual(arr.type, pa.string() ) def lowercase_ ( self : str ) ->List[Any]: snake_case__ : Tuple = pa.array(TypedSequence([[[1, 2, 3]]], type=ArrayaD((1, 3), 'int64' ) ) ) self.assertEqual(arr.type, ArrayaDExtensionType((1, 3), 'int64' ) ) def lowercase_ ( self : Any ) ->List[Any]: with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): snake_case__ : Any = pa.array(TypedSequence(['foo', 'bar'], type=ArrayaD((1, 3), 'int64' ) ) ) def lowercase_ ( self : Union[str, Any] ) ->Tuple: snake_case__ : Optional[Any] = pa.array(TypedSequence([[[1, 2, 3]]], try_type=ArrayaD((1, 3), 'int64' ) ) ) self.assertEqual(arr.type, ArrayaDExtensionType((1, 3), 'int64' ) ) def lowercase_ ( self : int ) ->Union[str, Any]: snake_case__ : int = pa.array(TypedSequence(['foo', 'bar'], try_type=ArrayaD((1, 3), 'int64' ) ) ) self.assertEqual(arr.type, pa.string() ) @require_pil def lowercase_ ( self : Any ) ->Optional[int]: import PIL.Image snake_case__ : Optional[int] = PIL.Image.fromarray(np.arange(1_0, dtype=np.uinta ).reshape(2, 5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects', side_effect=_snake_case ) as mock_cast_to_python_objects: snake_case__ : Dict = pa.array(TypedSequence([{'path': None, 'bytes': b'image_bytes'}, pil_image], type=Image() ) ) snake_case__ , snake_case__ : int = mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting', _snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def lowercase_ (A : Dict , A : int ): snake_case__ : str = pa.BufferReader(A ) if isinstance(A , pa.Buffer ) else pa.memory_map(A ) snake_case__ : Optional[int] = pa.ipc.open_stream(A ) snake_case__ : pa.Table = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def lowercase_ (A : List[str] , A : List[str] ): snake_case__ : Optional[Any] = pa.BufferOutputStream() snake_case__ : Optional[int] = pa.schema(A ) if fields else None with ArrowWriter(stream=A , schema=A , writer_batch_size=A ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) snake_case__ , snake_case__ : Optional[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case__ : str = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(A , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def lowercase_ (): snake_case__ : int = pa.BufferOutputStream() snake_case__ : Optional[int] = Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=A , features=A ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) snake_case__ , snake_case__ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata snake_case__ : List[str] = pa.BufferReader(output.getvalue() ) snake_case__ : int = pa.ipc.open_stream(A ) snake_case__ : pa.Table = f.read_all() snake_case__ : List[Any] = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(A ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) def lowercase_ (A : int ): snake_case__ : str = pa.BufferOutputStream() with ArrowWriter( stream=A , writer_batch_size=A , hash_salt='split_name' , check_duplicates=A , ) as writer: with pytest.raises(A ): writer.write({'col_1': 'foo', 'col_2': 1} , key=[1, 2] ) snake_case__ , snake_case__ : List[Any] = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 1_0] ) def lowercase_ (A : Optional[int] ): snake_case__ : Optional[int] = pa.BufferOutputStream() with ArrowWriter( stream=A , writer_batch_size=A , hash_salt='split_name' , check_duplicates=A , ) as writer: with pytest.raises(A ): writer.write({'col_1': 'foo', 'col_2': 1} , key=1_0 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=1_0 ) snake_case__ , snake_case__ : int = writer.finalize() @pytest.mark.parametrize('writer_batch_size' , [None, 2, 1_0] ) def lowercase_ (A : List[Any] ): snake_case__ : Any = pa.BufferOutputStream() with ArrowWriter( stream=A , writer_batch_size=A , hash_salt='split_name' , check_duplicates=A , ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} , key=1 ) writer.write({'col_1': 'bar', 'col_2': 2} , key=2 ) snake_case__ , snake_case__ : List[str] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def lowercase_ (A : Dict , A : Any ): snake_case__ : Union[str, Any] = pa.BufferOutputStream() snake_case__ : Dict = pa.schema(A ) if fields else None with ArrowWriter(stream=A , schema=A , writer_batch_size=A ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) snake_case__ , snake_case__ : Optional[int] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case__ : Union[str, Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(A , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def lowercase_ (A : Tuple , A : str ): snake_case__ : List[str] = pa.BufferOutputStream() snake_case__ : int = pa.schema(A ) if fields else None with ArrowWriter(stream=A , schema=A , writer_batch_size=A ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) snake_case__ , snake_case__ : List[Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case__ : List[Any] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(A , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size' , [None, 1, 1_0] ) @pytest.mark.parametrize( 'fields' , [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def lowercase_ (A : List[str] , A : Union[str, Any] ): snake_case__ : List[Any] = pa.BufferOutputStream() snake_case__ : int = pa.schema(A ) if fields else None with ArrowWriter(stream=A , schema=A , writer_batch_size=A ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) snake_case__ , snake_case__ : int = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: snake_case__ : List[str] = {'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(A , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def lowercase_ (): with tempfile.TemporaryDirectory() as tmp_dir: snake_case__ : int = {'col_1': pa.string(), 'col_2': pa.intaa()} snake_case__ : Tuple = os.path.join(A , 'test.arrow' ) with ArrowWriter(path=A , schema=pa.schema(A ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) snake_case__ , snake_case__ : Dict = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(A , metadata=writer._schema.metadata ) _check_output(A , 1 ) def lowercase_ (A : Union[str, Any] ): if pa.types.is_list(A ): return get_base_dtype(arr_type.value_type ) else: return arr_type def lowercase_ (A : List[Any] , A : Union[str, Any] ): if isinstance(lst[0] , A ): change_first_primitive_element_in_list(lst[0] , A ) else: snake_case__ : Dict = value @pytest.mark.parametrize('optimized_int_type, expected_dtype' , [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def lowercase_ (A : Tuple , A : List[str] , A : List[Any] ): snake_case__ : Any = pa.array(TypedSequence(A , optimized_int_type=A ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype' , [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ] , ) @pytest.mark.parametrize('sequence' , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def lowercase_ (A : List[Any] , A : Union[str, Any] , A : str ): # in range snake_case__ : Dict = pa.array(OptimizedTypedSequence(A , col=A ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications snake_case__ : Optional[Any] = copy.deepcopy(A ) snake_case__ : str = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(A , A ) snake_case__ : List[str] = pa.array(OptimizedTypedSequence(A , col=A ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception' , [False, True] ) def lowercase_ (A : Union[str, Any] , A : List[str] ): snake_case__ : List[str] = str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=A ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def lowercase_ (A : int ): snake_case__ : Any = 'mock://dataset-train.arrow' with ArrowWriter(path=A , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(A ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) snake_case__ , snake_case__ : Union[str, Any] = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(A ) def lowercase_ (): snake_case__ : List[str] = pa.BufferOutputStream() with ParquetWriter(stream=A ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) snake_case__ , snake_case__ : Any = writer.finalize() assert num_examples == 2 assert num_bytes > 0 snake_case__ : Any = pa.BufferReader(output.getvalue() ) snake_case__ : pa.Table = pq.read_table(A ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files' , [False, True] ) def lowercase_ (A : List[Any] , A : Optional[Any] ): import PIL.Image snake_case__ : int = str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(A , format='png' ) snake_case__ : Tuple = pa.BufferOutputStream() with ParquetWriter( stream=A , features=Features({'image': Image()} ) , embed_local_files=A ) as writer: writer.write({'image': image_path} ) writer.finalize() snake_case__ : Dict = pa.BufferReader(output.getvalue() ) snake_case__ : pa.Table = pq.read_table(A ) snake_case__ : Optional[Any] = pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'] , A ) with open(A , 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def lowercase_ (): snake_case__ : Dict = pa.schema([pa.field('col_1' , pa.string() , nullable=A )] ) snake_case__ : Any = pa.BufferOutputStream() with ArrowWriter(stream=A ) as writer: writer._build_writer(inferred_schema=A ) assert writer._schema == pa.schema([pa.field('col_1' , pa.string() )] )
277
from math import factorial def lowercase_ (A : int , A : int , A : float ): if successes > trials: raise ValueError('successes must be lower or equal to trials' ) if trials < 0 or successes < 0: raise ValueError('the function is defined for non-negative integers' ) if not isinstance(A , A ) or not isinstance(A , A ): raise ValueError('the function is defined for non-negative integers' ) if not 0 < prob < 1: raise ValueError('prob has to be in range of 1 - 0' ) snake_case__ : List[Any] = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! snake_case__ : List[str] = float(factorial(A ) ) coefficient /= factorial(A ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print("Probability of 2 successes out of 4 trails") print("with probability of 0.75 is:", end=" ") print(binomial_distribution(2, 4, 0.75))
277
1
import warnings from .generation import TFGenerationMixin class UpperCAmelCase__ ( A__ ): """simple docstring""" warnings.warn( "Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will " "be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead." , A__ , )
218
from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : Optional[Any] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCAmelCase__ ( A__ ): """simple docstring""" a = "vivit" def __init__( self : str , __lowerCamelCase : List[Any]=224 , __lowerCamelCase : Optional[int]=32 , __lowerCamelCase : Tuple=[2, 16, 16] , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : Optional[Any]=768 , __lowerCamelCase : Any=12 , __lowerCamelCase : Optional[Any]=12 , __lowerCamelCase : List[str]=3072 , __lowerCamelCase : Any="gelu_fast" , __lowerCamelCase : Union[str, Any]=0.0 , __lowerCamelCase : int=0.0 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Any=1e-06 , __lowerCamelCase : Dict=True , **__lowerCamelCase : Any , ) -> List[str]: SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = num_frames SCREAMING_SNAKE_CASE__ = tubelet_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = qkv_bias super().__init__(**__lowerCamelCase )
218
1
'''simple docstring''' def lowercase__ ( __lowercase : list[int] ) -> int: """simple docstring""" if not numbers: return 0 if not isinstance(__lowercase , (list, tuple) ) or not all( isinstance(__lowercase , __lowercase ) for number in numbers ): raise ValueError('numbers must be an iterable of integers' ) __UpperCamelCase = __UpperCamelCase = __UpperCamelCase = numbers[0] for i in range(1 , len(__lowercase ) ): # update the maximum and minimum subarray products __UpperCamelCase = numbers[i] if number < 0: __UpperCamelCase , __UpperCamelCase = min_till_now, max_till_now __UpperCamelCase = max(__lowercase , max_till_now * number ) __UpperCamelCase = min(__lowercase , min_till_now * number ) # update the maximum product found till now __UpperCamelCase = max(__lowercase , __lowercase ) return max_prod
53
'''simple docstring''' import warnings warnings.warn( "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " "`from accelerate import find_executable_batch_size` to avoid this warning.", FutureWarning, )
237
0
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case: '''simple docstring''' def __init__( self , A_ , A_=13 , A_=32 , A_=2 , A_=3 , A_=16 , A_=[1, 2, 1] , A_=[2, 2, 4] , A_=2 , A_=2.0 , A_=True , A_=0.0 , A_=0.0 , A_=0.1 , A_="gelu" , A_=False , A_=True , A_=0.0_2 , A_=1e-5 , A_=True , A_=None , A_=True , A_=10 , A_=8 , ) -> Dict: lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = embed_dim lowerCAmelCase = depths lowerCAmelCase = num_heads lowerCAmelCase = window_size lowerCAmelCase = mlp_ratio lowerCAmelCase = qkv_bias lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = drop_path_rate lowerCAmelCase = hidden_act lowerCAmelCase = use_absolute_embeddings lowerCAmelCase = patch_norm lowerCAmelCase = layer_norm_eps lowerCAmelCase = initializer_range lowerCAmelCase = is_training lowerCAmelCase = scope lowerCAmelCase = use_labels lowerCAmelCase = type_sequence_label_size lowerCAmelCase = encoder_stride def __snake_case ( self ) -> List[str]: lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase = self.get_config() return config, pixel_values, labels def __snake_case ( self ) -> int: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __snake_case ( self , A_ , A_ , A_ ) -> int: lowerCAmelCase = SwinvaModel(config=__snake_case ) model.to(__snake_case ) model.eval() lowerCAmelCase = model(__snake_case ) lowerCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowerCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __snake_case ( self , A_ , A_ , A_ ) -> List[str]: lowerCAmelCase = SwinvaForMaskedImageModeling(config=__snake_case ) model.to(__snake_case ) model.eval() lowerCAmelCase = model(__snake_case ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowerCAmelCase = 1 lowerCAmelCase = SwinvaForMaskedImageModeling(__snake_case ) model.to(__snake_case ) model.eval() lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __snake_case ( self , A_ , A_ , A_ ) -> Optional[Any]: lowerCAmelCase = self.type_sequence_label_size lowerCAmelCase = SwinvaForImageClassification(__snake_case ) model.to(__snake_case ) model.eval() lowerCAmelCase = model(__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __snake_case ( self ) -> List[Any]: lowerCAmelCase = self.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = config_and_inputs lowerCAmelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __snake_case( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase : Any = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) UpperCAmelCase : List[str] = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) UpperCAmelCase : Tuple = False UpperCAmelCase : str = False UpperCAmelCase : Dict = False UpperCAmelCase : Union[str, Any] = False def __snake_case ( self ) -> Optional[Any]: lowerCAmelCase = SwinvaModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=__snake_case , embed_dim=37 ) def __snake_case ( self ) -> List[Any]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __snake_case ( self ) -> str: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def __snake_case ( self ) -> Optional[Any]: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def __snake_case ( self ) -> Dict: pass def __snake_case ( self ) -> Optional[int]: lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(__snake_case ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__snake_case , nn.Linear ) ) def __snake_case ( self ) -> List[Any]: lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(__snake_case ) lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase = [*signature.parameters.keys()] lowerCAmelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __snake_case ) def __snake_case ( self ) -> Dict: lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = True for model_class in self.all_model_classes: lowerCAmelCase = True lowerCAmelCase = False lowerCAmelCase = True lowerCAmelCase = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): lowerCAmelCase = model(**self._prepare_for_class(__snake_case , __snake_case ) ) lowerCAmelCase = outputs.attentions lowerCAmelCase = len(self.model_tester.depths ) self.assertEqual(len(__snake_case ) , __snake_case ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase = True lowerCAmelCase = config.window_size**2 lowerCAmelCase = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): lowerCAmelCase = model(**self._prepare_for_class(__snake_case , __snake_case ) ) lowerCAmelCase = outputs.attentions self.assertEqual(len(__snake_case ) , __snake_case ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) lowerCAmelCase = len(__snake_case ) # Check attention is always last and order is fine lowerCAmelCase = True lowerCAmelCase = True lowerCAmelCase = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): lowerCAmelCase = model(**self._prepare_for_class(__snake_case , __snake_case ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): lowerCAmelCase = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states lowerCAmelCase = 2 self.assertEqual(out_len + added_hidden_states , len(__snake_case ) ) lowerCAmelCase = outputs.attentions self.assertEqual(len(__snake_case ) , __snake_case ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __snake_case ( self , A_ , A_ , A_ , A_ ) -> List[str]: lowerCAmelCase = model_class(__snake_case ) model.to(__snake_case ) model.eval() with torch.no_grad(): lowerCAmelCase = model(**self._prepare_for_class(__snake_case , __snake_case ) ) lowerCAmelCase = outputs.hidden_states lowerCAmelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(__snake_case ) , __snake_case ) # Swinv2 has a different seq_length lowerCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) lowerCAmelCase = outputs.reshaped_hidden_states self.assertEqual(len(__snake_case ) , __snake_case ) lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = reshaped_hidden_states[0].shape lowerCAmelCase = ( reshaped_hidden_states[0].view(__snake_case , __snake_case , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __snake_case ( self ) -> int: lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , __snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , __snake_case ) def __snake_case ( self ) -> Union[str, Any]: lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = 3 lowerCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowerCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowerCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowerCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase = True self.check_hidden_states_output(__snake_case , __snake_case , __snake_case , (padded_height, padded_width) ) def __snake_case ( self ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case ) def __snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__snake_case ) @slow def __snake_case ( self ) -> Tuple: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = SwinvaModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def __snake_case ( self ) -> Any: lowerCAmelCase, lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase = _config_zero_init(__snake_case ) for model_class in self.all_model_classes: lowerCAmelCase = model_class(config=__snake_case ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class __snake_case( unittest.TestCase ): '''simple docstring''' @cached_property def __snake_case ( self ) -> str: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def __snake_case ( self ) -> Any: lowerCAmelCase = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( __snake_case ) lowerCAmelCase = self.default_image_processor lowerCAmelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) lowerCAmelCase = image_processor(images=__snake_case , return_tensors="""pt""" ).to(__snake_case ) # forward pass with torch.no_grad(): lowerCAmelCase = model(**__snake_case ) # verify the logits lowerCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __snake_case ) lowerCAmelCase = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(__snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __snake_case , atol=1e-4 ) )
371
'''simple docstring''' from __future__ import annotations def _snake_case ( _SCREAMING_SNAKE_CASE : int | str ) -> bool: """simple docstring""" lowerCAmelCase = str(_SCREAMING_SNAKE_CASE ) return n == n[::-1] def _snake_case ( _SCREAMING_SNAKE_CASE : int = 1_000_000 ) -> Dict: """simple docstring""" lowerCAmelCase = 0 for i in range(1 , _SCREAMING_SNAKE_CASE ): if is_palindrome(_SCREAMING_SNAKE_CASE ) and is_palindrome(bin(_SCREAMING_SNAKE_CASE ).split("""b""" )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
187
0
'''simple docstring''' import sys a_ : Tuple = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def a_ ( __snake_case : str = N ) -> int: """simple docstring""" lowerCamelCase_ =-sys.maxsize - 1 for i in range(len(__snake_case ) - 12 ): lowerCamelCase_ =1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: lowerCamelCase_ =product return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
75
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): def lowercase ( self : Any ): _snake_case = tempfile.mkdtemp() # fmt: off _snake_case = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on _snake_case = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) _snake_case = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] _snake_case = {'''unk_token''': '''<unk>'''} _snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _snake_case = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_lowerCamelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_lowerCamelCase ) ) _snake_case = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], '''image_std''': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } _snake_case = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def lowercase ( self : Tuple , **_lowerCamelCase : Any ): return CLIPTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def lowercase ( self : str , **_lowerCamelCase : Any ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def lowercase ( self : int , **_lowerCamelCase : Optional[int] ): return CLIPImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def lowercase ( self : Union[str, Any] ): shutil.rmtree(self.tmpdirname ) def lowercase ( self : Any ): _snake_case = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _snake_case = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowercase ( self : Optional[Any] ): _snake_case = self.get_tokenizer() _snake_case = self.get_rust_tokenizer() _snake_case = self.get_image_processor() _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor_slow.save_pretrained(self.tmpdirname ) _snake_case = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_lowerCamelCase ) _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor_fast.save_pretrained(self.tmpdirname ) _snake_case = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , _lowerCamelCase ) self.assertIsInstance(processor_fast.tokenizer , _lowerCamelCase ) 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 , _lowerCamelCase ) self.assertIsInstance(processor_fast.image_processor , _lowerCamelCase ) def lowercase ( self : List[Any] ): _snake_case = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _snake_case = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _snake_case = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) _snake_case = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def lowercase ( self : int ): _snake_case = self.get_image_processor() _snake_case = self.get_tokenizer() _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) _snake_case = self.prepare_image_inputs() _snake_case = image_processor(_lowerCamelCase , return_tensors='''np''' ) _snake_case = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowercase ( self : Any ): _snake_case = self.get_image_processor() _snake_case = self.get_tokenizer() _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) _snake_case = '''lower newer''' _snake_case = processor(text=_lowerCamelCase ) _snake_case = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowercase ( self : Any ): _snake_case = self.get_image_processor() _snake_case = self.get_tokenizer() _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) _snake_case = '''lower newer''' _snake_case = self.prepare_image_inputs() _snake_case = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(_lowerCamelCase ): processor() def lowercase ( self : List[str] ): _snake_case = self.get_image_processor() _snake_case = self.get_tokenizer() _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) _snake_case = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _snake_case = processor.batch_decode(_lowerCamelCase ) _snake_case = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def lowercase ( self : List[Any] ): _snake_case = self.get_image_processor() _snake_case = self.get_tokenizer() _snake_case = CLIPProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) _snake_case = '''lower newer''' _snake_case = self.prepare_image_inputs() _snake_case = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
288
0
import re import string import numpy as np import datasets __UpperCamelCase : Tuple = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" __UpperCamelCase : int = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" __UpperCamelCase : Optional[int] = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class __magic_name__ ( datasets.Metric): def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , reference_urls=[] , ) def UpperCAmelCase__ ( self : List[Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : Dict=False , lowerCamelCase__ : Dict=False , lowerCamelCase__ : Optional[Any]=False , ) -> List[str]: '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase__ : List[str] = np.array([re.sub(_A , '''''' , _A ) for x in predictions] ) UpperCamelCase__ : int = np.array([re.sub(_A , '''''' , _A ) for x in references] ) else: UpperCamelCase__ : Optional[Any] = np.asarray(_A ) UpperCamelCase__ : Optional[Any] = np.asarray(_A ) if ignore_case: UpperCamelCase__ : int = np.char.lower(_A ) UpperCamelCase__ : List[str] = np.char.lower(_A ) if ignore_punctuation: UpperCamelCase__ : str = string.punctuation.maketrans('''''' , '''''' , string.punctuation ) UpperCamelCase__ : str = np.char.translate(_A , table=_A ) UpperCamelCase__ : Any = np.char.translate(_A , table=_A ) if ignore_numbers: UpperCamelCase__ : int = string.digits.maketrans('''''' , '''''' , string.digits ) UpperCamelCase__ : Tuple = np.char.translate(_A , table=_A ) UpperCamelCase__ : Optional[Any] = np.char.translate(_A , table=_A ) UpperCamelCase__ : Optional[Any] = predictions == references return {"exact_match": np.mean(_A ) * 100}
371
def _a ( SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : int ): """simple docstring""" if principal <= 0: raise Exception('''Principal borrowed must be > 0''' ) if rate_per_annum < 0: raise Exception('''Rate of interest must be >= 0''' ) if years_to_repay <= 0 or not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): raise Exception('''Years to repay must be an integer > 0''' ) # Yearly rate is divided by 12 to get monthly rate UpperCamelCase__ : int = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly UpperCamelCase__ : int = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
51
0
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class __SCREAMING_SNAKE_CASE ( ctypes.Structure ): '''simple docstring''' _a = [('size', ctypes.c_int), ('visible', ctypes.c_byte)] def snake_case__ ( ): """simple docstring""" if os.name == "nt": lowerCamelCase__ : Union[str, Any] =CursorInfo() lowerCamelCase__ : int =ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__lowerCamelCase , ctypes.byref(__lowerCamelCase ) ) lowerCamelCase__ : Tuple =False ctypes.windll.kernelaa.SetConsoleCursorInfo(__lowerCamelCase , ctypes.byref(__lowerCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25l''' ) sys.stdout.flush() def snake_case__ ( ): """simple docstring""" if os.name == "nt": lowerCamelCase__ : Optional[Any] =CursorInfo() lowerCamelCase__ : List[Any] =ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(__lowerCamelCase , ctypes.byref(__lowerCamelCase ) ) lowerCamelCase__ : List[str] =True ctypes.windll.kernelaa.SetConsoleCursorInfo(__lowerCamelCase , ctypes.byref(__lowerCamelCase ) ) elif os.name == "posix": sys.stdout.write('''\033[?25h''' ) sys.stdout.flush() @contextmanager def snake_case__ ( ): """simple docstring""" try: hide_cursor() yield finally: show_cursor()
238
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def _SCREAMING_SNAKE_CASE ( lowercase : Union[dict, list, tuple, torch.Tensor] ): '''simple docstring''' lowerCamelCase_ = [] if isinstance(lowercase , lowercase ): for v in tree.values(): shapes.extend(_fetch_dims(lowercase ) ) elif isinstance(lowercase , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(lowercase ) ) elif isinstance(lowercase , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('Not supported' ) return shapes @torch.jit.ignore def _SCREAMING_SNAKE_CASE ( lowercase : int , lowercase : Tuple[int, ...] ): '''simple docstring''' lowerCamelCase_ = [] for d in reversed(lowercase ): idx.append(flat_idx % d ) lowerCamelCase_ = flat_idx // d return tuple(reversed(lowercase ) ) @torch.jit.ignore def _SCREAMING_SNAKE_CASE ( lowercase : Sequence[int] , lowercase : Sequence[int] , lowercase : Sequence[int] , lowercase : Optional[Sequence[bool]] = None , lowercase : Optional[Sequence[bool]] = None , ): '''simple docstring''' def reduce_edge_list(lowercase : List[bool] ) -> None: lowerCamelCase_ = True for i in range(len(lowercase ) ): lowerCamelCase_ = -1 * (i + 1) l[reversed_idx] &= tally lowerCamelCase_ = l[reversed_idx] if start_edges is None: lowerCamelCase_ = [s == 0 for s in start] reduce_edge_list(lowercase ) if end_edges is None: lowerCamelCase_ = [e == (d - 1) for e, d in zip(lowercase , lowercase )] reduce_edge_list(lowercase ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(lowercase ) == 0: return [()] elif len(lowercase ) == 1: return [(slice(start[0] , end[0] + 1 ),)] lowerCamelCase_ = [] lowerCamelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(lowercase , lowercase ): if s == e: path_list.append(slice(lowercase , s + 1 ) ) else: break lowerCamelCase_ = tuple(lowercase ) lowerCamelCase_ = len(lowercase ) # start == end, and we're done if divergence_idx == len(lowercase ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase_ = start[divergence_idx] return tuple( path + (slice(lowercase , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowerCamelCase_ = end[divergence_idx] return tuple( path + (slice(lowercase , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) lowerCamelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def _SCREAMING_SNAKE_CASE ( lowercase : torch.Tensor , lowercase : int , lowercase : int , lowercase : int ): '''simple docstring''' lowerCamelCase_ = t.shape[:no_batch_dims] lowerCamelCase_ = list(_flat_idx_to_idx(lowercase , lowercase ) ) # _get_minimal_slice_set is inclusive lowerCamelCase_ = list(_flat_idx_to_idx(flat_end - 1 , lowercase ) ) # Get an ordered list of slices to perform lowerCamelCase_ = _get_minimal_slice_set( lowercase , lowercase , lowercase , ) lowerCamelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def _SCREAMING_SNAKE_CASE ( lowercase : Callable , lowercase : Dict[str, Any] , lowercase : int , lowercase : int , lowercase : bool = False , lowercase : Any = None , lowercase : bool = False , ): '''simple docstring''' if not (len(lowercase ) > 0): raise ValueError('Must provide at least one input' ) lowerCamelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(lowercase )] lowerCamelCase_ = tuple([max(lowercase ) for s in zip(*lowercase )] ) def _prep_inputs(lowercase : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: lowerCamelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) lowerCamelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: lowerCamelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t lowerCamelCase_ = tensor_tree_map(_prep_inputs , lowercase ) lowerCamelCase_ = None if _out is not None: lowerCamelCase_ = tensor_tree_map(lambda lowercase : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) lowerCamelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d lowerCamelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(lowercase : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t lowerCamelCase_ = 0 lowerCamelCase_ = prepped_outputs for _ in range(lowercase ): # Chunk the input if not low_mem: lowerCamelCase_ = _select_chunk else: lowerCamelCase_ = partial( _chunk_slice , flat_start=lowercase , flat_end=min(lowercase , i + chunk_size ) , no_batch_dims=len(lowercase ) , ) lowerCamelCase_ = tensor_tree_map(lowercase , lowercase ) # Run the layer on the chunk lowerCamelCase_ = layer(**lowercase ) # Allocate space for the output if out is None: lowerCamelCase_ = tensor_tree_map(lambda lowercase : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , lowercase ) # Put the chunk in its pre-allocated space if isinstance(lowercase , lowercase ): def assign(lowercase : dict , lowercase : dict ) -> None: for k, v in da.items(): if isinstance(lowercase , lowercase ): assign(lowercase , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: lowerCamelCase_ = da[k] assign(lowercase , lowercase ) elif isinstance(lowercase , lowercase ): for xa, xa in zip(lowercase , lowercase ): if _add_into_out: xa[i : i + chunk_size] += xa else: lowerCamelCase_ = xa elif isinstance(lowercase , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: lowerCamelCase_ = output_chunk else: raise ValueError('Not supported' ) i += chunk_size lowerCamelCase_ = tensor_tree_map(lambda lowercase : t.view(orig_batch_dims + t.shape[1:] ) , lowercase ) return out class A: '''simple docstring''' def __init__( self : Optional[Any] , A_ : int = 512 , ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ = max_chunk_size lowerCamelCase_ = None lowerCamelCase_ = None def a__ ( self : int , A_ : Callable , A_ : tuple , A_ : int ) -> int: """simple docstring""" logging.info('Tuning chunk size...' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size lowerCamelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] lowerCamelCase_ = [c for c in candidates if c > min_chunk_size] lowerCamelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(A_ : int ) -> bool: try: with torch.no_grad(): fn(*A_ , chunk_size=A_ ) return True except RuntimeError: return False lowerCamelCase_ = 0 lowerCamelCase_ = len(A_ ) - 1 while i > min_viable_chunk_size_index: lowerCamelCase_ = test_chunk_size(candidates[i] ) if not viable: lowerCamelCase_ = (min_viable_chunk_size_index + i) // 2 else: lowerCamelCase_ = i lowerCamelCase_ = (i + len(A_ ) - 1) // 2 return candidates[min_viable_chunk_size_index] def a__ ( self : List[str] , A_ : Iterable , A_ : Iterable ) -> bool: """simple docstring""" lowerCamelCase_ = True for aa, aa in zip(A_ , A_ ): assert type(A_ ) == type(A_ ) if isinstance(A_ , (list, tuple) ): consistent &= self._compare_arg_caches(A_ , A_ ) elif isinstance(A_ , A_ ): lowerCamelCase_ = [v for _, v in sorted(aa.items() , key=lambda A_ : x[0] )] lowerCamelCase_ = [v for _, v in sorted(aa.items() , key=lambda A_ : x[0] )] consistent &= self._compare_arg_caches(A_ , A_ ) else: consistent &= aa == aa return consistent def a__ ( self : int , A_ : Callable , A_ : tuple , A_ : int , ) -> int: """simple docstring""" lowerCamelCase_ = True lowerCamelCase_ = tree_map(lambda A_ : a.shape if isinstance(A_ , torch.Tensor ) else a , A_ , A_ ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(A_ ) lowerCamelCase_ = self._compare_arg_caches(self.cached_arg_data , A_ ) else: # Otherwise, we can reuse the precomputed value lowerCamelCase_ = False if not consistent: lowerCamelCase_ = self._determine_favorable_chunk_size( A_ , A_ , A_ , ) lowerCamelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
204
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer __snake_case = logging.get_logger(__name__) __snake_case = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all MVP models at https://huggingface.co/models?filter=mvp __snake_case = { """vocab_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json""", }, """added_tokens.json""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json""", }, """merges_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt""", }, """tokenizer_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json""", }, } __snake_case = { """RUCAIBox/mvp""": 1024, } class _lowerCAmelCase ( a__ ): __UpperCAmelCase : int = VOCAB_FILES_NAMES __UpperCAmelCase : Any = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[Any] = ['''input_ids''', '''attention_mask'''] __UpperCAmelCase : Any = MvpTokenizer def __init__( self , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__="replace" , UpperCamelCase__="<s>" , UpperCamelCase__="</s>" , UpperCamelCase__="</s>" , UpperCamelCase__="<s>" , UpperCamelCase__="<unk>" , UpperCamelCase__="<pad>" , UpperCamelCase__="<mask>" , UpperCamelCase__=False , UpperCamelCase__=True , **UpperCamelCase__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , errors=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , trim_offsets=UpperCamelCase__ , **UpperCamelCase__ , ) snake_case : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , UpperCamelCase__ ) != add_prefix_space: snake_case : List[str] = getattr(UpperCamelCase__ , pre_tok_state.pop("type" ) ) snake_case : Dict = add_prefix_space snake_case : str = pre_tok_class(**UpperCamelCase__ ) snake_case : Union[str, Any] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` snake_case : int = "post_processor" snake_case : List[str] = getattr(self.backend_tokenizer , UpperCamelCase__ , UpperCamelCase__ ) if tokenizer_component_instance: snake_case : Union[str, Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: snake_case : List[str] = tuple(state["sep"] ) if "cls" in state: snake_case : Dict = tuple(state["cls"] ) snake_case : str = False if state.get("add_prefix_space" , UpperCamelCase__ ) != add_prefix_space: snake_case : List[str] = add_prefix_space snake_case : Optional[Any] = True if state.get("trim_offsets" , UpperCamelCase__ ) != trim_offsets: snake_case : Dict = trim_offsets snake_case : Tuple = True if changes_to_apply: snake_case : List[Any] = getattr(UpperCamelCase__ , state.pop("type" ) ) snake_case : Union[str, Any] = component_class(**UpperCamelCase__ ) setattr(self.backend_tokenizer , UpperCamelCase__ , UpperCamelCase__ ) @property def lowerCamelCase ( self ) -> Optional[Any]: '''simple docstring''' if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def lowerCamelCase ( self , UpperCamelCase__ ) -> List[Any]: '''simple docstring''' snake_case : Dict = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else value snake_case : List[str] = value def lowerCamelCase ( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> Union[str, Any]: '''simple docstring''' snake_case : List[str] = kwargs.get("is_split_into_words" , UpperCamelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase ( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> Tuple: '''simple docstring''' snake_case : Optional[Any] = kwargs.get("is_split_into_words" , UpperCamelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> Any: '''simple docstring''' snake_case : Tuple = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__=None ) -> Any: '''simple docstring''' snake_case : Dict = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__ = None ) -> int: '''simple docstring''' snake_case : Union[str, Any] = [self.sep_token_id] snake_case : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
370
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) __snake_case = logging.getLogger(__name__) if __name__ == "__main__": __snake_case = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) __snake_case = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: __snake_case = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") __snake_case = Counter() for tk_ids in data: counter.update(tk_ids) __snake_case = [0] * args.vocab_size for k, v in counter.items(): __snake_case = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
112
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase = {'configuration_wavlm': ['WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WavLMConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ 'WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'WavLMForAudioFrameClassification', 'WavLMForCTC', 'WavLMForSequenceClassification', 'WavLMForXVector', 'WavLMModel', 'WavLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
188
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
0
'''simple docstring''' import functools def _A ( snake_case , snake_case ) -> int: _lowercase : List[str] = len(snake_case ) _lowercase : Any = len(snake_case ) @functools.cache def min_distance(snake_case , snake_case ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa _lowercase : Tuple = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , snake_case ) , 1 + min_distance(snake_case , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
199
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { 'weiweishi/roc-bert-base-zh': 'https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json', } class a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : Any = 'roc_bert' def __init__( self , _UpperCamelCase=30522 , _UpperCamelCase=768 , _UpperCamelCase=12 , _UpperCamelCase=12 , _UpperCamelCase=3072 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=512 , _UpperCamelCase=2 , _UpperCamelCase=0.0_2 , _UpperCamelCase=1E-1_2 , _UpperCamelCase=True , _UpperCamelCase=0 , _UpperCamelCase="absolute" , _UpperCamelCase=None , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=768 , _UpperCamelCase=910 , _UpperCamelCase=512 , _UpperCamelCase=24858 , _UpperCamelCase=True , **_UpperCamelCase , ): """simple docstring""" _lowercase : str = vocab_size _lowercase : List[str] = max_position_embeddings _lowercase : List[Any] = hidden_size _lowercase : Dict = num_hidden_layers _lowercase : str = num_attention_heads _lowercase : int = intermediate_size _lowercase : Optional[Any] = hidden_act _lowercase : Union[str, Any] = hidden_dropout_prob _lowercase : Dict = attention_probs_dropout_prob _lowercase : Dict = initializer_range _lowercase : List[Any] = type_vocab_size _lowercase : Tuple = layer_norm_eps _lowercase : Optional[int] = use_cache _lowercase : Tuple = enable_pronunciation _lowercase : Optional[int] = enable_shape _lowercase : int = pronunciation_embed_dim _lowercase : List[str] = pronunciation_vocab_size _lowercase : int = shape_embed_dim _lowercase : str = shape_vocab_size _lowercase : str = concat_input _lowercase : Dict = position_embedding_type _lowercase : Optional[Any] = classifier_dropout super().__init__(pad_token_id=_UpperCamelCase , **_UpperCamelCase )
199
1
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class lowercase__( __lowercase , unittest.TestCase ): """simple docstring""" a :Dict = RoCBertTokenizer a :Union[str, Any] = None a :Optional[int] = False a :List[Any] = True a :str = filter_non_english def _lowercase ( self : Optional[int] ) -> int: super().setUp() lowercase_ = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] lowercase_ = {} lowercase_ = {} for i, value in enumerate(SCREAMING_SNAKE_CASE_ ): lowercase_ = i lowercase_ = i lowercase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''word_shape_file'''] ) lowercase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''word_pronunciation_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.word_shape_file , '''w''' , encoding='''utf-8''' ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) with open(self.word_pronunciation_file , '''w''' , encoding='''utf-8''' ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Union[str, Any] ) -> Any: lowercase_ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) lowercase_ = tokenizer.tokenize('''你好[SEP]你是谁''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''你''', '''好''', '''[SEP]''', '''你''', '''是''', '''谁'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) def _lowercase ( self : Optional[Any] ) -> List[str]: lowercase_ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def _lowercase ( self : str ) -> Union[str, Any]: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def _lowercase ( self : int ) -> Dict: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def _lowercase ( self : List[Any] ) -> Dict: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def _lowercase ( self : Optional[Any] ) -> Optional[Any]: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def _lowercase ( self : int ) -> Dict: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase ( self : Optional[int] ) -> List[Any]: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase ( self : int ) -> Optional[Any]: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _lowercase ( self : Optional[Any] ) -> int: lowercase_ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def _lowercase ( self : Union[str, Any] ) -> List[Any]: lowercase_ = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] lowercase_ = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): lowercase_ = i lowercase_ = RoCBertWordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , 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 _lowercase ( self : Optional[int] ) -> Dict: 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 _lowercase ( self : Dict ) -> 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 _lowercase ( self : Union[str, Any] ) -> Tuple: 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 _lowercase ( self : Tuple ) -> List[str]: lowercase_ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) if self.test_rust_tokenizer: lowercase_ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) def _lowercase ( self : Optional[Any] ) -> int: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowercase_ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' lowercase_ = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , ) lowercase_ = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_ , '''do_lower_case''' ) else False lowercase_ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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 _lowercase ( self : int ) -> Optional[int]: lowercase_ = ["的", "人", "有"] lowercase_ = "".join(SCREAMING_SNAKE_CASE_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowercase_ = True lowercase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowercase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase_ = False lowercase_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowercase_ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that only the first Chinese character is not preceded by "##". lowercase_ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE_ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def _lowercase ( self : List[Any] ) -> Optional[int]: lowercase_ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) lowercase_ = tokenizer.encode('''你好''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.encode('''你是谁''' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _lowercase ( self : List[str] ) -> Any: lowercase_ = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE_ ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): lowercase_ = "你好,你是谁" lowercase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowercase_ = tokenizer.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
30
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[list[int]]) -> bool: '''simple docstring''' __UpperCamelCase : Any = len(_lowerCamelCase) # We need to create solution object to save path. __UpperCamelCase : List[str] = [[0 for _ in range(_lowerCamelCase)] for _ in range(_lowerCamelCase)] __UpperCamelCase : Optional[int] = run_maze(_lowerCamelCase , 0 , 0 , _lowerCamelCase) if solved: print("\n".join(str(_lowerCamelCase) for row in solutions)) else: print("No solution exists!") return solved def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[list[int]] , _lowerCamelCase : int , _lowerCamelCase : int , _lowerCamelCase : list[list[int]]) -> bool: '''simple docstring''' __UpperCamelCase : Tuple = len(_lowerCamelCase) # Final check point. if i == j == (size - 1): __UpperCamelCase : Optional[int] = 1 return True __UpperCamelCase : List[Any] = (not i < 0) and (not j < 0) # Check lower bounds __UpperCamelCase : List[str] = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. __UpperCamelCase : int = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited __UpperCamelCase : Tuple = 1 # check for directions if ( run_maze(_lowerCamelCase , i + 1 , _lowerCamelCase , _lowerCamelCase) or run_maze(_lowerCamelCase , _lowerCamelCase , j + 1 , _lowerCamelCase) or run_maze(_lowerCamelCase , i - 1 , _lowerCamelCase , _lowerCamelCase) or run_maze(_lowerCamelCase , _lowerCamelCase , j - 1 , _lowerCamelCase) ): return True __UpperCamelCase : Tuple = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
232
0
"""simple docstring""" import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase=7 , __UpperCAmelCase=3 , __UpperCAmelCase=18 , __UpperCAmelCase=30 , __UpperCAmelCase=400 , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase=[0.5, 0.5, 0.5] , __UpperCAmelCase=[0.5, 0.5, 0.5] , __UpperCAmelCase=False , ) -> int: _a = size if size is not None else {'''height''': 20, '''width''': 20} _a = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} _a = parent _a = batch_size _a = num_channels _a = image_size _a = min_resolution _a = max_resolution _a = do_resize _a = size _a = do_center_crop _a = crop_size _a = do_normalize _a = image_mean _a = image_std _a = do_reduce_labels def _UpperCAmelCase ( self ) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def A_ ( ): """simple docstring""" _a = load_dataset('''hf-internal-testing/fixtures_ade20k''', split='''test''' ) _a = Image.open(dataset[0]['''file'''] ) _a = Image.open(dataset[1]['''file'''] ) return image, map def A_ ( ): """simple docstring""" _a = load_dataset('''hf-internal-testing/fixtures_ade20k''', split='''test''' ) _a = Image.open(ds[0]['''file'''] ) _a = Image.open(ds[1]['''file'''] ) _a = Image.open(ds[2]['''file'''] ) _a = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __lowerCamelCase ( a__ , unittest.TestCase ): '''simple docstring''' A_ : Dict = BeitImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self ) -> Optional[int]: _a = BeitImageProcessingTester(self ) @property def _UpperCAmelCase ( self ) -> List[str]: return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self ) -> Optional[Any]: _a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''size''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_center_crop''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''center_crop''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_mean''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_std''' ) ) def _UpperCAmelCase ( self ) -> List[str]: _a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) self.assertEqual(image_processor.do_reduce_labels , __UpperCAmelCase ) _a = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=__UpperCAmelCase ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) self.assertEqual(image_processor.do_reduce_labels , __UpperCAmelCase ) def _UpperCAmelCase ( self ) -> Any: pass def _UpperCAmelCase ( self ) -> int: # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched _a = image_processing(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _UpperCAmelCase ( self ) -> List[str]: # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched _a = image_processing(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _UpperCAmelCase ( self ) -> Optional[int]: # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched _a = image_processing(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def _UpperCAmelCase ( self ) -> List[Any]: # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) _a = [] for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input _a = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched _a = image_processing(__UpperCAmelCase , __UpperCAmelCase , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test not batched input (PIL images) _a , _a = prepare_semantic_single_inputs() _a = image_processing(__UpperCAmelCase , __UpperCAmelCase , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) # Test batched input (PIL images) _a , _a = prepare_semantic_batch_inputs() _a = image_processing(__UpperCAmelCase , __UpperCAmelCase , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 ) def _UpperCAmelCase ( self ) -> List[Any]: # Initialize image_processing _a = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 _a , _a = prepare_semantic_single_inputs() _a = image_processing(__UpperCAmelCase , __UpperCAmelCase , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 150 ) _a = True _a = image_processing(__UpperCAmelCase , __UpperCAmelCase , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 255 )
153
"""simple docstring""" from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __snake_case = datasets.load_iris() __snake_case = np.array(data['''data''']) __snake_case = np.array(data['''target''']) __snake_case = data['''target_names'''] __snake_case ,__snake_case ,__snake_case ,__snake_case = train_test_split(X, y) def A_ ( _lowerCAmelCase : int, _lowerCAmelCase : Union[str, Any] ): """simple docstring""" return np.linalg.norm(np.array(_lowerCAmelCase ) - np.array(_lowerCAmelCase ) ) def A_ ( _lowerCAmelCase : Optional[int], _lowerCAmelCase : Tuple, _lowerCAmelCase : Optional[Any], _lowerCAmelCase : int, _lowerCAmelCase : str=5 ): """simple docstring""" _a = zip(_lowerCAmelCase, _lowerCAmelCase ) # List of distances of all points from the point to be classified _a = [] for data_point in data: _a = euclidean_distance(data_point[0], _lowerCAmelCase ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. _a = [i[1] for i in sorted(_lowerCAmelCase )[:k]] # Most commonly occurring class among them # is the class into which the point is classified _a = Counter(_lowerCAmelCase ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
153
1
from math import factorial def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 1_00 ): return sum(map(SCREAMING_SNAKE_CASE__ , str(factorial(SCREAMING_SNAKE_CASE__ ) ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
62
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10**12 ): __UpperCamelCase =1 __UpperCamelCase =0 __UpperCamelCase =1 __UpperCamelCase =1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f"""{solution() = }""")
62
1
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Any = IFInpaintingPipeline _A : Optional[int] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'} _A : str = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _A : Optional[Any] = PipelineTesterMixin.required_optional_params - {'latents'} def UpperCamelCase_ ( self ) -> int: """simple docstring""" return self._get_dummy_components() def UpperCamelCase_ ( self , snake_case__ , snake_case__=0 ) -> Union[str, Any]: """simple docstring""" if str(snake_case__ ).startswith("""mps""" ): UpperCAmelCase = torch.manual_seed(snake_case__ ) else: UpperCAmelCase = torch.Generator(device=snake_case__ ).manual_seed(snake_case__ ) UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case__ ) ).to(snake_case__ ) UpperCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" self._test_save_load_local() def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
351
"""simple docstring""" import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline lowerCAmelCase_ : Tuple = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=False , ): '''simple docstring''' output_path.parent.mkdir(parents=lowerCAmelCase , exist_ok=lowerCAmelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( lowerCAmelCase , lowerCAmelCase , f=output_path.as_posix() , input_names=lowerCAmelCase , output_names=lowerCAmelCase , dynamic_axes=lowerCAmelCase , do_constant_folding=lowerCAmelCase , use_external_data_format=lowerCAmelCase , enable_onnx_checker=lowerCAmelCase , opset_version=lowerCAmelCase , ) else: export( lowerCAmelCase , lowerCAmelCase , f=output_path.as_posix() , input_names=lowerCAmelCase , output_names=lowerCAmelCase , dynamic_axes=lowerCAmelCase , do_constant_folding=lowerCAmelCase , opset_version=lowerCAmelCase , ) @torch.no_grad() def _lowerCAmelCase ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = False ): '''simple docstring''' UpperCAmelCase = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): UpperCAmelCase = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: UpperCAmelCase = """cpu""" UpperCAmelCase = StableDiffusionPipeline.from_pretrained(lowerCAmelCase , torch_dtype=lowerCAmelCase ).to(lowerCAmelCase ) UpperCAmelCase = Path(lowerCAmelCase ) # TEXT ENCODER UpperCAmelCase = pipeline.text_encoder.config.max_position_embeddings UpperCAmelCase = pipeline.text_encoder.config.hidden_size UpperCAmelCase = pipeline.tokenizer( """A sample prompt""" , padding="""max_length""" , max_length=pipeline.tokenizer.model_max_length , truncation=lowerCAmelCase , return_tensors="""pt""" , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=lowerCAmelCase , dtype=torch.intaa )) , output_path=output_path / """text_encoder""" / """model.onnx""" , ordered_input_names=["""input_ids"""] , output_names=["""last_hidden_state""", """pooler_output"""] , dynamic_axes={ """input_ids""": {0: """batch""", 1: """sequence"""}, } , opset=lowerCAmelCase , ) del pipeline.text_encoder # UNET UpperCAmelCase = pipeline.unet.config.in_channels UpperCAmelCase = pipeline.unet.config.sample_size UpperCAmelCase = output_path / """unet""" / """model.onnx""" onnx_export( pipeline.unet , model_args=( torch.randn(2 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), torch.randn(2 ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), torch.randn(2 , lowerCAmelCase , lowerCAmelCase ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), False, ) , output_path=lowerCAmelCase , ordered_input_names=["""sample""", """timestep""", """encoder_hidden_states""", """return_dict"""] , output_names=["""out_sample"""] , dynamic_axes={ """sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, """timestep""": {0: """batch"""}, """encoder_hidden_states""": {0: """batch""", 1: """sequence"""}, } , opset=lowerCAmelCase , use_external_data_format=lowerCAmelCase , ) UpperCAmelCase = str(unet_path.absolute().as_posix() ) UpperCAmelCase = os.path.dirname(lowerCAmelCase ) UpperCAmelCase = onnx.load(lowerCAmelCase ) # clean up existing tensor files shutil.rmtree(lowerCAmelCase ) os.mkdir(lowerCAmelCase ) # collate external tensor files into one onnx.save_model( lowerCAmelCase , lowerCAmelCase , save_as_external_data=lowerCAmelCase , all_tensors_to_one_file=lowerCAmelCase , location="""weights.pb""" , convert_attribute=lowerCAmelCase , ) del pipeline.unet # VAE ENCODER UpperCAmelCase = pipeline.vae UpperCAmelCase = vae_encoder.config.in_channels UpperCAmelCase = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder UpperCAmelCase = lambda lowerCAmelCase , lowerCAmelCase : vae_encoder.encode(lowerCAmelCase , lowerCAmelCase )[0].sample() onnx_export( lowerCAmelCase , model_args=( torch.randn(1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), False, ) , output_path=output_path / """vae_encoder""" / """model.onnx""" , ordered_input_names=["""sample""", """return_dict"""] , output_names=["""latent_sample"""] , dynamic_axes={ """sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=lowerCAmelCase , ) # VAE DECODER UpperCAmelCase = pipeline.vae UpperCAmelCase = vae_decoder.config.latent_channels UpperCAmelCase = vae_decoder.config.out_channels # forward only through the decoder part UpperCAmelCase = vae_encoder.decode onnx_export( lowerCAmelCase , model_args=( torch.randn(1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), False, ) , output_path=output_path / """vae_decoder""" / """model.onnx""" , ordered_input_names=["""latent_sample""", """return_dict"""] , output_names=["""sample"""] , dynamic_axes={ """latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=lowerCAmelCase , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: UpperCAmelCase = pipeline.safety_checker UpperCAmelCase = safety_checker.config.vision_config.num_channels UpperCAmelCase = safety_checker.config.vision_config.image_size UpperCAmelCase = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), torch.randn(1 , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ).to(device=lowerCAmelCase , dtype=lowerCAmelCase ), ) , output_path=output_path / """safety_checker""" / """model.onnx""" , ordered_input_names=["""clip_input""", """images"""] , output_names=["""out_images""", """has_nsfw_concepts"""] , dynamic_axes={ """clip_input""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, """images""": {0: """batch""", 1: """height""", 2: """width""", 3: """channels"""}, } , opset=lowerCAmelCase , ) del pipeline.safety_checker UpperCAmelCase = OnnxRuntimeModel.from_pretrained(output_path / """safety_checker""" ) UpperCAmelCase = pipeline.feature_extractor else: UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / """vae_encoder""" ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / """vae_decoder""" ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / """text_encoder""" ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / """unet""" ) , scheduler=pipeline.scheduler , safety_checker=lowerCAmelCase , feature_extractor=lowerCAmelCase , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(lowerCAmelCase ) print("""ONNX pipeline saved to""" , lowerCAmelCase ) del pipeline del onnx_pipeline UpperCAmelCase = OnnxStableDiffusionPipeline.from_pretrained(lowerCAmelCase , provider="""CPUExecutionProvider""" ) print("""ONNX pipeline is loadable""" ) if __name__ == "__main__": lowerCAmelCase_ : Tuple = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=1_4, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') lowerCAmelCase_ : Union[str, Any] = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
248
0
"""simple docstring""" import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase ( __lowerCamelCase , unittest.TestCase ): SCREAMING_SNAKE_CASE_ = CodeGenTokenizer SCREAMING_SNAKE_CASE_ = CodeGenTokenizerFast SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = {"add_prefix_space": True} SCREAMING_SNAKE_CASE_ = False def a_ ( self) -> Tuple: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case_ = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] snake_case_ = dict(zip(SCREAMING_SNAKE_CASE_, range(len(SCREAMING_SNAKE_CASE_)))) snake_case_ = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] snake_case_ = {'unk_token': '<unk>'} snake_case_ = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['vocab_file']) snake_case_ = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['merges_file']) with open(self.vocab_file, 'w', encoding='utf-8') as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_) + '\n') with open(self.merges_file, 'w', encoding='utf-8') as fp: fp.write('\n'.join(SCREAMING_SNAKE_CASE_)) def a_ ( self, **lowerCAmelCase__) -> Optional[int]: kwargs.update(self.special_tokens_map) return CodeGenTokenizer.from_pretrained(self.tmpdirname, **SCREAMING_SNAKE_CASE_) def a_ ( self, **lowerCAmelCase__) -> Union[str, Any]: kwargs.update(self.special_tokens_map) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname, **SCREAMING_SNAKE_CASE_) def a_ ( self, lowerCAmelCase__) -> str: snake_case_ = 'lower newer' snake_case_ = 'lower newer' return input_text, output_text def a_ ( self) -> List[Any]: snake_case_ = CodeGenTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map) snake_case_ = 'lower newer' snake_case_ = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] snake_case_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_, add_prefix_space=SCREAMING_SNAKE_CASE_) self.assertListEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_) snake_case_ = tokens + [tokenizer.unk_token] snake_case_ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_), SCREAMING_SNAKE_CASE_) def a_ ( self) -> Optional[Any]: if not self.test_rust_tokenizer: return snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE_) snake_case_ = 'lower newer' # Testing tokenization snake_case_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_, add_prefix_space=SCREAMING_SNAKE_CASE_) snake_case_ = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_) self.assertListEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_) # Testing conversion to ids without special tokens snake_case_ = tokenizer.encode(SCREAMING_SNAKE_CASE_, add_special_tokens=SCREAMING_SNAKE_CASE_, add_prefix_space=SCREAMING_SNAKE_CASE_) snake_case_ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_, add_special_tokens=SCREAMING_SNAKE_CASE_) self.assertListEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_) # Testing conversion to ids with special tokens snake_case_ = self.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE_) snake_case_ = tokenizer.encode(SCREAMING_SNAKE_CASE_, add_prefix_space=SCREAMING_SNAKE_CASE_) snake_case_ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_) self.assertListEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_) # Testing the unknown token snake_case_ = tokens + [rust_tokenizer.unk_token] snake_case_ = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_), SCREAMING_SNAKE_CASE_) def a_ ( self, *lowerCAmelCase__, **lowerCAmelCase__) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def a_ ( self, lowerCAmelCase__=15) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})'): snake_case_ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_) # Simple input snake_case_ = 'This is a simple input' snake_case_ = ['This is a simple input 1', 'This is a simple input 2'] snake_case_ = ('This is a simple input', 'This is a pair') snake_case_ = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE_, tokenizer_r.encode, SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, padding='max_length') # Simple input self.assertRaises(SCREAMING_SNAKE_CASE_, tokenizer_r.encode_plus, SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, padding='max_length') # Simple input self.assertRaises( SCREAMING_SNAKE_CASE_, tokenizer_r.batch_encode_plus, SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, padding='max_length', ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE_, tokenizer_r.encode, SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, padding='max_length') # Pair input self.assertRaises(SCREAMING_SNAKE_CASE_, tokenizer_r.encode_plus, SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, padding='max_length') # Pair input self.assertRaises( SCREAMING_SNAKE_CASE_, tokenizer_r.batch_encode_plus, SCREAMING_SNAKE_CASE_, max_length=SCREAMING_SNAKE_CASE_, padding='max_length', ) def a_ ( self) -> List[Any]: snake_case_ = CodeGenTokenizer.from_pretrained(self.tmpdirname, pad_token='<pad>') # Simple input snake_case_ = 'This is a simple input' snake_case_ = ['This is a simple input looooooooong', 'This is a simple input'] snake_case_ = ('This is a simple input', 'This is a pair') snake_case_ = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] snake_case_ = tokenizer.pad_token_id snake_case_ = tokenizer(SCREAMING_SNAKE_CASE_, padding='max_length', max_length=30, return_tensors='np') snake_case_ = tokenizer(SCREAMING_SNAKE_CASE_, padding=SCREAMING_SNAKE_CASE_, truncate=SCREAMING_SNAKE_CASE_, return_tensors='np') snake_case_ = tokenizer(*SCREAMING_SNAKE_CASE_, padding='max_length', max_length=60, return_tensors='np') snake_case_ = tokenizer(SCREAMING_SNAKE_CASE_, padding=SCREAMING_SNAKE_CASE_, truncate=SCREAMING_SNAKE_CASE_, return_tensors='np') # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1], 30) self.assertTrue(pad_token_id in out_s['input_ids']) self.assertTrue(0 in out_s['attention_mask']) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1], 33) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0]) self.assertFalse(0 in out_sa['attention_mask'][0]) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1]) self.assertTrue(0 in out_sa['attention_mask'][1]) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1], 60) self.assertTrue(pad_token_id in out_p['input_ids']) self.assertTrue(0 in out_p['attention_mask']) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1], 52) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0]) self.assertFalse(0 in out_pa['attention_mask'][0]) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1]) self.assertTrue(0 in out_pa['attention_mask'][1]) def a_ ( self) -> str: snake_case_ = '$$$' snake_case_ = CodeGenTokenizer.from_pretrained(self.tmpdirname, bos_token=SCREAMING_SNAKE_CASE_, add_bos_token=SCREAMING_SNAKE_CASE_) snake_case_ = 'This is a simple input' snake_case_ = ['This is a simple input 1', 'This is a simple input 2'] snake_case_ = tokenizer.bos_token_id snake_case_ = tokenizer(SCREAMING_SNAKE_CASE_) snake_case_ = tokenizer(SCREAMING_SNAKE_CASE_) self.assertEqual(out_s.input_ids[0], SCREAMING_SNAKE_CASE_) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids)) snake_case_ = tokenizer.decode(out_s.input_ids) snake_case_ = tokenizer.batch_decode(out_sa.input_ids) self.assertEqual(decode_s.split()[0], SCREAMING_SNAKE_CASE_) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa)) @slow def a_ ( self) -> Optional[Any]: snake_case_ = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono') snake_case_ = '\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#' snake_case_ = '\nif len_a > len_b: result = a\nelse: result = b' snake_case_ = tokenizer.encode(SCREAMING_SNAKE_CASE_) snake_case_ = ['^#', re.escape('<|endoftext|>'), '^\'\'\'', '^\"\"\"', '\n\n\n'] snake_case_ = tokenizer.decode(SCREAMING_SNAKE_CASE_, truncate_before_pattern=SCREAMING_SNAKE_CASE_) self.assertEqual(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_) def a_ ( self) -> Optional[int]: pass
69
import argparse import os import torch from transformers.utils import WEIGHTS_NAME lowerCamelCase_ = ['''small''', '''medium''', '''large'''] lowerCamelCase_ = '''lm_head.decoder.weight''' lowerCamelCase_ = '''lm_head.weight''' def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = torch.load(__a ) UpperCamelCase__ = d.pop(__a ) os.makedirs(__a , exist_ok=__a ) torch.save(__a , os.path.join(__a , __a ) ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--dialogpt_path''', default='''.''', type=str) lowerCamelCase_ = parser.parse_args() for MODEL in DIALOGPT_MODELS: lowerCamelCase_ = os.path.join(args.dialogpt_path, f'{MODEL}_ft.pkl') lowerCamelCase_ = f'./DialoGPT-{MODEL}' convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
244
0
"""simple docstring""" import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1024 , lowerCAmelCase_=1024 , lowerCAmelCase_=False , **lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path="train" , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = tok.pad_token_id def get_lens(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = tqdm( DataLoader(lowerCAmelCase_ , batch_size=512 , num_workers=8 , shuffle=lowerCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __SCREAMING_SNAKE_CASE = [] for batch in dl: __SCREAMING_SNAKE_CASE = batch["input_ids"].ne(lowerCAmelCase_ ).sum(1 ).tolist() __SCREAMING_SNAKE_CASE = batch["labels"].ne(lowerCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCAmelCase_ , lowerCAmelCase_ ): max_lens.append(max(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: max_lens.extend(lowerCAmelCase_ ) return max_lens __SCREAMING_SNAKE_CASE = get_lens(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path="val" , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = get_lens(lowerCAmelCase_ ) pickle_save(lowerCAmelCase_ , train_ds.len_file ) pickle_save(lowerCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
361
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return " ".join( "".join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('''Hey wollef sroirraw'''))
195
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/config.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/config.json", } class lowercase ( UpperCamelCase__ ): _a = "xlnet" _a = ["mems"] _a = { "n_token": "vocab_size", # Backward compatibility "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , _a=3_2000 , _a=1024 , _a=24 , _a=16 , _a=4096 , _a="gelu" , _a=True , _a="bi" , _a=0.02 , _a=1e-12 , _a=0.1 , _a=512 , _a=None , _a=True , _a=False , _a=False , _a=-1 , _a=False , _a="last" , _a=True , _a="tanh" , _a=0.1 , _a=5 , _a=5 , _a=5 , _a=1 , _a=2 , **_a , ) -> Optional[int]: _A : Tuple = vocab_size _A : int = d_model _A : int = n_layer _A : Union[str, Any] = n_head if d_model % n_head != 0: raise ValueError(F'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0''' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F'''`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})''' ) _A : Optional[int] = d_model // n_head _A : Optional[int] = ff_activation _A : Dict = d_inner _A : Union[str, Any] = untie_r _A : Any = attn_type _A : Optional[int] = initializer_range _A : Optional[Any] = layer_norm_eps _A : List[Any] = dropout _A : Optional[Any] = mem_len _A : Union[str, Any] = reuse_len _A : Tuple = bi_data _A : Optional[int] = clamp_len _A : Dict = same_length _A : Dict = summary_type _A : Optional[int] = summary_use_proj _A : Union[str, Any] = summary_activation _A : Optional[Any] = summary_last_dropout _A : str = start_n_top _A : List[Any] = end_n_top _A : List[str] = bos_token_id _A : List[Any] = pad_token_id _A : str = eos_token_id if "use_cache" in kwargs: warnings.warn( """The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`""" """ instead.""" , snake_case__ , ) _A : Dict = kwargs["use_cache"] _A : str = use_mems_eval _A : str = use_mems_train super().__init__(pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ ) @property def a__ ( self ) -> Optional[Any]: logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def a__ ( self , _a ) -> List[str]: raise NotImplementedError( F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
26
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE__ ( lowercase ): """simple docstring""" a : int ="dpr" def __init__( self , snake_case__=30_522 , snake_case__=768 , snake_case__=12 , snake_case__=12 , snake_case__=3_072 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=512 , snake_case__=2 , snake_case__=0.02 , snake_case__=1e-12 , snake_case__=0 , snake_case__="absolute" , snake_case__ = 0 , **snake_case__ , ): """simple docstring""" super().__init__(pad_token_id=snake_case__ , **snake_case__ ) lowerCAmelCase : Union[str, Any] = vocab_size lowerCAmelCase : str = hidden_size lowerCAmelCase : Any = num_hidden_layers lowerCAmelCase : Optional[int] = num_attention_heads lowerCAmelCase : Union[str, Any] = hidden_act lowerCAmelCase : Dict = intermediate_size lowerCAmelCase : Union[str, Any] = hidden_dropout_prob lowerCAmelCase : Dict = attention_probs_dropout_prob lowerCAmelCase : Dict = max_position_embeddings lowerCAmelCase : Tuple = type_vocab_size lowerCAmelCase : Any = initializer_range lowerCAmelCase : Any = layer_norm_eps lowerCAmelCase : Dict = projection_dim lowerCAmelCase : Dict = position_embedding_type
108
0
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="pt" )-> int: """simple docstring""" UpperCamelCase_ = {"add_prefix_space": True} if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and not line.startswith(" " ) else {} UpperCamelCase_ = padding_side return tokenizer( [line] , max_length=SCREAMING_SNAKE_CASE_ , padding="max_length" if pad_to_max_length else None , truncation=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , )-> Tuple: """simple docstring""" UpperCamelCase_ = input_ids.ne(SCREAMING_SNAKE_CASE_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __magic_name__ ( snake_case ): def __init__( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase="train" , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase="" , )-> Dict: super().__init__() UpperCamelCase_ = Path(_lowercase ).joinpath(type_path + ".source" ) UpperCamelCase_ = Path(_lowercase ).joinpath(type_path + ".target" ) UpperCamelCase_ = self.get_char_lens(self.src_file ) UpperCamelCase_ = max_source_length UpperCamelCase_ = max_target_length assert min(self.src_lens ) > 0, F"found empty line in {self.src_file}" UpperCamelCase_ = tokenizer UpperCamelCase_ = prefix if n_obs is not None: UpperCamelCase_ = self.src_lens[:n_obs] UpperCamelCase_ = src_lang UpperCamelCase_ = tgt_lang def __len__( self )-> Tuple: return len(self.src_lens ) def __getitem__( self , _lowercase )-> Dict[str, torch.Tensor]: UpperCamelCase_ = index + 1 # linecache starts at 1 UpperCamelCase_ = self.prefix + linecache.getline(str(self.src_file ) , _lowercase ).rstrip("\n" ) UpperCamelCase_ = linecache.getline(str(self.tgt_file ) , _lowercase ).rstrip("\n" ) assert source_line, F"empty source line for index {index}" assert tgt_line, F"empty tgt line for index {index}" # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowercase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right UpperCamelCase_ = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowercase ) else self.tokenizer ) UpperCamelCase_ = self.tokenizer.generator if isinstance(self.tokenizer , _lowercase ) else self.tokenizer UpperCamelCase_ = encode_line(_lowercase , _lowercase , self.max_source_length , "right" ) UpperCamelCase_ = encode_line(_lowercase , _lowercase , self.max_target_length , "right" ) UpperCamelCase_ = source_inputs["input_ids"].squeeze() UpperCamelCase_ = target_inputs["input_ids"].squeeze() UpperCamelCase_ = source_inputs["attention_mask"].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def UpperCAmelCase_ ( _lowercase )-> Any: return [len(_lowercase ) for x in Path(_lowercase ).open().readlines()] def UpperCAmelCase_ ( self , _lowercase )-> Dict[str, torch.Tensor]: UpperCamelCase_ = torch.stack([x["input_ids"] for x in batch] ) UpperCamelCase_ = torch.stack([x["attention_mask"] for x in batch] ) UpperCamelCase_ = torch.stack([x["decoder_input_ids"] for x in batch] ) UpperCamelCase_ = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowercase ) else self.tokenizer.pad_token_id ) UpperCamelCase_ = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowercase ) else self.tokenizer.pad_token_id ) UpperCamelCase_ = trim_batch(_lowercase , _lowercase ) UpperCamelCase_ , UpperCamelCase_ = trim_batch(_lowercase , _lowercase , attention_mask=_lowercase ) UpperCamelCase_ = { "input_ids": source_ids, "attention_mask": source_mask, "decoder_input_ids": y, } return batch SCREAMING_SNAKE_CASE :List[str] = getLogger(__name__) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> Optional[Any]: """simple docstring""" return list(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_ ) ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> None: """simple docstring""" UpperCamelCase_ = get_git_info() save_json(SCREAMING_SNAKE_CASE_ , os.path.join(SCREAMING_SNAKE_CASE_ , "git_log.json" ) ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=4 , **SCREAMING_SNAKE_CASE_ )-> Tuple: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , indent=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> int: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ ) as f: return json.load(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase( )-> str: """simple docstring""" UpperCamelCase_ = git.Repo(search_parent_directories=SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = { "repo_id": str(SCREAMING_SNAKE_CASE_ ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), "hostname": str(socket.gethostname() ), } return repo_infos def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> List: """simple docstring""" return list(map(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> int: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: return pickle.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> Tuple: """simple docstring""" def remove_articles(SCREAMING_SNAKE_CASE_ ): return re.sub(r"\b(a|an|the)\b" , " " , SCREAMING_SNAKE_CASE_ ) def white_space_fix(SCREAMING_SNAKE_CASE_ ): return " ".join(text.split() ) def remove_punc(SCREAMING_SNAKE_CASE_ ): UpperCamelCase_ = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(SCREAMING_SNAKE_CASE_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE_ ) ) ) ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> Union[str, Any]: """simple docstring""" UpperCamelCase_ = normalize_answer(SCREAMING_SNAKE_CASE_ ).split() UpperCamelCase_ = normalize_answer(SCREAMING_SNAKE_CASE_ ).split() UpperCamelCase_ = Counter(SCREAMING_SNAKE_CASE_ ) & Counter(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = sum(common.values() ) if num_same == 0: return 0 UpperCamelCase_ = 1.0 * num_same / len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = 1.0 * num_same / len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> Tuple: """simple docstring""" return normalize_answer(SCREAMING_SNAKE_CASE_ ) == normalize_answer(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> Dict: """simple docstring""" assert len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = 0 for hypo, pred in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): em += exact_match_score(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: em /= len(SCREAMING_SNAKE_CASE_ ) return {"em": em} def lowerCAmelCase( SCREAMING_SNAKE_CASE_ )-> Dict: """simple docstring""" return model_prefix.startswith("rag" ) def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )-> Optional[int]: """simple docstring""" UpperCamelCase_ = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead UpperCamelCase_ = "dropout_rate" for p in extra_params: if getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and not hasattr(SCREAMING_SNAKE_CASE_ , equivalent_param[p] ): logger.info("config doesn't have a `{}` attribute".format(SCREAMING_SNAKE_CASE_ ) ) delattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) continue UpperCamelCase_ = p if hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else equivalent_param[p] setattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) delattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return hparams, config
60
def lowerCAmelCase( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False )-> str: """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase_ = f"Expected string as input, found {type(SCREAMING_SNAKE_CASE_ )}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase_ = f"Expected boolean as use_pascal parameter, found {type(SCREAMING_SNAKE_CASE_ )}" raise ValueError(SCREAMING_SNAKE_CASE_ ) UpperCamelCase_ = input_str.split("_" ) UpperCamelCase_ = 0 if use_pascal else 1 UpperCamelCase_ = words[start_index:] UpperCamelCase_ = [word[0].upper() + word[1:] for word in words_to_capitalize] UpperCamelCase_ = "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
60
1
'''simple docstring''' import os def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =len(grid[0] ) _SCREAMING_SNAKE_CASE =len(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(_UpperCamelCase ): for j in range(n_rows - 3 ): _SCREAMING_SNAKE_CASE =grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] _SCREAMING_SNAKE_CASE =grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: _SCREAMING_SNAKE_CASE =( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: _SCREAMING_SNAKE_CASE =( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) _SCREAMING_SNAKE_CASE =max( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if max_product > largest: _SCREAMING_SNAKE_CASE =max_product return largest def _lowerCAmelCase ( ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE =[] with open(os.path.dirname(_UpperCamelCase ) + '/grid.txt' ) as file: for line in file: grid.append(line.strip('\n' ).split(' ' ) ) _SCREAMING_SNAKE_CASE =[[int(_UpperCamelCase ) for i in grid[j]] for j in range(len(_UpperCamelCase ) )] return largest_product(_UpperCamelCase ) if __name__ == "__main__": print(solution())
47
'''simple docstring''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : str = { "huggingface/time-series-transformer-tourism-monthly": ( "https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json" ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( A__ ): A__ = 'time_series_transformer' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[int] , _a : Optional[int] = None , _a : Optional[int] = None , _a : str = "student_t" , _a : str = "nll" , _a : int = 1 , _a : List[int] = [1, 2, 3, 4, 5, 6, 7] , _a : Optional[Union[str, bool]] = "mean" , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : int = 0 , _a : Optional[List[int]] = None , _a : Optional[List[int]] = None , _a : int = 32 , _a : int = 32 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : int = 2 , _a : bool = True , _a : str = "gelu" , _a : int = 64 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : float = 0.1 , _a : int = 100 , _a : float = 0.02 , _a : Union[str, Any]=True , **_a : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =prediction_length _SCREAMING_SNAKE_CASE =context_length or prediction_length _SCREAMING_SNAKE_CASE =distribution_output _SCREAMING_SNAKE_CASE =loss _SCREAMING_SNAKE_CASE =input_size _SCREAMING_SNAKE_CASE =num_time_features _SCREAMING_SNAKE_CASE =lags_sequence _SCREAMING_SNAKE_CASE =scaling _SCREAMING_SNAKE_CASE =num_dynamic_real_features _SCREAMING_SNAKE_CASE =num_static_real_features _SCREAMING_SNAKE_CASE =num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(_a ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) _SCREAMING_SNAKE_CASE =cardinality else: _SCREAMING_SNAKE_CASE =[0] if embedding_dimension and num_static_categorical_features > 0: if len(_a ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) _SCREAMING_SNAKE_CASE =embedding_dimension else: _SCREAMING_SNAKE_CASE =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] _SCREAMING_SNAKE_CASE =num_parallel_samples # Transformer architecture configuration _SCREAMING_SNAKE_CASE =input_size * len(_a ) + self._number_of_features _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =decoder_layerdrop _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =use_cache super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : List[Any] ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
47
1
'''simple docstring''' # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : Dict = 42 lowerCAmelCase_ : List[Any] = None def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str=0.9_99 , SCREAMING_SNAKE_CASE__ : Union[str, Any]="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(SCREAMING_SNAKE_CASE__ : List[str] ): return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(SCREAMING_SNAKE_CASE__ : Dict ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) UpperCAmelCase__ = [] for i in range(a__ ): UpperCAmelCase__ = i / num_diffusion_timesteps UpperCAmelCase__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a__ ) / alpha_bar_fn(a__ ) , a__ ) ) return torch.tensor(a__ , dtype=torch.floataa ) class lowerCAmelCase_ ( lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : Tuple = 1 @register_to_config def __init__( self : int , _UpperCAmelCase : Optional[Any] = 10_00 , _UpperCAmelCase : List[Any] = 0.0001 , _UpperCAmelCase : Union[str, Any] = 0.02 , _UpperCAmelCase : Dict = "linear" , _UpperCAmelCase : List[str] = None , _UpperCAmelCase : Optional[Any] = True , _UpperCAmelCase : Any = True , _UpperCAmelCase : int = 0 , _UpperCAmelCase : Optional[Any] = "epsilon" , _UpperCAmelCase : Dict = 1.0 , **_UpperCAmelCase : Optional[int] , ): """simple docstring""" if kwargs.get("""set_alpha_to_one""" , _snake_case ) is not None: UpperCAmelCase__ = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , _snake_case , standard_warn=_snake_case ) UpperCAmelCase__ = kwargs["""set_alpha_to_one"""] if trained_betas is not None: UpperCAmelCase__ = torch.tensor(_snake_case , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase__ = torch.linspace(_snake_case , _snake_case , _snake_case , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase__ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , _snake_case , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase__ = betas_for_alpha_bar(_snake_case ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) UpperCAmelCase__ = 1.0 - self.betas UpperCAmelCase__ = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. UpperCAmelCase__ = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution UpperCAmelCase__ = 1.0 # setable values UpperCAmelCase__ = None UpperCAmelCase__ = torch.from_numpy(np.arange(0 , _snake_case ).copy().astype(np.intaa ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple = None ): """simple docstring""" return sample def SCREAMING_SNAKE_CASE__ ( self : Tuple , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Optional[Any] = None ): """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) UpperCAmelCase__ = num_inference_steps UpperCAmelCase__ = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 UpperCAmelCase__ = (np.arange(0 , _snake_case ) * step_ratio).round().copy().astype(np.intaa ) UpperCAmelCase__ = torch.from_numpy(_snake_case ).to(_snake_case ) self.timesteps += self.config.steps_offset def SCREAMING_SNAKE_CASE__ ( self : Dict , _UpperCAmelCase : List[Any] , _UpperCAmelCase : List[str] , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : str = 0.0 , _UpperCAmelCase : Dict = False , _UpperCAmelCase : Union[str, Any] = None , _UpperCAmelCase : Optional[Any] = True , ): """simple docstring""" UpperCAmelCase__ = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process UpperCAmelCase__ = self.alphas_cumprod[timestep] UpperCAmelCase__ = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) UpperCAmelCase__ = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": UpperCAmelCase__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 UpperCAmelCase__ = model_output elif self.config.prediction_type == "sample": UpperCAmelCase__ = model_output UpperCAmelCase__ = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": UpperCAmelCase__ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output UpperCAmelCase__ = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: UpperCAmelCase__ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCAmelCase__ = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCAmelCase__ = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=_snake_case , pred_original_sample=_snake_case ) def __len__( self : Any ): """simple docstring""" return self.config.num_train_timesteps
361
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : set ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ), len(grid[0] ) if ( min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) UpperCAmelCase__ = 0 count += depth_first_search(SCREAMING_SNAKE_CASE__ , row + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) count += depth_first_search(SCREAMING_SNAKE_CASE__ , row - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) count += depth_first_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , col + 1 , SCREAMING_SNAKE_CASE__ ) count += depth_first_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , col - 1 , SCREAMING_SNAKE_CASE__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
61
0
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase__ : '''simple docstring''' def __init__( self, __magic_name__, __magic_name__=13, __magic_name__=30, __magic_name__=2, __magic_name__=3, __magic_name__=True, __magic_name__=True, __magic_name__=32, __magic_name__=5, __magic_name__=4, __magic_name__=37, __magic_name__="gelu", __magic_name__=0.1, __magic_name__=0.1, __magic_name__=10, __magic_name__=0.02, __magic_name__=None, __magic_name__=2, ) -> Tuple: """simple docstring""" UpperCamelCase__ : List[Any] = parent UpperCamelCase__ : Tuple = batch_size UpperCamelCase__ : Any = image_size UpperCamelCase__ : List[str] = patch_size UpperCamelCase__ : int = num_channels UpperCamelCase__ : str = is_training UpperCamelCase__ : Optional[int] = use_labels UpperCamelCase__ : int = hidden_size UpperCamelCase__ : Optional[Any] = num_hidden_layers UpperCamelCase__ : Optional[Any] = num_attention_heads UpperCamelCase__ : Dict = intermediate_size UpperCamelCase__ : Optional[int] = hidden_act UpperCamelCase__ : List[str] = hidden_dropout_prob UpperCamelCase__ : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase__ : Any = type_sequence_label_size UpperCamelCase__ : Optional[Any] = initializer_range UpperCamelCase__ : List[str] = scope UpperCamelCase__ : Dict = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ : Optional[int] = (image_size // patch_size) ** 2 UpperCamelCase__ : Any = num_patches + 1 def UpperCamelCase__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ : Optional[int] = None if self.use_labels: UpperCamelCase__ : Tuple = ids_tensor([self.batch_size], self.type_sequence_label_size ) UpperCamelCase__ : Dict = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" return ViTConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=UpperCAmelCase__, initializer_range=self.initializer_range, encoder_stride=self.encoder_stride, ) def UpperCamelCase__ ( self, __magic_name__, __magic_name__, __magic_name__ ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : int = ViTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() UpperCamelCase__ : Tuple = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self, __magic_name__, __magic_name__, __magic_name__ ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : List[str] = ViTForMaskedImageModeling(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() UpperCamelCase__ : Any = model(UpperCAmelCase__ ) self.parent.assertEqual( result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase__ : List[str] = 1 UpperCamelCase__ : int = ViTForMaskedImageModeling(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() UpperCamelCase__ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ : Dict = model(UpperCAmelCase__ ) self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase__ ( self, __magic_name__, __magic_name__, __magic_name__ ) -> Tuple: """simple docstring""" UpperCamelCase__ : Any = self.type_sequence_label_size UpperCamelCase__ : Union[str, Any] = ViTForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() UpperCamelCase__ : Optional[int] = model(UpperCAmelCase__, labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ : Optional[Any] = 1 UpperCamelCase__ : Optional[Any] = ViTForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() UpperCamelCase__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ : Tuple = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase__ ( self ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : List[str] = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) ,( UpperCamelCase__ ) ,( UpperCamelCase__ ) , ) : List[str] = config_and_inputs UpperCamelCase__ : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowercase__ ( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' a : Optional[Any] = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) a : Union[str, Any] = ( {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification} if is_torch_available() else {} ) a : int = True a : str = False a : List[str] = False a : Optional[int] = False def UpperCamelCase__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase__ : List[Any] = ViTModelTester(self ) UpperCamelCase__ : Tuple = ConfigTester(self, config_class=UpperCAmelCase__, has_text_modality=UpperCAmelCase__, hidden_size=37 ) def UpperCamelCase__ ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" pass def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase__ ,UpperCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ : Any = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) UpperCamelCase__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__, nn.Linear ) ) def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase__ ,UpperCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ : Any = model_class(UpperCAmelCase__ ) UpperCamelCase__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ : Optional[Any] = [*signature.parameters.keys()] UpperCamelCase__ : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1], UpperCAmelCase__ ) def UpperCamelCase__ ( self ) -> Any: """simple docstring""" UpperCamelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCamelCase__ ( self ) -> Any: """simple docstring""" UpperCamelCase__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__ ) def UpperCamelCase__ ( self ) -> Tuple: """simple docstring""" UpperCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @slow def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ : Dict = ViTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def lowerCAmelCase_ ( ) -> List[Any]: UpperCamelCase__ : Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowercase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None @slow def UpperCamelCase__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : int = ViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' ).to(UpperCAmelCase__ ) UpperCamelCase__ : str = self.default_image_processor UpperCamelCase__ : int = prepare_img() UpperCamelCase__ : Optional[int] = image_processor(images=UpperCAmelCase__, return_tensors='''pt''' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): UpperCamelCase__ : Union[str, Any] = model(**UpperCAmelCase__ ) # verify the logits UpperCamelCase__ : Dict = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape, UpperCAmelCase__ ) UpperCamelCase__ : List[str] = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3], UpperCAmelCase__, atol=1E-4 ) ) @slow def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. UpperCamelCase__ : Dict = ViTModel.from_pretrained('''facebook/dino-vits8''' ).to(UpperCAmelCase__ ) UpperCamelCase__ : Optional[Any] = ViTImageProcessor.from_pretrained('''facebook/dino-vits8''', size=480 ) UpperCamelCase__ : Tuple = prepare_img() UpperCamelCase__ : Union[str, Any] = image_processor(images=UpperCAmelCase__, return_tensors='''pt''' ) UpperCamelCase__ : int = inputs.pixel_values.to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): UpperCamelCase__ : Dict = model(UpperCAmelCase__, interpolate_pos_encoding=UpperCAmelCase__ ) # verify the logits UpperCamelCase__ : Dict = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape, UpperCAmelCase__ ) UpperCamelCase__ : str = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], UpperCAmelCase__, atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" UpperCamelCase__ : Any = ViTModel.from_pretrained('''facebook/dino-vits8''', torch_dtype=torch.floataa, device_map='''auto''' ) UpperCamelCase__ : Optional[Any] = self.default_image_processor UpperCamelCase__ : List[str] = prepare_img() UpperCamelCase__ : Optional[int] = image_processor(images=UpperCAmelCase__, return_tensors='''pt''' ) UpperCamelCase__ : Optional[int] = inputs.pixel_values.to(UpperCAmelCase__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): UpperCamelCase__ : Any = model(UpperCAmelCase__ )
201
'''simple docstring''' class UpperCAmelCase_ : def __init__( self : List[str] , UpperCAmelCase__ : list[int] ) -> None: lowerCAmelCase = len(UpperCAmelCase__ ) lowerCAmelCase = [0] * len_array if len_array > 0: lowerCAmelCase = array[0] for i in range(1 , UpperCAmelCase__ ): lowerCAmelCase = self.prefix_sum[i - 1] + array[i] def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> int: if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __UpperCAmelCase ( self : int , UpperCAmelCase__ : int ) -> bool: lowerCAmelCase = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(UpperCAmelCase__ ) return False if __name__ == "__main__": import doctest doctest.testmod()
4
0
"""simple docstring""" import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __snake_case ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" _lowerCamelCase = RobertaTokenizer _lowerCamelCase = RobertaTokenizerFast _lowerCamelCase = True _lowerCamelCase = {"""cls_token""": """<s>"""} def UpperCamelCase__( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __A : List[str] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', ] __A : int = dict(zip(__lowerCamelCase , range(len(__lowerCamelCase ) ) ) ) __A : str = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] __A : Dict = {'''unk_token''': '''<unk>'''} __A : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __A : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__lowerCamelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__lowerCamelCase ) ) def UpperCamelCase__( self , **__lowerCamelCase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def UpperCamelCase__( self , **__lowerCamelCase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCamelCase ) def UpperCamelCase__( self , __lowerCamelCase ): '''simple docstring''' __A : str = '''lower newer''' __A : int = '''lower newer''' return input_text, output_text def UpperCamelCase__( self ): '''simple docstring''' __A : Tuple = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) __A : List[Any] = '''lower newer''' __A : int = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] __A : List[Any] = tokenizer.tokenize(__lowerCamelCase ) # , add_prefix_space=True) self.assertListEqual(__lowerCamelCase , __lowerCamelCase ) __A : str = tokens + [tokenizer.unk_token] __A : Any = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , __lowerCamelCase ) def UpperCamelCase__( self ): '''simple docstring''' __A : Union[str, Any] = self.get_tokenizer() self.assertListEqual(tokenizer.encode('''Hello world!''' , add_special_tokens=__lowerCamelCase ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode('''Hello world! cécé herlolip 418''' , add_special_tokens=__lowerCamelCase ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def UpperCamelCase__( self ): '''simple docstring''' __A : Dict = self.tokenizer_class.from_pretrained('''roberta-base''' ) __A : Union[str, Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=__lowerCamelCase ) __A : Union[str, Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__lowerCamelCase ) __A : List[Any] = tokenizer.encode( '''sequence builders''' , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) __A : Tuple = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) __A : str = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase ) __A : List[Any] = tokenizer.build_inputs_with_special_tokens(__lowerCamelCase , __lowerCamelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCamelCase__( self ): '''simple docstring''' __A : Tuple = self.get_tokenizer() __A : Union[str, Any] = '''Encode this sequence.''' __A : Optional[Any] = tokenizer.byte_encoder[''' '''.encode('''utf-8''' )[0]] # Testing encoder arguments __A : List[Any] = tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) __A : int = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__lowerCamelCase , __lowerCamelCase ) __A : Tuple = tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase , add_prefix_space=__lowerCamelCase ) __A : str = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) tokenizer.add_special_tokens({'''bos_token''': '''<s>'''} ) __A : int = tokenizer.encode(__lowerCamelCase , add_special_tokens=__lowerCamelCase ) __A : List[Any] = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__lowerCamelCase , __lowerCamelCase ) # Testing spaces after special tokens __A : Any = '''<mask>''' tokenizer.add_special_tokens( {'''mask_token''': AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase )} ) # mask token has a left space __A : Union[str, Any] = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) __A : Tuple = '''Encode <mask> sequence''' __A : str = '''Encode <mask>sequence''' __A : Optional[Any] = tokenizer.encode(__lowerCamelCase ) __A : Dict = encoded.index(__lowerCamelCase ) __A : Any = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) __A : Dict = tokenizer.encode(__lowerCamelCase ) __A : List[Any] = encoded.index(__lowerCamelCase ) __A : Union[str, Any] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__lowerCamelCase , __lowerCamelCase ) def UpperCamelCase__( self ): '''simple docstring''' pass def UpperCamelCase__( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __A : str = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) __A : List[Any] = self.tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) __A : List[Any] = '''A, <mask> AllenNLP sentence.''' __A : Union[str, Any] = tokenizer_r.encode_plus(__lowerCamelCase , add_special_tokens=__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) __A : Any = tokenizer_p.encode_plus(__lowerCamelCase , add_special_tokens=__lowerCamelCase , return_token_type_ids=__lowerCamelCase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['''token_type_ids'''] ) , sum(tokens_p['''token_type_ids'''] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['''attention_mask'''] ) / len(tokens_r['''attention_mask'''] ) , sum(tokens_p['''attention_mask'''] ) / len(tokens_p['''attention_mask'''] ) , ) __A : Tuple = tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''] ) __A : Dict = tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['''input_ids'''] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r['''input_ids'''] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( __lowerCamelCase , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) self.assertSequenceEqual( __lowerCamelCase , ['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''] ) def UpperCamelCase__( self ): '''simple docstring''' for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): __A : str = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : List[Any] = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) __A : List[Any] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] , __lowerCamelCase ) self.assertEqual(post_processor_state['''add_prefix_space'''] , __lowerCamelCase ) self.assertEqual(post_processor_state['''trim_offsets'''] , __lowerCamelCase ) def UpperCamelCase__( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __A : Optional[int] = '''hello''' # `hello` is a token in the vocabulary of `pretrained_name` __A : str = F"""{text_of_1_token} {text_of_1_token}""" __A : int = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : List[Any] = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__lowerCamelCase ) + 1, len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , ) __A : List[str] = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : Tuple = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__lowerCamelCase ) + 1, len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , ) __A : int = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : List[Any] = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__lowerCamelCase ), len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , ) __A : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : List[Any] = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__lowerCamelCase ), len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , ) __A : List[Any] = F""" {text}""" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) __A : Optional[int] = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : Optional[int] = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__lowerCamelCase ) + 1, 1 + len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , ) __A : List[str] = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : Optional[Any] = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__lowerCamelCase ), 1 + len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , ) __A : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __lowerCamelCase , use_fast=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase ) __A : Optional[Any] = tokenizer_r(__lowerCamelCase , return_offsets_mapping=__lowerCamelCase , add_special_tokens=__lowerCamelCase ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__lowerCamelCase )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__lowerCamelCase ), 1 + len(__lowerCamelCase ) + 1 + len(__lowerCamelCase )) , )
359
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def __lowercase ( snake_case_ : int ) ->str: '''simple docstring''' if not isinstance(snake_case_ ,snake_case_ ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: raise ValueError('''Undefined for non-natural numbers''' ) __A : int = precision __A : Tuple = ceil(precision / 14 ) __A : Dict = 426880 * Decimal(10005 ).sqrt() __A : Optional[Any] = 1 __A : int = 13591409 __A : Optional[int] = Decimal(snake_case_ ) for k in range(1 ,snake_case_ ): __A : int = factorial(6 * k ) // (factorial(3 * k ) * factorial(snake_case_ ) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a_ = 50 print(f'''The first {n} digits of pi is: {pi(n)}''')
291
0
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowerCamelCase_ : int = logging.getLogger(__name__) if __name__ == "__main__": lowerCamelCase_ : Any = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=3_0_5_2_2, type=int) lowerCamelCase_ : int = parser.parse_args() logger.info(F'Loading data from {args.data_file}') with open(args.data_file, """rb""") as fp: lowerCamelCase_ : Optional[int] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowerCamelCase_ : Optional[int] = Counter() for tk_ids in data: counter.update(tk_ids) lowerCamelCase_ : Dict = [0] * args.vocab_size for k, v in counter.items(): lowerCamelCase_ : Any = v logger.info(F'Dump to {args.token_counts_dump}') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
81
"""simple docstring""" def _A ( ): """simple docstring""" for n in range(1 , 1_00_00_00 ): yield n * (n + 1) // 2 def _A ( lowercase ): """simple docstring""" a =1 a =2 while i * i <= n: a =0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowercase ) > 5_00 ) if __name__ == "__main__": print(solution())
81
1
"""simple docstring""" import argparse import glob import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback from torch import nn from torch.utils.data import DataLoader from transformers import MBartTokenizer, TaForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from utils import ( ROUGE_KEYS, LegacySeqaSeqDataset, SeqaSeqDataset, assert_all_frozen, calculate_bleu, calculate_rouge, check_output_dir, flatten_list, freeze_embeds, freeze_params, get_git_info, label_smoothed_nll_loss, lmap, pickle_save, save_git_info, save_json, use_task_specific_params, ) # need the parent dir module sys.path.insert(2, str(Path(__file__).resolve().parents[1])) from lightning_base import BaseTransformer, add_generic_args, generic_train # noqa lowercase__ = logging.getLogger(__name__) class __lowerCamelCase ( A__ ): '''simple docstring''' a_ : Union[str, Any] = """summarization""" a_ : List[str] = ["""loss"""] a_ : Union[str, Any] = ROUGE_KEYS a_ : Dict = """rouge2""" def __init__( self : List[str] , a_ : Any , **a_ : Any ): if hparams.sortish_sampler and hparams.gpus > 1: lowerCAmelCase_ : Tuple = False elif hparams.max_tokens_per_batch is not None: if hparams.gpus > 1: raise NotImplementedError("Dynamic Batch size does not work for multi-gpu training" ) if hparams.sortish_sampler: raise ValueError("--sortish_sampler and --max_tokens_per_batch may not be used simultaneously" ) super().__init__(a_ , num_labels=a_ , mode=self.mode , **a_ ) use_task_specific_params(self.model , "summarization" ) save_git_info(self.hparams.output_dir ) lowerCAmelCase_ : str = Path(self.output_dir ) / "metrics.json" lowerCAmelCase_ : Optional[int] = Path(self.output_dir ) / "hparams.pkl" pickle_save(self.hparams , self.hparams_save_path ) lowerCAmelCase_ : Tuple = 0 lowerCAmelCase_ : int = defaultdict(a_ ) lowerCAmelCase_ : Dict = self.config.model_type lowerCAmelCase_ : List[str] = self.config.tgt_vocab_size if self.model_type == "fsmt" else self.config.vocab_size lowerCAmelCase_ : dict = { "data_dir": self.hparams.data_dir, "max_source_length": self.hparams.max_source_length, "prefix": self.model.config.prefix or "", } lowerCAmelCase_ : Tuple = { "train": self.hparams.n_train, "val": self.hparams.n_val, "test": self.hparams.n_test, } lowerCAmelCase_ : Dict = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()} lowerCAmelCase_ : Any = { "train": self.hparams.max_target_length, "val": self.hparams.val_max_target_length, "test": self.hparams.test_max_target_length, } assert self.target_lens["train"] <= self.target_lens["val"], f'''target_lens: {self.target_lens}''' assert self.target_lens["train"] <= self.target_lens["test"], f'''target_lens: {self.target_lens}''' if self.hparams.freeze_embeds: freeze_embeds(self.model ) if self.hparams.freeze_encoder: freeze_params(self.model.get_encoder() ) assert_all_frozen(self.model.get_encoder() ) lowerCAmelCase_ : Optional[int] = get_git_info()["repo_sha"] lowerCAmelCase_ : List[str] = hparams.num_workers lowerCAmelCase_ : List[str] = None # default to config if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer , a_ ): lowerCAmelCase_ : Union[str, Any] = self.tokenizer.lang_code_to_id[hparams.tgt_lang] lowerCAmelCase_ : Any = self.decoder_start_token_id lowerCAmelCase_ : List[Any] = ( SeqaSeqDataset if hasattr(self.tokenizer , "prepare_seq2seq_batch" ) else LegacySeqaSeqDataset ) lowerCAmelCase_ : Union[str, Any] = False lowerCAmelCase_ : Dict = self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams if self.hparams.eval_max_gen_length is not None: lowerCAmelCase_ : Dict = self.hparams.eval_max_gen_length else: lowerCAmelCase_ : Optional[int] = self.model.config.max_length lowerCAmelCase_ : List[Any] = self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric def lowerCamelCase ( self : List[str] , a_ : Dict[str, torch.Tensor] ): lowerCAmelCase_ : Any = { k: self.tokenizer.batch_decode(v.tolist() ) if "mask" not in k else v.shape for k, v in batch.items() } save_json(a_ , Path(self.output_dir ) / "text_batch.json" ) save_json({k: v.tolist() for k, v in batch.items()} , Path(self.output_dir ) / "tok_batch.json" ) lowerCAmelCase_ : Optional[int] = True return readable_batch def lowerCamelCase ( self : List[str] , a_ : List[str] , **a_ : Tuple ): return self.model(a_ , **a_ ) def lowerCamelCase ( self : Any , a_ : List[int] ): lowerCAmelCase_ : Dict = self.tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) return lmap(str.strip , a_ ) def lowerCamelCase ( self : Union[str, Any] , a_ : dict ): lowerCAmelCase_ : str = self.tokenizer.pad_token_id lowerCAmelCase_ , lowerCAmelCase_ : int = batch["input_ids"], batch["attention_mask"] lowerCAmelCase_ : Optional[Any] = batch["labels"] if isinstance(self.model , a_ ): lowerCAmelCase_ : int = self.model._shift_right(a_ ) else: lowerCAmelCase_ : Union[str, Any] = shift_tokens_right(a_ , a_ ) if not self.already_saved_batch: # This would be slightly better if it only happened on rank zero lowerCAmelCase_ : Union[str, Any] = decoder_input_ids self.save_readable_batch(a_ ) lowerCAmelCase_ : Union[str, Any] = self(a_ , attention_mask=a_ , decoder_input_ids=a_ , use_cache=a_ ) lowerCAmelCase_ : Optional[Any] = outputs["logits"] if self.hparams.label_smoothing == 0: # Same behavior as modeling_bart.py, besides ignoring pad_token_id lowerCAmelCase_ : Dict = nn.CrossEntropyLoss(ignore_index=a_ ) assert lm_logits.shape[-1] == self.vocab_size lowerCAmelCase_ : Any = ce_loss_fct(lm_logits.view(-1 , lm_logits.shape[-1] ) , tgt_ids.view(-1 ) ) else: lowerCAmelCase_ : Dict = nn.functional.log_softmax(a_ , dim=-1 ) lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = label_smoothed_nll_loss( a_ , a_ , self.hparams.label_smoothing , ignore_index=a_ ) return (loss,) @property def lowerCamelCase ( self : str ): return self.tokenizer.pad_token_id def lowerCamelCase ( self : List[str] , a_ : Optional[Any] , a_ : Union[str, Any] ): lowerCAmelCase_ : Optional[Any] = self._step(a_ ) lowerCAmelCase_ : Dict = dict(zip(self.loss_names , a_ ) ) # tokens per batch lowerCAmelCase_ : List[Any] = batch["input_ids"].ne(self.pad ).sum() + batch["labels"].ne(self.pad ).sum() lowerCAmelCase_ : Tuple = batch["input_ids"].shape[0] lowerCAmelCase_ : Optional[Any] = batch["input_ids"].eq(self.pad ).sum() lowerCAmelCase_ : Tuple = batch["input_ids"].eq(self.pad ).float().mean() # TODO(SS): make a wandb summary metric for this return {"loss": loss_tensors[0], "log": logs} def lowerCamelCase ( self : Tuple , a_ : Union[str, Any] , a_ : Union[str, Any] ): return self._generative_step(a_ ) def lowerCamelCase ( self : str , a_ : Tuple , a_ : Dict="val" ): self.step_count += 1 lowerCAmelCase_ : Optional[int] = {k: torch.stack([x[k] for x in outputs] ).mean() for k in self.loss_names} lowerCAmelCase_ : Dict = losses["loss"] lowerCAmelCase_ : Optional[int] = { k: np.array([x[k] for x in outputs] ).mean() for k in self.metric_names + ["gen_time", "gen_len"] } lowerCAmelCase_ : List[Any] = ( generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric] ) lowerCAmelCase_ : torch.FloatTensor = torch.tensor(a_ ).type_as(a_ ) generative_metrics.update({k: v.item() for k, v in losses.items()} ) losses.update(a_ ) lowerCAmelCase_ : int = {f'''{prefix}_avg_{k}''': x for k, x in losses.items()} lowerCAmelCase_ : Optional[Any] = self.step_count self.metrics[prefix].append(a_ ) # callback writes this to self.metrics_save_path lowerCAmelCase_ : Dict = flatten_list([x["preds"] for x in outputs] ) return { "log": all_metrics, "preds": preds, f'''{prefix}_loss''': loss, f'''{prefix}_{self.val_metric}''': metric_tensor, } def lowerCamelCase ( self : str , a_ : Optional[int] , a_ : Optional[Any] ): return calculate_rouge(a_ , a_ ) def lowerCamelCase ( self : Tuple , a_ : dict ): lowerCAmelCase_ : Any = time.time() # parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens') lowerCAmelCase_ : Optional[int] = self.model.generate( batch["input_ids"] , attention_mask=batch["attention_mask"] , use_cache=a_ , decoder_start_token_id=self.decoder_start_token_id , num_beams=self.eval_beams , max_length=self.eval_max_length , ) lowerCAmelCase_ : List[str] = (time.time() - ta) / batch["input_ids"].shape[0] lowerCAmelCase_ : List[str] = self.ids_to_clean_text(a_ ) lowerCAmelCase_ : List[str] = self.ids_to_clean_text(batch["labels"] ) lowerCAmelCase_ : Optional[int] = self._step(a_ ) lowerCAmelCase_ : Union[str, Any] = dict(zip(self.loss_names , a_ ) ) lowerCAmelCase_ : Dict = self.calc_generative_metrics(a_ , a_ ) lowerCAmelCase_ : str = np.mean(lmap(a_ , a_ ) ) base_metrics.update(gen_time=a_ , gen_len=a_ , preds=a_ , target=a_ , **a_ ) return base_metrics def lowerCamelCase ( self : Tuple , a_ : int , a_ : List[str] ): return self._generative_step(a_ ) def lowerCamelCase ( self : str , a_ : Optional[int] ): return self.validation_epoch_end(a_ , prefix="test" ) def lowerCamelCase ( self : Tuple , a_ : Tuple ): lowerCAmelCase_ : Optional[int] = self.n_obs[type_path] lowerCAmelCase_ : Optional[int] = self.target_lens[type_path] lowerCAmelCase_ : int = self.dataset_class( self.tokenizer , type_path=a_ , n_obs=a_ , max_target_length=a_ , **self.dataset_kwargs , ) return dataset def lowerCamelCase ( self : List[Any] , a_ : str , a_ : int , a_ : bool = False ): lowerCAmelCase_ : List[Any] = self.get_dataset(a_ ) if self.hparams.sortish_sampler and type_path != "test" and type_path != "val": lowerCAmelCase_ : Dict = dataset.make_sortish_sampler(a_ , distributed=self.hparams.gpus > 1 ) return DataLoader( a_ , batch_size=a_ , collate_fn=dataset.collate_fn , shuffle=a_ , num_workers=self.num_workers , sampler=a_ , ) elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val": lowerCAmelCase_ : Tuple = dataset.make_dynamic_sampler( self.hparams.max_tokens_per_batch , distributed=self.hparams.gpus > 1 ) return DataLoader( a_ , batch_sampler=a_ , collate_fn=dataset.collate_fn , num_workers=self.num_workers , ) else: return DataLoader( a_ , batch_size=a_ , collate_fn=dataset.collate_fn , shuffle=a_ , num_workers=self.num_workers , sampler=a_ , ) def lowerCamelCase ( self : int ): lowerCAmelCase_ : List[str] = self.get_dataloader("train" , batch_size=self.hparams.train_batch_size , shuffle=a_ ) return dataloader def lowerCamelCase ( self : Tuple ): return self.get_dataloader("val" , batch_size=self.hparams.eval_batch_size ) def lowerCamelCase ( self : int ): return self.get_dataloader("test" , batch_size=self.hparams.eval_batch_size ) @staticmethod def lowerCamelCase ( a_ : Union[str, Any] , a_ : Tuple ): BaseTransformer.add_model_specific_args(a_ , a_ ) add_generic_args(a_ , a_ ) parser.add_argument( "--max_source_length" , default=10_24 , type=a_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--max_target_length" , default=56 , type=a_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--val_max_target_length" , default=1_42 , type=a_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--test_max_target_length" , default=1_42 , type=a_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument("--freeze_encoder" , action="store_true" ) parser.add_argument("--freeze_embeds" , action="store_true" ) parser.add_argument("--sortish_sampler" , action="store_true" , default=a_ ) parser.add_argument("--overwrite_output_dir" , action="store_true" , default=a_ ) parser.add_argument("--max_tokens_per_batch" , type=a_ , default=a_ ) parser.add_argument("--logger_name" , type=a_ , choices=["default", "wandb", "wandb_shared"] , default="default" ) parser.add_argument("--n_train" , type=a_ , default=-1 , required=a_ , help="# examples. -1 means use all." ) parser.add_argument("--n_val" , type=a_ , default=5_00 , required=a_ , help="# examples. -1 means use all." ) parser.add_argument("--n_test" , type=a_ , default=-1 , required=a_ , help="# examples. -1 means use all." ) parser.add_argument( "--task" , type=a_ , default="summarization" , required=a_ , help="# examples. -1 means use all." ) parser.add_argument("--label_smoothing" , type=a_ , default=0.0 , required=a_ ) parser.add_argument("--src_lang" , type=a_ , default="" , required=a_ ) parser.add_argument("--tgt_lang" , type=a_ , default="" , required=a_ ) parser.add_argument("--eval_beams" , type=a_ , default=a_ , required=a_ ) parser.add_argument( "--val_metric" , type=a_ , default=a_ , required=a_ , choices=["bleu", "rouge2", "loss", None] ) parser.add_argument("--eval_max_gen_length" , type=a_ , default=a_ , help="never generate more than n tokens" ) parser.add_argument("--save_top_k" , type=a_ , default=1 , required=a_ , help="How many checkpoints to save" ) parser.add_argument( "--early_stopping_patience" , type=a_ , default=-1 , required=a_ , help=( "-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So" " val_check_interval will effect it." ) , ) return parser class __lowerCamelCase ( A__ ): '''simple docstring''' a_ : Any = """translation""" a_ : Any = ["""loss"""] a_ : List[Any] = ["""bleu"""] a_ : Dict = """bleu""" def __init__( self : List[Any] , a_ : Any , **a_ : Optional[Any] ): super().__init__(a_ , **a_ ) lowerCAmelCase_ : Dict = hparams.src_lang lowerCAmelCase_ : Optional[int] = hparams.tgt_lang def lowerCamelCase ( self : List[Any] , a_ : str , a_ : Any ): return calculate_bleu(a_ , a_ ) def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase=None ) -> SummarizationModule: """simple docstring""" Path(args.output_dir ).mkdir(exist_ok=__UpperCamelCase ) check_output_dir(__UpperCamelCase , expected_items=3 ) if model is None: if "summarization" in args.task: lowerCAmelCase_ : SummarizationModule = SummarizationModule(__UpperCamelCase ) else: lowerCAmelCase_ : SummarizationModule = TranslationModule(__UpperCamelCase ) lowerCAmelCase_ : List[str] = Path(args.data_dir ).name if ( args.logger_name == "default" or args.fast_dev_run or str(args.output_dir ).startswith("/tmp" ) or str(args.output_dir ).startswith("/var" ) ): lowerCAmelCase_ : Optional[Any] = True # don't pollute wandb logs unnecessarily elif args.logger_name == "wandb": from pytorch_lightning.loggers import WandbLogger lowerCAmelCase_ : List[Any] = os.environ.get("WANDB_PROJECT" , __UpperCamelCase ) lowerCAmelCase_ : List[Any] = WandbLogger(name=model.output_dir.name , project=__UpperCamelCase ) elif args.logger_name == "wandb_shared": from pytorch_lightning.loggers import WandbLogger lowerCAmelCase_ : List[Any] = WandbLogger(name=model.output_dir.name , project=f'''hf_{dataset}''' ) if args.early_stopping_patience >= 0: lowerCAmelCase_ : List[str] = get_early_stopping_callback(model.val_metric , args.early_stopping_patience ) else: lowerCAmelCase_ : Optional[int] = False lowerCAmelCase_ : Union[str, Any] = args.val_metric == "loss" lowerCAmelCase_ : pl.Trainer = generic_train( __UpperCamelCase , __UpperCamelCase , logging_callback=SeqaSeqLoggingCallback() , checkpoint_callback=get_checkpoint_callback( args.output_dir , model.val_metric , args.save_top_k , __UpperCamelCase ) , early_stopping_callback=__UpperCamelCase , logger=__UpperCamelCase , ) pickle_save(model.hparams , model.output_dir / "hparams.pkl" ) if not args.do_predict: return model lowerCAmelCase_ : Any = "" lowerCAmelCase_ : int = sorted(glob.glob(os.path.join(args.output_dir , "*.ckpt" ) , recursive=__UpperCamelCase ) ) if checkpoints: lowerCAmelCase_ : Optional[int] = checkpoints[-1] lowerCAmelCase_ : Optional[int] = checkpoints[-1] trainer.logger.log_hyperparams(model.hparams ) # test() without a model tests using the best checkpoint automatically trainer.test() return model if __name__ == "__main__": lowercase__ = argparse.ArgumentParser() lowercase__ = pl.Trainer.add_argparse_args(parser) lowercase__ = SummarizationModule.add_model_specific_args(parser, os.getcwd()) lowercase__ = parser.parse_args() main(args)
161
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = { """EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""", # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __lowerCamelCase ( A__ ): '''simple docstring''' a_ : Union[str, Any] = """gpt_neo""" a_ : List[Any] = ["""past_key_values"""] a_ : Optional[Any] = {"""num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Optional[int] , a_ : List[str]=5_02_57 , a_ : List[str]=20_48 , a_ : Union[str, Any]=20_48 , a_ : Union[str, Any]=24 , a_ : Optional[int]=[[["global", "local"], 12]] , a_ : str=16 , a_ : Optional[Any]=None , a_ : str=2_56 , a_ : Union[str, Any]="gelu_new" , a_ : Optional[int]=0.0 , a_ : Optional[Any]=0.0 , a_ : List[Any]=0.0 , a_ : List[Any]=0.1 , a_ : Optional[Any]=1e-5 , a_ : Optional[Any]=0.02 , a_ : int=True , a_ : Optional[Any]=5_02_56 , a_ : Tuple=5_02_56 , **a_ : str , ): lowerCAmelCase_ : Optional[Any] = vocab_size lowerCAmelCase_ : str = max_position_embeddings lowerCAmelCase_ : Tuple = hidden_size lowerCAmelCase_ : Union[str, Any] = num_layers lowerCAmelCase_ : str = num_heads lowerCAmelCase_ : List[str] = intermediate_size lowerCAmelCase_ : Union[str, Any] = window_size lowerCAmelCase_ : Any = activation_function lowerCAmelCase_ : str = resid_dropout lowerCAmelCase_ : Union[str, Any] = embed_dropout lowerCAmelCase_ : Optional[Any] = attention_dropout lowerCAmelCase_ : Dict = classifier_dropout lowerCAmelCase_ : int = layer_norm_epsilon lowerCAmelCase_ : Dict = initializer_range lowerCAmelCase_ : List[Any] = use_cache lowerCAmelCase_ : Optional[int] = bos_token_id lowerCAmelCase_ : str = eos_token_id lowerCAmelCase_ : Optional[Any] = attention_types lowerCAmelCase_ : Optional[Any] = self.expand_attention_types_params(a_ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f'''but is `len(config.attention_layers) = {len(self.attention_layers )}`, ''' f'''`config.num_layers = {self.num_layers}`. ''' "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) @staticmethod def lowerCamelCase ( a_ : Optional[Any] ): lowerCAmelCase_ : int = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> int: """simple docstring""" import torch lowerCAmelCase_ : str = input.size() lowerCAmelCase_ : List[Any] = len(__UpperCamelCase ) lowerCAmelCase_ : Tuple = shape[dimension] lowerCAmelCase_ : Tuple = torch.arange(0 , __UpperCamelCase , __UpperCamelCase ) lowerCAmelCase_ : List[Any] = torch.div(sizedim - size , __UpperCamelCase , rounding_mode="floor" ) + 1 lowerCAmelCase_ : Dict = torch.arange(__UpperCamelCase ) + low_indices[:min_length][:, None] lowerCAmelCase_ : Tuple = [slice(__UpperCamelCase )] * rank lowerCAmelCase_ : List[str] = indices lowerCAmelCase_ : Dict = input[s] lowerCAmelCase_ : Tuple = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(__UpperCamelCase ) def __lowerCamelCase ( __UpperCamelCase , __UpperCamelCase ) -> Any: """simple docstring""" import torch lowerCAmelCase_ : Optional[int] = torch.arange(1 , __UpperCamelCase ) lowerCAmelCase_ : Tuple = torch.remainder(__UpperCamelCase , __UpperCamelCase ) lowerCAmelCase_ : Tuple = remainders == 0 lowerCAmelCase_ : List[Any] = candidates[divisor_indices] lowerCAmelCase_ : List[str] = torch.max(__UpperCamelCase ) return largest_divisor, torch.div(__UpperCamelCase , __UpperCamelCase , rounding_mode="floor" ) class __lowerCamelCase ( A__ ): '''simple docstring''' @property def lowerCamelCase ( self : List[str] ): lowerCAmelCase_ : Any = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(a_ , direction="inputs" ) lowerCAmelCase_ : int = {0: "batch", 1: "past_sequence + sequence"} else: lowerCAmelCase_ : str = {0: "batch", 1: "sequence"} return common_inputs @property def lowerCamelCase ( self : int ): return self._config.num_heads def lowerCamelCase ( self : Optional[Any] , a_ : PreTrainedTokenizer , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , ): lowerCAmelCase_ : int = 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() lowerCAmelCase_ : str = 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 lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = common_inputs["input_ids"].shape # Not using the same length for past_key_values lowerCAmelCase_ : str = seqlen + 2 lowerCAmelCase_ : Tuple = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCAmelCase_ : Optional[int] = [ (torch.zeros(a_ ), torch.zeros(a_ )) for _ in range(self.num_layers ) ] lowerCAmelCase_ : Tuple = common_inputs["attention_mask"] if self.use_past: lowerCAmelCase_ : List[str] = ordered_inputs["attention_mask"].dtype lowerCAmelCase_ : Optional[Any] = torch.cat( [ordered_inputs["attention_mask"], torch.ones(a_ , a_ , dtype=a_ )] , dim=1 ) return ordered_inputs @property def lowerCamelCase ( self : Union[str, Any] ): return 13
161
1
from __future__ import annotations def __UpperCamelCase ( _A , _A ): lowerCAmelCase_ = get_failure_array(_A ) # 2) Step through text searching for pattern lowerCAmelCase_ , lowerCAmelCase_ = 0, 0 # index into text, pattern while i < len(_A ): if pattern[j] == text[i]: if j == (len(_A ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: lowerCAmelCase_ = failure[j - 1] continue i += 1 return False def __UpperCamelCase ( _A ): lowerCAmelCase_ = [0] lowerCAmelCase_ = 0 lowerCAmelCase_ = 1 while j < len(_A ): if pattern[i] == pattern[j]: i += 1 elif i > 0: lowerCAmelCase_ = failure[i - 1] continue j += 1 failure.append(_A ) return failure if __name__ == "__main__": # Test 1) _A = '''abc1abc12''' _A = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' _A = '''alskfjaldsk23adsfabcabc''' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) _A = '''ABABX''' _A = '''ABABZABABYABABX''' assert kmp(pattern, text) # Test 3) _A = '''AAAB''' _A = '''ABAAAAAB''' assert kmp(pattern, text) # Test 4) _A = '''abcdabcy''' _A = '''abcxabcdabxabcdabcdabcy''' assert kmp(pattern, text) # Test 5) _A = '''aabaabaaa''' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
278
def __UpperCamelCase ( _A ): if not numbers: return 0 if not isinstance(_A , (list, tuple) ) or not all( isinstance(_A , _A ) for number in numbers ): raise ValueError('''numbers must be an iterable of integers''' ) lowerCAmelCase_ = lowerCAmelCase_ = lowerCAmelCase_ = numbers[0] for i in range(1 , len(_A ) ): # update the maximum and minimum subarray products lowerCAmelCase_ = numbers[i] if number < 0: lowerCAmelCase_ , lowerCAmelCase_ = min_till_now, max_till_now lowerCAmelCase_ = max(_A , max_till_now * number ) lowerCAmelCase_ = min(_A , min_till_now * number ) # update the maximum product found till now lowerCAmelCase_ = max(_A , _A ) return max_prod
278
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
354
"""simple docstring""" import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE_ : List[str] = '\\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' SCREAMING_SNAKE_CASE_ : List[str] = '\\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' SCREAMING_SNAKE_CASE_ : List[Any] = '\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 a ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self: Tuple ): """simple docstring""" 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 UpperCamelCase ( self: int , UpperCamelCase: Optional[int] , UpperCamelCase: Union[str, Any] , UpperCamelCase: bool = False , UpperCamelCase: bool = False , UpperCamelCase: bool = False , UpperCamelCase: bool = False , ): """simple docstring""" A__ = len(references[0] ) if any(len(UpperCamelCase ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) A__ = [[refs[i] for refs in references] for i in range(UpperCamelCase )] A__ = TER( normalized=UpperCamelCase , no_punct=UpperCamelCase , asian_support=UpperCamelCase , case_sensitive=UpperCamelCase , ) A__ = sb_ter.corpus_score(UpperCamelCase , UpperCamelCase ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
69
0
"""simple docstring""" from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 lowerCamelCase__ = { # 1536-bit 5: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 2048-bit 14: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AACAA68FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 3072-bit 15: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64""" + """ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7""" + """ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B""" + """F12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31""" + """43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 4096-bit 16: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64""" + """ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7""" + """ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B""" + """F12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31""" + """43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7""" + """88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA""" + """2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6""" + """287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED""" + """1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9""" + """93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199""" + """FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 6144-bit 17: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08""" + """8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B""" + """302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9""" + """A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6""" + """49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8""" + """FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C""" + """180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718""" + """3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D""" + """04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D""" + """B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226""" + """1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC""" + """E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26""" + """99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB""" + """04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2""" + """233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127""" + """D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492""" + """36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406""" + """AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918""" + """DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151""" + """2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03""" + """F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F""" + """BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA""" + """CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B""" + """B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632""" + """387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E""" + """6DCC4024FFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, # 8192-bit 18: { """prime""": int( """FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1""" + """29024E088A67CC74020BBEA63B139B22514A08798E3404DD""" + """EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245""" + """E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED""" + """EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D""" + """C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F""" + """83655D23DCA3AD961C62F356208552BB9ED529077096966D""" + """670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B""" + """E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9""" + """DE2BCBF6955817183995497CEA956AE515D2261898FA0510""" + """15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64""" + """ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7""" + """ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B""" + """F12FFA06D98A0864D87602733EC86A64521F2B18177B200C""" + """BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31""" + """43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7""" + """88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA""" + """2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6""" + """287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED""" + """1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9""" + """93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492""" + """36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD""" + """F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831""" + """179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B""" + """DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF""" + """5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6""" + """D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3""" + """23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA""" + """CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328""" + """06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C""" + """DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE""" + """12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4""" + """38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300""" + """741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568""" + """3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9""" + """22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B""" + """4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A""" + """062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36""" + """4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1""" + """B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92""" + """4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47""" + """9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71""" + """60C980DD98EDD3DFFFFFFFFFFFFFFFFF""", base=16, ), """generator""": 2, }, } class A__ : def __init__( self , _SCREAMING_SNAKE_CASE = 14 ): if group not in primes: raise ValueError('Unsupported Group' ) __lowerCAmelCase : Dict = primes[group]['prime'] __lowerCAmelCase : Any = primes[group]['generator'] __lowerCAmelCase : Dict = int(hexlify(urandom(32 ) ) , base=16 ) def __lowerCamelCase ( self ): return hex(self.__private_key )[2:] def __lowerCamelCase ( self ): __lowerCAmelCase : str = pow(self.generator , self.__private_key , self.prime ) return hex(_SCREAMING_SNAKE_CASE )[2:] def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): # check if the other public key is valid based on NIST SP800-56 return ( 2 <= key <= self.prime - 2 and pow(_SCREAMING_SNAKE_CASE , (self.prime - 1) // 2 , self.prime ) == 1 ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Any = int(_SCREAMING_SNAKE_CASE , base=16 ) if not self.is_valid_public_key(_SCREAMING_SNAKE_CASE ): raise ValueError('Invalid public key' ) __lowerCAmelCase : Dict = pow(_SCREAMING_SNAKE_CASE , self.__private_key , self.prime ) return shaaaa(str(_SCREAMING_SNAKE_CASE ).encode() ).hexdigest() @staticmethod def __lowerCamelCase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # check if the other public key is valid based on NIST SP800-56 return ( 2 <= remote_public_key_str <= prime - 2 and pow(_SCREAMING_SNAKE_CASE , (prime - 1) // 2 , _SCREAMING_SNAKE_CASE ) == 1 ) @staticmethod def __lowerCamelCase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 14 ): __lowerCAmelCase : Optional[int] = int(_SCREAMING_SNAKE_CASE , base=16 ) __lowerCAmelCase : List[Any] = int(_SCREAMING_SNAKE_CASE , base=16 ) __lowerCAmelCase : Tuple = primes[group]['prime'] if not DiffieHellman.is_valid_public_key_static(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError('Invalid public key' ) __lowerCAmelCase : Tuple = pow(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return shaaaa(str(_SCREAMING_SNAKE_CASE ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
86
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 snake_case_ : List[str] = logging.get_logger(__name__) snake_case_ : Tuple = { "Salesforce/codegen-350M-nl": "https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json", "Salesforce/codegen-350M-multi": "https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json", "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json", "Salesforce/codegen-2B-nl": "https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json", "Salesforce/codegen-2B-multi": "https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json", "Salesforce/codegen-2B-mono": "https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json", "Salesforce/codegen-6B-nl": "https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json", "Salesforce/codegen-6B-multi": "https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json", "Salesforce/codegen-6B-mono": "https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json", "Salesforce/codegen-16B-nl": "https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json", "Salesforce/codegen-16B-multi": "https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json", "Salesforce/codegen-16B-mono": "https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json", } class __snake_case ( a ): UpperCAmelCase__ : str = '''codegen''' UpperCAmelCase__ : int = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Union[str, Any] , _snake_case : Union[str, Any]=50400 , _snake_case : Optional[int]=2048 , _snake_case : Union[str, Any]=2048 , _snake_case : List[str]=4096 , _snake_case : Any=28 , _snake_case : List[str]=16 , _snake_case : int=64 , _snake_case : Tuple=None , _snake_case : Dict="gelu_new" , _snake_case : Union[str, Any]=0.0 , _snake_case : Optional[Any]=0.0 , _snake_case : List[Any]=0.0 , _snake_case : List[Any]=1e-5 , _snake_case : List[str]=0.0_2 , _snake_case : Optional[Any]=True , _snake_case : int=50256 , _snake_case : Tuple=50256 , _snake_case : int=False , **_snake_case : Any , ): """simple docstring""" UpperCAmelCase_ = vocab_size UpperCAmelCase_ = n_ctx UpperCAmelCase_ = n_positions UpperCAmelCase_ = n_embd UpperCAmelCase_ = n_layer UpperCAmelCase_ = n_head UpperCAmelCase_ = n_inner UpperCAmelCase_ = rotary_dim UpperCAmelCase_ = activation_function UpperCAmelCase_ = resid_pdrop UpperCAmelCase_ = embd_pdrop UpperCAmelCase_ = attn_pdrop UpperCAmelCase_ = layer_norm_epsilon UpperCAmelCase_ = initializer_range UpperCAmelCase_ = use_cache UpperCAmelCase_ = bos_token_id UpperCAmelCase_ = eos_token_id super().__init__( bos_token_id=_snake_case , eos_token_id=_snake_case , tie_word_embeddings=_snake_case , **_snake_case) class __snake_case ( a ): def __init__( self : Tuple , _snake_case : PretrainedConfig , _snake_case : str = "default" , _snake_case : List[PatchingSpec] = None , _snake_case : bool = False , ): """simple docstring""" super().__init__(_snake_case , task=_snake_case , patching_specs=_snake_case , use_past=_snake_case) if not getattr(self._config , '''pad_token_id''' , _snake_case): # TODO: how to do that better? UpperCAmelCase_ = 0 @property def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}) if self.use_past: self.fill_with_past_key_values_(_snake_case , direction='''inputs''') UpperCAmelCase_ = {0: '''batch''', 1: '''past_sequence + sequence'''} else: UpperCAmelCase_ = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def lowerCamelCase ( self : List[str]): """simple docstring""" return self._config.n_layer @property def lowerCamelCase ( self : int): """simple docstring""" return self._config.n_head def lowerCamelCase ( self : Optional[int] , _snake_case : PreTrainedTokenizer , _snake_case : int = -1 , _snake_case : int = -1 , _snake_case : bool = False , _snake_case : Optional[TensorType] = None , ): """simple docstring""" UpperCAmelCase_ = super(_snake_case , self).generate_dummy_inputs( _snake_case , batch_size=_snake_case , seq_length=_snake_case , is_pair=_snake_case , framework=_snake_case) # We need to order the input in the way they appears in the forward() UpperCAmelCase_ = 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 UpperCAmelCase_ , UpperCAmelCase_ = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values UpperCAmelCase_ = seqlen + 2 UpperCAmelCase_ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) UpperCAmelCase_ = [ (torch.zeros(_snake_case), torch.zeros(_snake_case)) for _ in range(self.num_layers) ] UpperCAmelCase_ = common_inputs['''attention_mask'''] if self.use_past: UpperCAmelCase_ = ordered_inputs['''attention_mask'''].dtype UpperCAmelCase_ = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(_snake_case , _snake_case , dtype=_snake_case)] , dim=1) return ordered_inputs @property def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" return 13
51
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 lowerCamelCase : def __init__(self : str , _A : Optional[Any] , _A : List[str] , _A : bool = True , _A : bool = False ) -> str: snake_case = scheduler snake_case = optimizers if isinstance(_A , (list, tuple) ) else [optimizers] snake_case = split_batches snake_case = step_with_optimizer snake_case = GradientState() def UpperCAmelCase(self : List[Any] , *_A : int , **_A : Union[str, Any] ) -> int: 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 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 UpperCAmelCase(self : List[str] ) -> str: return self.scheduler.get_last_lr() def UpperCAmelCase(self : List[str] ) -> Union[str, Any]: return self.scheduler.state_dict() def UpperCAmelCase(self : str , _A : Optional[Any] ) -> Any: self.scheduler.load_state_dict(_A ) def UpperCAmelCase(self : Union[str, Any] ) -> Tuple: return self.scheduler.get_lr() def UpperCAmelCase(self : Tuple , *_A : int , **_A : Union[str, Any] ) -> str: return self.scheduler.print_lr(*_A , **_A )
350
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowercase_ ( A__ ) -> str: """simple docstring""" return getitem, k def lowercase_ ( A__ , A__ ) -> str: """simple docstring""" return setitem, k, v def lowercase_ ( A__ ) -> List[Any]: """simple docstring""" return delitem, k def lowercase_ ( A__ , A__ , *A__ ) -> str: """simple docstring""" try: return fun(A__ , *A__ ), None except Exception as e: return None, e _A = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) _A = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] _A = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] _A = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] _A = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] _A = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("key_a", "val_b"), ] @pytest.mark.parametrize( "operations" , ( pytest.param(_add_items , id="add items" ), pytest.param(_overwrite_items , id="overwrite items" ), pytest.param(_delete_items , id="delete items" ), pytest.param(_access_absent_items , id="access absent items" ), pytest.param(_add_with_resize_up , id="add with resize up" ), pytest.param(_add_with_resize_down , id="add with resize down" ), ) , ) def lowercase_ ( A__ ) -> List[Any]: """simple docstring""" snake_case = HashMap(initial_block_size=4 ) snake_case = {} for _, (fun, *args) in enumerate(A__ ): snake_case , snake_case = _run_operation(A__ , A__ , *A__ ) snake_case , snake_case = _run_operation(A__ , A__ , *A__ ) assert my_res == py_res assert str(A__ ) == str(A__ ) assert set(A__ ) == set(A__ ) assert len(A__ ) == len(A__ ) assert set(my.items() ) == set(py.items() ) def lowercase_ ( ) -> Optional[int]: """simple docstring""" def is_public(A__ ) -> bool: return not name.startswith("_" ) snake_case = {name for name in dir({} ) if is_public(A__ )} snake_case = {name for name in dir(HashMap() ) if is_public(A__ )} assert dict_public_names > hash_public_names
137
0
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCamelCase__ =TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ ): '''simple docstring''' __snake_case : Union[str, Any] = TextaTextGenerationPipeline(model=a_ , tokenizer=a_ ) return generator, ["Something to write", "Something else"] def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : Union[str, Any] = 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''' ) ) __snake_case : List[Any] = 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_ )}], ] , ) __snake_case : Optional[int] = 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 ): '''simple docstring''' __snake_case : Any = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''pt''' ) # do_sample=False necessary for reproducibility __snake_case : int = generator('''Something there''' , do_sample=a_ ) self.assertEqual(a_ , [{'''generated_text''': ''''''}] ) __snake_case : Optional[int] = 3 __snake_case : int = generator( '''Something there''' , num_return_sequences=a_ , num_beams=a_ , ) __snake_case : Dict = [ {'''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_ ) __snake_case : List[Any] = 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 )}, ] , ) __snake_case : Dict = generator.model.config.eos_token_id __snake_case : Any = '''<pad>''' __snake_case : Tuple = 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 ): '''simple docstring''' __snake_case : Optional[int] = pipeline('''text2text-generation''' , model='''patrickvonplaten/t5-tiny-random''' , framework='''tf''' ) # do_sample=False necessary for reproducibility __snake_case : Union[str, Any] = generator('''Something there''' , do_sample=a_ ) self.assertEqual(a_ , [{'''generated_text''': ''''''}] )
102
"""simple docstring""" import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig lowercase__ = { """facebook/maskformer-swin-base-ade""": ( """https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json""" ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } lowercase__ = logging.get_logger(__name__) class __lowerCamelCase ( A__ ): '''simple docstring''' a_ : Optional[int] = """maskformer""" a_ : Optional[int] = {"""hidden_size""": """mask_feature_size"""} a_ : Optional[int] = ["""resnet""", """swin"""] a_ : int = ["""detr"""] def __init__( self : str , a_ : int = 2_56 , a_ : int = 2_56 , a_ : float = 0.1 , a_ : bool = False , a_ : Optional[Dict] = None , a_ : Optional[Dict] = None , a_ : float = 0.02 , a_ : float = 1.0 , a_ : float = 1.0 , a_ : float = 1.0 , a_ : float = 20.0 , a_ : Optional[bool] = None , **a_ : str , ): if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k lowerCAmelCase_ : Tuple = SwinConfig( image_size=3_84 , in_channels=3 , patch_size=4 , embed_dim=1_28 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(a_ , a_ ): lowerCAmelCase_ : Optional[Any] = backbone_config.pop("model_type" ) lowerCAmelCase_ : Any = CONFIG_MAPPING[backbone_model_type] lowerCAmelCase_ : str = config_class.from_dict(a_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. ''' f'''Supported model types: {",".join(self.backbones_supported )}''' ) if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 lowerCAmelCase_ : Union[str, Any] = DetrConfig() else: # verify that the decoder is supported lowerCAmelCase_ : Optional[Any] = ( decoder_config.pop("model_type" ) if isinstance(a_ , a_ ) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( f'''Transformer Decoder {decoder_type} not supported, please use one of''' f''' {",".join(self.decoders_supported )}''' ) if isinstance(a_ , a_ ): lowerCAmelCase_ : Optional[int] = CONFIG_MAPPING[decoder_type] lowerCAmelCase_ : List[Any] = config_class.from_dict(a_ ) lowerCAmelCase_ : str = backbone_config lowerCAmelCase_ : Tuple = decoder_config # main feature dimension for the model lowerCAmelCase_ : str = fpn_feature_size lowerCAmelCase_ : str = mask_feature_size # initializer lowerCAmelCase_ : List[Any] = init_std lowerCAmelCase_ : Tuple = init_xavier_std # Hungarian matcher && loss lowerCAmelCase_ : int = cross_entropy_weight lowerCAmelCase_ : Dict = dice_weight lowerCAmelCase_ : int = mask_weight lowerCAmelCase_ : Any = use_auxiliary_loss lowerCAmelCase_ : Dict = no_object_weight lowerCAmelCase_ : Optional[int] = output_auxiliary_logits lowerCAmelCase_ : int = self.decoder_config.encoder_attention_heads lowerCAmelCase_ : str = self.decoder_config.num_hidden_layers super().__init__(**a_ ) @classmethod def lowerCamelCase ( cls : int , a_ : PretrainedConfig , a_ : PretrainedConfig , **a_ : Tuple ): return cls( backbone_config=a_ , decoder_config=a_ , **a_ , ) def lowerCamelCase ( self : Any ): lowerCAmelCase_ : Optional[int] = copy.deepcopy(self.__dict__ ) lowerCAmelCase_ : Optional[Any] = self.backbone_config.to_dict() lowerCAmelCase_ : Union[str, Any] = self.decoder_config.to_dict() lowerCAmelCase_ : List[str] = self.__class__.model_type return output
241
0
import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset __A = pd.read_csv( "https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/" "position_salaries.csv" ) __A = dataset.iloc[:, 1:2].values __A = dataset.iloc[:, 2].values __A , __A , __A , __A = train_test_split(X, y, test_size=0.2, random_state=0) __A = PolynomialFeatures(degree=4) __A = poly_reg.fit_transform(X) __A = LinearRegression() pol_reg.fit(X_poly, y) def lowerCamelCase_ ( ) -> str: """simple docstring""" plt.scatter(UpperCamelCase__ , UpperCamelCase__ , color='red' ) plt.plot(UpperCamelCase__ , pol_reg.predict(poly_reg.fit_transform(UpperCamelCase__ ) ) , color='blue' ) plt.title('Truth or Bluff (Linear Regression)' ) plt.xlabel('Position level' ) plt.ylabel('Salary' ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
348
from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> int: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> str: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[int]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> str: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> List[Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[int]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> List[Any]: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> str: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> int: '''simple docstring''' requires_backends(self , ['sentencepiece'] ) class __lowerCAmelCase ( metaclass=__magic_name__ ): """simple docstring""" snake_case_ = ['''sentencepiece'''] def __init__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> int: '''simple docstring''' requires_backends(self , ['sentencepiece'] )
348
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int lowerCamelCase = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class A ( datasets.BuilderConfig ): UpperCamelCase__ : Optional[datasets.Features] =None def a_ ( SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : List[int] , ): '''simple docstring''' import pyspark def generate_fn(): _lowerCamelCase : str =df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: _lowerCamelCase : List[str] =df_with_partition_id.select('*' ).where(F'''part_id = {partition_id}''' ).drop('part_id' ) _lowerCamelCase : Tuple =partition_df.collect() _lowerCamelCase : int =0 for row in rows: yield F'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class A ( _BaseExamplesIterable ): def __init__( self : Dict , lowercase_ : "pyspark.sql.DataFrame" , lowercase_ : Optional[Any]=None , ) -> Union[str, Any]: """simple docstring""" _lowerCamelCase : Tuple =df _lowerCamelCase : int =partition_order or range(self.df.rdd.getNumPartitions() ) _lowerCamelCase : Optional[Any] =_generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : List[str] ) -> List[str]: """simple docstring""" yield from self.generate_examples_fn() def lowerCamelCase ( self : Optional[Any] , lowercase_ : np.random.Generator ) -> "SparkExamplesIterable": """simple docstring""" _lowerCamelCase : Tuple =list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(lowercase_ ) return SparkExamplesIterable(self.df , partition_order=lowercase_ ) def lowerCamelCase ( self : Tuple , lowercase_ : int , lowercase_ : int ) -> "SparkExamplesIterable": """simple docstring""" _lowerCamelCase : Dict =self.split_shard_indices_by_worker(lowercase_ , lowercase_ ) return SparkExamplesIterable(self.df , partition_order=lowercase_ ) @property def lowerCamelCase ( self : Optional[int] ) -> int: """simple docstring""" return len(self.partition_order ) class A ( datasets.DatasetBuilder ): UpperCamelCase__ : str =SparkConfig def __init__( self : List[str] , lowercase_ : "pyspark.sql.DataFrame" , lowercase_ : str = None , lowercase_ : str = None , **lowercase_ : Tuple , ) -> Tuple: """simple docstring""" import pyspark _lowerCamelCase : str =pyspark.sql.SparkSession.builder.getOrCreate() _lowerCamelCase : int =df _lowerCamelCase : Union[str, Any] =working_dir super().__init__( cache_dir=lowercase_ , config_name=str(self.df.semanticHash() ) , **lowercase_ , ) def lowerCamelCase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" def create_cache_and_write_probe(lowercase_ : Optional[Any] ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=lowercase_ ) _lowerCamelCase : int =os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(lowercase_ , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: _lowerCamelCase : List[str] =( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(lowercase_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def lowerCamelCase ( self : List[Any] ) -> Any: """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def lowerCamelCase ( self : int , lowercase_ : datasets.download.download_manager.DownloadManager ) -> List[Any]: """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowerCamelCase ( self : Any , lowercase_ : Union[str, Any] ) -> List[str]: """simple docstring""" import pyspark def get_arrow_batch_size(lowercase_ : List[str] ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) _lowerCamelCase : Dict =self.df.count() _lowerCamelCase : Any =df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. _lowerCamelCase : List[Any] =( self.df.limit(lowercase_ ) .repartition(1 ) .mapInArrow(lowercase_ , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) _lowerCamelCase : List[Any] =approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. _lowerCamelCase : str =min(lowercase_ , int(approx_total_size / max_shard_size ) ) _lowerCamelCase : Any =self.df.repartition(lowercase_ ) def lowerCamelCase ( self : Dict , lowercase_ : str , lowercase_ : str , lowercase_ : int , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: """simple docstring""" import pyspark _lowerCamelCase : Any =ParquetWriter if file_format == 'parquet' else ArrowWriter _lowerCamelCase : List[Any] =os.path.join(self._working_dir , os.path.basename(lowercase_ ) ) if self._working_dir else fpath _lowerCamelCase : Optional[Any] =file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. _lowerCamelCase : Optional[Any] =self.config.features _lowerCamelCase : Optional[int] =self._writer_batch_size _lowerCamelCase : List[Any] =self._fs.storage_options def write_arrow(lowercase_ : Tuple ): # Within the same SparkContext, no two task attempts will share the same attempt ID. _lowerCamelCase : List[str] =pyspark.TaskContext().taskAttemptId() _lowerCamelCase : Tuple =next(lowercase_ , lowercase_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) _lowerCamelCase : str =0 _lowerCamelCase : Optional[int] =writer_class( features=lowercase_ , path=working_fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , writer_batch_size=lowercase_ , storage_options=lowercase_ , embed_local_files=lowercase_ , ) _lowerCamelCase : Optional[Any] =pa.Table.from_batches([first_batch] ) writer.write_table(lowercase_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: _lowerCamelCase , _lowerCamelCase : Dict =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 _lowerCamelCase : Union[str, Any] =writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , writer_batch_size=lowercase_ , storage_options=lowercase_ , embed_local_files=lowercase_ , ) _lowerCamelCase : Optional[Any] =pa.Table.from_batches([batch] ) writer.write_table(lowercase_ ) if writer._num_bytes > 0: _lowerCamelCase , _lowerCamelCase : List[Any] =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(lowercase_ ) ): _lowerCamelCase : Tuple =os.path.join(os.path.dirname(lowercase_ ) , os.path.basename(lowercase_ ) ) shutil.move(lowercase_ , lowercase_ ) _lowerCamelCase : Dict =( self.df.mapInArrow(lowercase_ , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def lowerCamelCase ( self : Union[str, Any] , lowercase_ : "datasets.SplitGenerator" , lowercase_ : str = "arrow" , lowercase_ : Optional[Union[str, int]] = None , lowercase_ : Optional[int] = None , **lowercase_ : Optional[int] , ) -> List[Any]: """simple docstring""" self._validate_cache_dir() _lowerCamelCase : Dict =convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(lowercase_ ) _lowerCamelCase : List[Any] =not is_remote_filesystem(self._fs ) _lowerCamelCase : Tuple =os.path.join if is_local else posixpath.join _lowerCamelCase : Optional[Any] ='-TTTTT-SSSSS-of-NNNNN' _lowerCamelCase : Optional[int] =F'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' _lowerCamelCase : int =path_join(self._output_dir , lowercase_ ) _lowerCamelCase : Union[str, Any] =0 _lowerCamelCase : str =0 _lowerCamelCase : Optional[Any] =0 _lowerCamelCase : Any =[] _lowerCamelCase : Any =[] for task_id, content in self._prepare_split_single(lowercase_ , lowercase_ , lowercase_ ): ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Tuple =content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(lowercase_ ) _lowerCamelCase : Union[str, Any] =total_num_examples _lowerCamelCase : Tuple =total_num_bytes # should rename everything at the end logger.debug(F'''Renaming {total_shards} shards.''' ) if total_shards > 1: _lowerCamelCase : Any =all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. _lowerCamelCase : Union[str, Any] =self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( lowercase_ : int , lowercase_ : int , lowercase_ : int , ): rename( lowercase_ , fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , F'''{global_shard_id:05d}''' ).replace('NNNNN' , F'''{total_shards:05d}''' ) , ) _lowerCamelCase : str =[] _lowerCamelCase : Optional[Any] =0 for i in range(len(lowercase_ ) ): _lowerCamelCase , _lowerCamelCase : str =task_id_and_num_shards[i] for shard_id in range(lowercase_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(lowercase_ , len(lowercase_ ) ).map(lambda lowercase_ : _rename_shard(*lowercase_ ) ).collect() else: # don't use any pattern _lowerCamelCase : Any =0 _lowerCamelCase : Tuple =task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , fpath.replace(lowercase_ , '' ) , ) def lowerCamelCase ( self : Tuple , lowercase_ : "datasets.SplitGenerator" , ) -> SparkExamplesIterable: """simple docstring""" return SparkExamplesIterable(self.df )
199
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class A : UpperCamelCase__ : Union[str, Any] =XGLMConfig UpperCamelCase__ : Dict ={} UpperCamelCase__ : Tuple ='gelu' def __init__( self : List[Any] , lowercase_ : List[str] , lowercase_ : Union[str, Any]=14 , lowercase_ : Dict=7 , lowercase_ : Union[str, Any]=True , lowercase_ : Optional[Any]=True , lowercase_ : Any=True , lowercase_ : Optional[int]=99 , lowercase_ : List[Any]=32 , lowercase_ : List[Any]=2 , lowercase_ : Dict=4 , lowercase_ : List[str]=37 , lowercase_ : int="gelu" , lowercase_ : List[Any]=0.1 , lowercase_ : Union[str, Any]=0.1 , lowercase_ : List[str]=512 , lowercase_ : Union[str, Any]=0.02 , ) -> Optional[Any]: """simple docstring""" _lowerCamelCase : Dict =parent _lowerCamelCase : Optional[Any] =batch_size _lowerCamelCase : Optional[int] =seq_length _lowerCamelCase : Union[str, Any] =is_training _lowerCamelCase : Tuple =use_input_mask _lowerCamelCase : str =use_labels _lowerCamelCase : Any =vocab_size _lowerCamelCase : List[str] =d_model _lowerCamelCase : List[Any] =num_hidden_layers _lowerCamelCase : Union[str, Any] =num_attention_heads _lowerCamelCase : List[Any] =ffn_dim _lowerCamelCase : Optional[Any] =activation_function _lowerCamelCase : Dict =activation_dropout _lowerCamelCase : Tuple =attention_dropout _lowerCamelCase : List[str] =max_position_embeddings _lowerCamelCase : int =initializer_range _lowerCamelCase : Optional[int] =None _lowerCamelCase : Optional[Any] =0 _lowerCamelCase : List[str] =2 _lowerCamelCase : Any =1 def lowerCamelCase ( self : str ) -> int: """simple docstring""" return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def lowerCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" _lowerCamelCase : Union[str, Any] =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) _lowerCamelCase : Any =None if self.use_input_mask: _lowerCamelCase : str =random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : Optional[int] =self.get_config() _lowerCamelCase : Optional[Any] =floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def lowerCamelCase ( self : List[str] ) -> Dict: """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=lowercase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=lowercase_ , ) def lowerCamelCase ( self : Optional[int] ) -> str: """simple docstring""" _lowerCamelCase : str =self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Any =config_and_inputs _lowerCamelCase : Union[str, Any] ={ 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class A ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): UpperCamelCase__ : Union[str, Any] =(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () UpperCamelCase__ : List[str] =(TFXGLMForCausalLM,) if is_tf_available() else () UpperCamelCase__ : Any =( {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {} ) UpperCamelCase__ : str =False UpperCamelCase__ : int =False UpperCamelCase__ : int =False def lowerCamelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" _lowerCamelCase : Tuple =TFXGLMModelTester(self ) _lowerCamelCase : str =ConfigTester(self , config_class=lowercase_ , n_embd=37 ) def lowerCamelCase ( self : str ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() @slow def lowerCamelCase ( self : Any ) -> int: """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : int =TFXGLMModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def lowerCamelCase ( self : Optional[int] ) -> str: """simple docstring""" super().test_resize_token_embeddings() @require_tf class A ( unittest.TestCase ): @slow def lowerCamelCase ( self : str , lowercase_ : str=True ) -> Tuple: """simple docstring""" _lowerCamelCase : Any =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) _lowerCamelCase : List[Any] =tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off _lowerCamelCase : int =[2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581] # fmt: on _lowerCamelCase : Dict =model.generate(lowercase_ , do_sample=lowercase_ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , lowercase_ ) @slow def lowerCamelCase ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" _lowerCamelCase : List[str] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) _lowerCamelCase : Any =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) _lowerCamelCase : Tuple =tokenizer('Today is a nice day and' , return_tensors='tf' ) _lowerCamelCase : Optional[int] =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): _lowerCamelCase : List[Any] =model.generate(lowercase_ , do_sample=lowercase_ , seed=[7, 0] ) _lowerCamelCase : Union[str, Any] =tokenizer.decode(output_ids[0] , skip_special_tokens=lowercase_ ) _lowerCamelCase : Union[str, Any] =( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(lowercase_ , lowercase_ ) @slow def lowerCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" _lowerCamelCase : int =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) _lowerCamelCase : Any =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) _lowerCamelCase : Optional[Any] ='left' # use different length sentences to test batching _lowerCamelCase : int =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] _lowerCamelCase : List[Any] =tokenizer(lowercase_ , return_tensors='tf' , padding=lowercase_ ) _lowerCamelCase : int =inputs['input_ids'] _lowerCamelCase : str =model.generate(input_ids=lowercase_ , attention_mask=inputs['attention_mask'] , max_new_tokens=12 ) _lowerCamelCase : Optional[Any] =tokenizer(sentences[0] , return_tensors='tf' ).input_ids _lowerCamelCase : List[str] =model.generate(input_ids=lowercase_ , max_new_tokens=12 ) _lowerCamelCase : Tuple =tokenizer(sentences[1] , return_tensors='tf' ).input_ids _lowerCamelCase : Dict =model.generate(input_ids=lowercase_ , max_new_tokens=12 ) _lowerCamelCase : str =tokenizer.batch_decode(lowercase_ , skip_special_tokens=lowercase_ ) _lowerCamelCase : str =tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowercase_ ) _lowerCamelCase : int =tokenizer.decode(output_padded[0] , skip_special_tokens=lowercase_ ) _lowerCamelCase : List[str] =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(lowercase_ , lowercase_ ) self.assertListEqual(lowercase_ , [non_padded_sentence, padded_sentence] )
199
1
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class _lowercase ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowercase_ = IFInpaintingPipeline lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = PipelineTesterMixin.required_optional_params - {'latents'} def _UpperCamelCase ( self ) -> str: return self._get_dummy_components() def _UpperCamelCase ( self , UpperCAmelCase_ , UpperCAmelCase_=0 ) -> Union[str, Any]: if str(UpperCAmelCase_ ).startswith('mps' ): lowerCamelCase : List[Any] = torch.manual_seed(UpperCAmelCase_ ) else: lowerCamelCase : int = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) lowerCamelCase : int = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) lowerCamelCase : List[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) lowerCamelCase : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def _UpperCamelCase ( self ) -> Any: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def _UpperCamelCase ( self ) -> Dict: self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' ) def _UpperCamelCase ( self ) -> str: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def _UpperCamelCase ( self ) -> str: self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _UpperCamelCase ( self ) -> int: self._test_save_load_local() def _UpperCamelCase ( self ) -> List[str]: self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
205
"""simple docstring""" def UpperCAmelCase ( a_, a_ ): '''simple docstring''' while b: lowerCamelCase , lowerCamelCase : Tuple = b, a % b return a def UpperCAmelCase ( a_, a_ ): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(a_, a % b ) def UpperCAmelCase ( ): '''simple docstring''' print(F"""euclidean_gcd(3, 5) = {euclidean_gcd(3, 5 )}""" ) print(F"""euclidean_gcd(5, 3) = {euclidean_gcd(5, 3 )}""" ) print(F"""euclidean_gcd(1, 3) = {euclidean_gcd(1, 3 )}""" ) print(F"""euclidean_gcd(3, 6) = {euclidean_gcd(3, 6 )}""" ) print(F"""euclidean_gcd(6, 3) = {euclidean_gcd(6, 3 )}""" ) print(F"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3, 5 )}""" ) print(F"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5, 3 )}""" ) print(F"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1, 3 )}""" ) print(F"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3, 6 )}""" ) print(F"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6, 3 )}""" ) if __name__ == "__main__": main()
205
1
from __future__ import annotations from dataclasses import dataclass @dataclass class _a : _lowercase : float _lowercase : TreeNode | None = None _lowercase : TreeNode | None = None def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" def is_valid_tree(SCREAMING_SNAKE_CASE ) -> bool: if node is None: return True if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(__lowerCAmelCase ): raise ValueError( '''Each node should be type of TreeNode and data should be float.''' ) def is_binary_search_tree_recursive_check( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , __lowerCAmelCase , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , __lowerCAmelCase ) ) return is_binary_search_tree_recursive_check(__lowerCAmelCase , -float('''inf''' ) , float('''inf''' ) ) if __name__ == "__main__": import doctest doctest.testmod()
110
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available lowerCamelCase : int ={ '''configuration_audio_spectrogram_transformer''': [ '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ASTConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] =[ '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ASTForAudioClassification''', '''ASTModel''', '''ASTPreTrainedModel''', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] =['''ASTFeatureExtractor'''] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys lowerCamelCase : Optional[int] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
189
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available A_ : Union[str, Any] = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys A_ : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
141
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class _a (__magic_name__ ): '''simple docstring''' UpperCAmelCase__: Optional[Any] = '''MCTCTFeatureExtractor''' UpperCAmelCase__: Optional[int] = '''AutoTokenizer''' def __init__( self , A__ , A__ ): super().__init__(A__ , A__ ) A__ : List[str] = self.feature_extractor A__ : Optional[int] = False def __call__( self , *A__ , **A__ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*A__ , **A__ ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) A__ : Dict = kwargs.pop("""raw_speech""" ) else: A__ : Tuple = kwargs.pop("""audio""" , A__ ) A__ : Union[str, Any] = kwargs.pop("""sampling_rate""" , A__ ) A__ : int = kwargs.pop("""text""" , A__ ) if len(A__ ) > 0: A__ : Optional[int] = args[0] A__ : Dict = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: A__ : List[str] = self.feature_extractor(A__ , *A__ , sampling_rate=A__ , **A__ ) if text is not None: A__ : Optional[Any] = self.tokenizer(A__ , **A__ ) if text is None: return inputs elif audio is None: return encodings else: A__ : List[Any] = encodings["""input_ids"""] return inputs def __A ( self , *A__ , **A__ ): return self.tokenizer.batch_decode(*A__ , **A__ ) def __A ( self , *A__ , **A__ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*A__ , **A__ ) A__ : Optional[Any] = kwargs.pop("""input_features""" , A__ ) A__ : Union[str, Any] = kwargs.pop("""labels""" , A__ ) if len(A__ ) > 0: A__ : List[Any] = args[0] A__ : Optional[int] = args[1:] if input_features is not None: A__ : Union[str, Any] = self.feature_extractor.pad(A__ , *A__ , **A__ ) if labels is not None: A__ : List[Any] = self.tokenizer.pad(A__ , **A__ ) if labels is None: return input_features elif input_features is None: return labels else: A__ : Dict = labels["""input_ids"""] return input_features def __A ( self , *A__ , **A__ ): return self.tokenizer.decode(*A__ , **A__ ) @contextmanager def __A ( self ): warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) A__ : int = True A__ : List[Any] = self.tokenizer yield A__ : Tuple = self.feature_extractor A__ : Dict = False
141
1