code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_=0 ) -> int: # a graph with Node 0,1,...,N-1 __UpperCamelCase =n __UpperCamelCase =[ [math.inf for j in range(0 , A_ )] for i in range(0 , A_ ) ] # adjacency matrix for weight __UpperCamelCase =[ [math.inf for j in range(0 , A_ )] for i in range(0 , A_ ) ] # dp[i][j] stores minimum distance from i to j def _a ( self , A_ , A_ , A_ ) -> int: __UpperCamelCase =w def _a ( self ) -> List[str]: for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): __UpperCamelCase =min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def _a ( self , A_ , A_ ) -> List[Any]: return self.dp[u][v] if __name__ == "__main__": _A = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
import random def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =num - 1 __UpperCamelCase =0 while s % 2 == 0: __UpperCamelCase =s // 2 t += 1 for _ in range(5 ): __UpperCamelCase =random.randrange(2 , num - 1 ) __UpperCamelCase =pow(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if v != 1: __UpperCamelCase =0 while v != (num - 1): if i == t - 1: return False else: __UpperCamelCase =i + 1 __UpperCamelCase =(v**2) % num return True def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if num < 2: return False __UpperCamelCase =[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10_24 ): while True: __UpperCamelCase =random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(SCREAMING_SNAKE_CASE__ ): return num if __name__ == "__main__": _A = generate_large_prime() print(('Prime number:', num)) print(('is_prime_low_num:', is_prime_low_num(num)))
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[dict, list, tuple, torch.Tensor] ): __UpperCamelCase =[] if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for v in tree.values(): shapes.extend(_fetch_dims(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('Not supported' ) return shapes @torch.jit.ignore def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple[int, ...] ): __UpperCamelCase =[] for d in reversed(SCREAMING_SNAKE_CASE__ ): idx.append(flat_idx % d ) __UpperCamelCase =flat_idx // d return tuple(reversed(SCREAMING_SNAKE_CASE__ ) ) @torch.jit.ignore def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Sequence[int] , SCREAMING_SNAKE_CASE__ : Sequence[int] , SCREAMING_SNAKE_CASE__ : Sequence[int] , SCREAMING_SNAKE_CASE__ : Optional[Sequence[bool]] = None , SCREAMING_SNAKE_CASE__ : Optional[Sequence[bool]] = None , ): # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(SCREAMING_SNAKE_CASE__ : List[bool] ) -> None: __UpperCamelCase =True for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =-1 * (i + 1) l[reversed_idx] &= tally __UpperCamelCase =l[reversed_idx] if start_edges is None: __UpperCamelCase =[s == 0 for s in start] reduce_edge_list(SCREAMING_SNAKE_CASE__ ) if end_edges is None: __UpperCamelCase =[e == (d - 1) for e, d in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] reduce_edge_list(SCREAMING_SNAKE_CASE__ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(SCREAMING_SNAKE_CASE__ ) == 0: return [()] elif len(SCREAMING_SNAKE_CASE__ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] __UpperCamelCase =[] __UpperCamelCase =[] # Dimensions common to start and end can be selected directly for s, e in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if s == e: path_list.append(slice(SCREAMING_SNAKE_CASE__ , s + 1 ) ) else: break __UpperCamelCase =tuple(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) # start == end, and we're done if divergence_idx == len(SCREAMING_SNAKE_CASE__ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None __UpperCamelCase =start[divergence_idx] return tuple( path + (slice(SCREAMING_SNAKE_CASE__ , 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 __UpperCamelCase =end[divergence_idx] return tuple( path + (slice(SCREAMING_SNAKE_CASE__ , 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() ) __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =t.shape[:no_batch_dims] __UpperCamelCase =list(_flat_idx_to_idx(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # _get_minimal_slice_set is inclusive __UpperCamelCase =list(_flat_idx_to_idx(flat_end - 1 , SCREAMING_SNAKE_CASE__ ) ) # Get an ordered list of slices to perform __UpperCamelCase =_get_minimal_slice_set( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) __UpperCamelCase =[t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : Dict[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Any = None , SCREAMING_SNAKE_CASE__ : bool = False , ): if not (len(SCREAMING_SNAKE_CASE__ ) > 0): raise ValueError('Must provide at least one input' ) __UpperCamelCase =[shape[:no_batch_dims] for shape in _fetch_dims(SCREAMING_SNAKE_CASE__ )] __UpperCamelCase =tuple([max(SCREAMING_SNAKE_CASE__ ) for s in zip(*SCREAMING_SNAKE_CASE__ )] ) def _prep_inputs(SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: __UpperCamelCase =t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) __UpperCamelCase =t.reshape(-1 , *t.shape[no_batch_dims:] ) else: __UpperCamelCase =t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t __UpperCamelCase =tensor_tree_map(_prep_inputs , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =None if _out is not None: __UpperCamelCase =tensor_tree_map(lambda SCREAMING_SNAKE_CASE__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) __UpperCamelCase =1 for d in orig_batch_dims: flat_batch_dim *= d __UpperCamelCase =flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t __UpperCamelCase =0 __UpperCamelCase =prepped_outputs for _ in range(SCREAMING_SNAKE_CASE__ ): # Chunk the input if not low_mem: __UpperCamelCase =_select_chunk else: __UpperCamelCase =partial( _chunk_slice , flat_start=SCREAMING_SNAKE_CASE__ , flat_end=min(SCREAMING_SNAKE_CASE__ , i + chunk_size ) , no_batch_dims=len(SCREAMING_SNAKE_CASE__ ) , ) __UpperCamelCase =tensor_tree_map(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Run the layer on the chunk __UpperCamelCase =layer(**SCREAMING_SNAKE_CASE__ ) # Allocate space for the output if out is None: __UpperCamelCase =tensor_tree_map(lambda SCREAMING_SNAKE_CASE__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , SCREAMING_SNAKE_CASE__ ) # Put the chunk in its pre-allocated space if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def assign(SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : dict ) -> None: for k, v in da.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assign(SCREAMING_SNAKE_CASE__ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: __UpperCamelCase =da[k] assign(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for xa, xa in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if _add_into_out: xa[i : i + chunk_size] += xa else: __UpperCamelCase =xa elif isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: __UpperCamelCase =output_chunk else: raise ValueError('Not supported' ) i += chunk_size __UpperCamelCase =tensor_tree_map(lambda SCREAMING_SNAKE_CASE__ : t.view(orig_batch_dims + t.shape[1:] ) , SCREAMING_SNAKE_CASE__ ) return out class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = 512 , ) -> Tuple: __UpperCamelCase =max_chunk_size __UpperCamelCase =None __UpperCamelCase =None def _a ( self , A_ , A_ , A_ ) -> int: logging.info('Tuning chunk size...' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size __UpperCamelCase =[2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] __UpperCamelCase =[c for c in candidates if c > min_chunk_size] __UpperCamelCase =[min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(A_ ) -> bool: try: with torch.no_grad(): fn(*A_ , chunk_size=A_ ) return True except RuntimeError: return False __UpperCamelCase =0 __UpperCamelCase =len(A_ ) - 1 while i > min_viable_chunk_size_index: __UpperCamelCase =test_chunk_size(candidates[i] ) if not viable: __UpperCamelCase =(min_viable_chunk_size_index + i) // 2 else: __UpperCamelCase =i __UpperCamelCase =(i + len(A_ ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _a ( self , A_ , A_ ) -> bool: __UpperCamelCase =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_ ): __UpperCamelCase =[v for _, v in sorted(aa.items() , key=lambda A_ : x[0] )] __UpperCamelCase =[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 , A_ , A_ , A_ , ) -> int: __UpperCamelCase =True __UpperCamelCase =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_ ) __UpperCamelCase =self._compare_arg_caches(self.cached_arg_data , A_ ) else: # Otherwise, we can reuse the precomputed value __UpperCamelCase =False if not consistent: __UpperCamelCase =self._determine_favorable_chunk_size( A_ , A_ , A_ , ) __UpperCamelCase =arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
62
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( 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: __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _A = logging.get_logger(__name__) # pylint: disable=invalid-name _A = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any]=8 ): __UpperCamelCase =height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __UpperCamelCase =width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ , A_ , ) -> int: super().__init__() self.register_modules( unet=A_ , scheduler=A_ , movq=A_ , ) __UpperCamelCase =2 ** (len(self.movq.config.block_out_channels ) - 1) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> Tuple: if latents is None: __UpperCamelCase =randn_tensor(A_ , generator=A_ , device=A_ , dtype=A_ ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) __UpperCamelCase =latents.to(A_ ) __UpperCamelCase =latents * scheduler.init_noise_sigma return latents def _a ( self , A_=0 ) -> List[str]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __UpperCamelCase =torch.device(f'cuda:{gpu_id}' ) __UpperCamelCase =[ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A_ , A_ ) def _a ( self , A_=0 ) -> Tuple: if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __UpperCamelCase =torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=A_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __UpperCamelCase =None for cpu_offloaded_model in [self.unet, self.movq]: __UpperCamelCase , __UpperCamelCase =cpu_offload_with_hook(A_ , A_ , prev_module_hook=A_ ) # We'll offload the last model manually. __UpperCamelCase =hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _a ( self ) -> Dict: if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(A_ , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A_ ) def __call__( self , A_ , A_ , A_ = 512 , A_ = 512 , A_ = 100 , A_ = 4.0 , A_ = 1 , A_ = None , A_ = None , A_ = "pil" , A_ = True , ) -> Dict: __UpperCamelCase =self._execution_device __UpperCamelCase =guidance_scale > 1.0 if isinstance(A_ , A_ ): __UpperCamelCase =torch.cat(A_ , dim=0 ) __UpperCamelCase =image_embeds.shape[0] * num_images_per_prompt if isinstance(A_ , A_ ): __UpperCamelCase =torch.cat(A_ , dim=0 ) if do_classifier_free_guidance: __UpperCamelCase =image_embeds.repeat_interleave(A_ , dim=0 ) __UpperCamelCase =negative_image_embeds.repeat_interleave(A_ , dim=0 ) __UpperCamelCase =torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A_ ) self.scheduler.set_timesteps(A_ , device=A_ ) __UpperCamelCase =self.scheduler.timesteps __UpperCamelCase =self.unet.config.in_channels __UpperCamelCase , __UpperCamelCase =downscale_height_and_width(A_ , A_ , self.movq_scale_factor ) # create initial latent __UpperCamelCase =self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A_ , A_ , A_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A_ ) ): # expand the latents if we are doing classifier free guidance __UpperCamelCase =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __UpperCamelCase ={'image_embeds': image_embeds} __UpperCamelCase =self.unet( sample=A_ , timestep=A_ , encoder_hidden_states=A_ , added_cond_kwargs=A_ , return_dict=A_ , )[0] if do_classifier_free_guidance: __UpperCamelCase , __UpperCamelCase =noise_pred.split(latents.shape[1] , dim=1 ) __UpperCamelCase , __UpperCamelCase =noise_pred.chunk(2 ) __UpperCamelCase , __UpperCamelCase =variance_pred.chunk(2 ) __UpperCamelCase =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __UpperCamelCase =torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __UpperCamelCase , __UpperCamelCase =noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __UpperCamelCase =self.scheduler.step( A_ , A_ , A_ , generator=A_ , )[0] # post-processing __UpperCamelCase =self.movq.decode(A_ , force_not_quantize=A_ )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: __UpperCamelCase =image * 0.5 + 0.5 __UpperCamelCase =image.clamp(0 , 1 ) __UpperCamelCase =image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __UpperCamelCase =self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from __future__ import annotations import collections import pprint from pathlib import Path def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): return "".join(sorted(SCREAMING_SNAKE_CASE__ ) ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): return word_by_signature[signature(SCREAMING_SNAKE_CASE__ )] _A = Path(__file__).parent.joinpath('words.txt').read_text(encoding='utf-8') _A = sorted({word.strip().lower() for word in data.splitlines()}) _A = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": _A = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('anagrams.txt', 'w') as file: file.write('all_anagrams = \n ') file.write(pprint.pformat(all_anagrams))
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _A = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase__ : Any = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: UpperCAmelCase__ : Tuple = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: UpperCAmelCase__ : List[str] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def _a ( self , A_ , A_ , A_ ) -> List[str]: __UpperCamelCase =ZeroShotClassificationPipeline( model=A_ , tokenizer=A_ , candidate_labels=['polics', 'health'] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def _a ( self , A_ , A_ ) -> Any: __UpperCamelCase =classifier('Who are you voting for in 2020?' , candidate_labels='politics' ) self.assertEqual(A_ , {'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) # No kwarg __UpperCamelCase =classifier('Who are you voting for in 2020?' , ['politics'] ) self.assertEqual(A_ , {'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) __UpperCamelCase =classifier('Who are you voting for in 2020?' , candidate_labels=['politics'] ) self.assertEqual(A_ , {'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) __UpperCamelCase =classifier('Who are you voting for in 2020?' , candidate_labels='politics, public health' ) self.assertEqual( A_ , {'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) __UpperCamelCase =classifier('Who are you voting for in 2020?' , candidate_labels=['politics', 'public health'] ) self.assertEqual( A_ , {'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) __UpperCamelCase =classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='This text is about {}' ) self.assertEqual(A_ , {'sequence': ANY(A_ ), 'labels': [ANY(A_ )], 'scores': [ANY(A_ )]} ) # https://github.com/huggingface/transformers/issues/13846 __UpperCamelCase =classifier(['I am happy'] , ['positive', 'negative'] ) self.assertEqual( A_ , [ {'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} for i in range(1 ) ] , ) __UpperCamelCase =classifier(['I am happy', 'I am sad'] , ['positive', 'negative'] ) self.assertEqual( A_ , [ {'sequence': ANY(A_ ), 'labels': [ANY(A_ ), ANY(A_ )], 'scores': [ANY(A_ ), ANY(A_ )]} for i in range(2 ) ] , ) with self.assertRaises(A_ ): classifier('' , candidate_labels='politics' ) with self.assertRaises(A_ ): classifier(A_ , candidate_labels='politics' ) with self.assertRaises(A_ ): classifier('Who are you voting for in 2020?' , candidate_labels='' ) with self.assertRaises(A_ ): classifier('Who are you voting for in 2020?' , candidate_labels=A_ ) with self.assertRaises(A_ ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='Not formatting template' , ) with self.assertRaises(A_ ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template=A_ , ) self.run_entailment_id(A_ ) def _a ( self , A_ ) -> Dict: __UpperCamelCase =zero_shot_classifier.model.config __UpperCamelCase =config.labelaid __UpperCamelCase =zero_shot_classifier.entailment_id __UpperCamelCase ={'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __UpperCamelCase ={'entailment': 0, 'neutral': 1, 'contradiction': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __UpperCamelCase ={'ENTAIL': 0, 'NON-ENTAIL': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __UpperCamelCase ={'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __UpperCamelCase =original_labelaid self.assertEqual(A_ , zero_shot_classifier.entailment_id ) @require_torch def _a ( self ) -> Optional[Any]: __UpperCamelCase =pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( 'Who are you voting for in 2020?' * 100 , candidate_labels=['politics', 'public health', 'science'] ) @require_torch def _a ( self ) -> int: __UpperCamelCase =pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) __UpperCamelCase =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.333, 0.333, 0.333], } , ) @require_tf def _a ( self ) -> List[Any]: __UpperCamelCase =pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='tf' , ) __UpperCamelCase =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.333, 0.333, 0.333], } , ) @slow @require_torch def _a ( self ) -> List[Any]: __UpperCamelCase =pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='pt' ) __UpperCamelCase =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.976, 0.015, 0.009], } , ) __UpperCamelCase =zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=A_ , ) self.assertEqual( nested_simplify(A_ ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def _a ( self ) -> List[str]: __UpperCamelCase =pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='tf' ) __UpperCamelCase =zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(A_ ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.976, 0.015, 0.009], } , ) __UpperCamelCase =zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=A_ , ) self.assertEqual( nested_simplify(A_ ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.817, 0.713, 0.018, 0.018], } , )
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMSNModel', 'ViTMSNForImageClassification', 'ViTMSNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __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 =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
# Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union _A = re.compile(R'^(?P<major>\d+)' R'\.(?P<minor>\d+)' R'\.(?P<patch>\d+)$') @total_ordering @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str UpperCAmelCase__ : Optional[str] = None UpperCAmelCase__ : Optional[Union[str, int]] = None UpperCAmelCase__ : Optional[Union[str, int]] = None UpperCAmelCase__ : Optional[Union[str, int]] = None def _a ( self ) -> Dict: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =_str_to_version_tuple(self.version_str ) def __repr__( self ) -> List[Any]: return f'{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}' @property def _a ( self ) -> List[str]: return self.major, self.minor, self.patch def _a ( self , A_ ) -> Optional[Any]: if isinstance(A_ , A_ ): return Version(A_ ) elif isinstance(A_ , A_ ): return other raise TypeError(f'{other} (type {type(A_ )}) cannot be compared to version.' ) def __eq__( self , A_ ) -> Union[str, Any]: try: __UpperCamelCase =self._validate_operand(A_ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self , A_ ) -> Optional[int]: __UpperCamelCase =self._validate_operand(A_ ) return self.tuple < other.tuple def __hash__( self ) -> Optional[Any]: return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def _a ( cls , A_ ) -> Tuple: __UpperCamelCase ={f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def _a ( self ) -> str: return self.version_str def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =_VERSION_REG.match(SCREAMING_SNAKE_CASE__ ) if not res: raise ValueError(F'Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.' ) return tuple(int(SCREAMING_SNAKE_CASE__ ) for v in [res.group('major' ), res.group('minor' ), res.group('patch' )] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): return ".".join(str(SCREAMING_SNAKE_CASE__ ) for v in version_tuple )
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): if index == number_of_items: return 0 __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =knapsack(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 ) if weights[index] <= max_weight: __UpperCamelCase =values[index] + knapsack( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , max_weight - weights[index] , index + 1 ) return max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Tuple = "philschmid/bart-large-cnn-samsum" UpperCAmelCase__ : Optional[Any] = ( "This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, " "and returns a summary of the text." ) UpperCAmelCase__ : Optional[Any] = "summarizer" UpperCAmelCase__ : Optional[int] = AutoTokenizer UpperCAmelCase__ : str = AutoModelForSeqaSeqLM UpperCAmelCase__ : Any = ["text"] UpperCAmelCase__ : str = ["text"] def _a ( self , A_ ) -> Optional[Any]: return self.pre_processor(A_ , return_tensors='pt' , truncation=A_ ) def _a ( self , A_ ) -> Dict: return self.model.generate(**A_ )[0] def _a ( self , A_ ) -> List[str]: return self.pre_processor.decode(A_ , skip_special_tokens=A_ , clean_up_tokenization_spaces=A_ )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '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 _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
from __future__ import annotations def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): if partitions <= 0: raise ValueError('partitions must be a positive number!' ) if partitions > number_of_bytes: raise ValueError('partitions can not > number_of_bytes!' ) __UpperCamelCase =number_of_bytes // partitions __UpperCamelCase =[] for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =i * bytes_per_partition + 1 __UpperCamelCase =( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(F'{start_bytes}-{end_bytes}' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
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
import argparse import json from tqdm import tqdm def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=SCREAMING_SNAKE_CASE__ , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=SCREAMING_SNAKE_CASE__ , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=SCREAMING_SNAKE_CASE__ , help='where to store parsed gold_data_path file' , ) __UpperCamelCase =parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __UpperCamelCase =json.load(SCREAMING_SNAKE_CASE__ ) for dpr_record in tqdm(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =dpr_record['question'] __UpperCamelCase =[context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(SCREAMING_SNAKE_CASE__ ) + '\n' ) if __name__ == "__main__": main()
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '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 _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin _A = get_tests_dir('fixtures/test_sentencepiece.model') _A = get_tests_dir('fixtures/test_sentencepiece_bpe.model') _A = 'pt' if is_torch_available() else 'tf' @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = CamembertTokenizer UpperCAmelCase__ : Tuple = CamembertTokenizerFast UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : List[Any] = True def _a ( self ) -> List[str]: super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase =CamembertTokenizer(A_ ) tokenizer.save_pretrained(self.tmpdirname ) def _a ( self ) -> str: __UpperCamelCase ='<pad>' __UpperCamelCase =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ ) def _a ( self ) -> int: __UpperCamelCase =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(A_ ) , 1004 ) def _a ( self ) -> int: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def _a ( self ) -> Optional[int]: __UpperCamelCase =CamembertTokenizer(A_ ) tokenizer.save_pretrained(self.tmpdirname ) __UpperCamelCase =CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =tokenizer.encode(A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) __UpperCamelCase =tokenizer.convert_ids_to_tokens(A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Optional[Any]: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =tokenizer.tokenize(A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase =tokenizer.encode(A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) @slow def _a ( self ) -> Union[str, Any]: # fmt: off __UpperCamelCase ={'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. __UpperCamelCase =[ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=A_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=A_ , )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _A = logging.get_logger(__name__) _A = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } _A = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } _A = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _UpperCAmelCase ( ): __UpperCamelCase =( list(range(ord('!' ) , ord('~' ) + 1 ) ) + list(range(ord('¡' ) , ord('¬' ) + 1 ) ) + list(range(ord('®' ) , ord('ÿ' ) + 1 ) ) ) __UpperCamelCase =bs[:] __UpperCamelCase =0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE__ ) cs.append(2**8 + n ) n += 1 __UpperCamelCase =[chr(SCREAMING_SNAKE_CASE__ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple ): __UpperCamelCase =set() __UpperCamelCase =word[0] for char in word[1:]: pairs.add((prev_char, char) ) __UpperCamelCase =char return pairs class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : List[str] = VOCAB_FILES_NAMES UpperCAmelCase__ : List[Any] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Dict = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="replace" , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_=False , **A_ , ) -> Union[str, Any]: __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else bos_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else eos_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else sep_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else cls_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else unk_token __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token super().__init__( errors=A_ , bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , add_prefix_space=A_ , **A_ , ) with open(A_ , encoding='utf-8' ) as vocab_handle: __UpperCamelCase =json.load(A_ ) __UpperCamelCase ={v: k for k, v in self.encoder.items()} __UpperCamelCase =errors # how to handle errors in decoding __UpperCamelCase =bytes_to_unicode() __UpperCamelCase ={v: k for k, v in self.byte_encoder.items()} with open(A_ , encoding='utf-8' ) as merges_handle: __UpperCamelCase =merges_handle.read().split('\n' )[1:-1] __UpperCamelCase =[tuple(merge.split() ) for merge in bpe_merges] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase ={} __UpperCamelCase =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __UpperCamelCase =re.compile(r'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def _a ( self ) -> Union[str, Any]: return len(self.encoder ) def _a ( self ) -> Union[str, Any]: return dict(self.encoder , **self.added_tokens_encoder ) def _a ( self , A_ ) -> List[str]: if token in self.cache: return self.cache[token] __UpperCamelCase =tuple(A_ ) __UpperCamelCase =get_pairs(A_ ) if not pairs: return token while True: __UpperCamelCase =min(A_ , key=lambda A_ : self.bpe_ranks.get(A_ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break __UpperCamelCase , __UpperCamelCase =bigram __UpperCamelCase =[] __UpperCamelCase =0 while i < len(A_ ): try: __UpperCamelCase =word.index(A_ , A_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __UpperCamelCase =j if word[i] == first and i < len(A_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __UpperCamelCase =tuple(A_ ) __UpperCamelCase =new_word if len(A_ ) == 1: break else: __UpperCamelCase =get_pairs(A_ ) __UpperCamelCase =' '.join(A_ ) __UpperCamelCase =word return word def _a ( self , A_ ) -> Tuple: __UpperCamelCase =[] for token in re.findall(self.pat , A_ ): __UpperCamelCase =''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A_ ).split(' ' ) ) return bpe_tokens def _a ( self , A_ ) -> Dict: return self.encoder.get(A_ , self.encoder.get(self.unk_token ) ) def _a ( self , A_ ) -> Optional[Any]: return self.decoder.get(A_ ) def _a ( self , A_ ) -> int: __UpperCamelCase =''.join(A_ ) __UpperCamelCase =bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(A_ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=A_ , ensure_ascii=A_ ) + '\n' ) __UpperCamelCase =0 with open(A_ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda A_ : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ' Please check that the tokenizer is not corrupted!' ) __UpperCamelCase =token_index writer.write(' '.join(A_ ) + '\n' ) index += 1 return vocab_file, merge_file def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _a ( self , A_ , A_=False , **A_ ) -> Tuple: __UpperCamelCase =kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(A_ ) > 0 and not text[0].isspace()): __UpperCamelCase =' ' + text return (text, kwargs) def _a ( self , A_ , A_ = None ) -> Tuple: return token_ids_a + [self.eos_token_id] def _a ( self , A_ ) -> List[int]: __UpperCamelCase =[] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(' ' + text ) else: # Generated responses should contain them already. inputs.append(A_ ) __UpperCamelCase =' '.join(A_ ) __UpperCamelCase =self.encode(A_ ) if len(A_ ) > self.model_max_length: __UpperCamelCase =input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import fire from utils import calculate_rouge, save_json def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=None , **SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =[x.strip() for x in open(SCREAMING_SNAKE_CASE__ ).readlines()] __UpperCamelCase =[x.strip() for x in open(SCREAMING_SNAKE_CASE__ ).readlines()][: len(SCREAMING_SNAKE_CASE__ )] __UpperCamelCase =calculate_rouge(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if save_path is not None: save_json(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , indent=SCREAMING_SNAKE_CASE__ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =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 __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =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()
62
1
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[int]: __UpperCamelCase =inspect.getfile(accelerate.test_utils ) __UpperCamelCase =os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __UpperCamelCase =test_metrics @require_cpu def _a ( self ) -> Optional[int]: debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ) -> str: debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ) -> Optional[int]: self.test_metrics.main() @require_multi_gpu def _a ( self ) -> int: print(f'Found {torch.cuda.device_count()} devices.' ) __UpperCamelCase =['torchrun', f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(A_ , env=os.environ.copy() )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from __future__ import annotations import queue class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> Optional[int]: __UpperCamelCase =data __UpperCamelCase =None __UpperCamelCase =None def _UpperCAmelCase ( ): print('\n********Press N to stop entering at any point of time********\n' ) __UpperCamelCase =input('Enter the value of the root node: ' ).strip().lower() __UpperCamelCase =queue.Queue() __UpperCamelCase =TreeNode(int(SCREAMING_SNAKE_CASE__ ) ) q.put(SCREAMING_SNAKE_CASE__ ) while not q.empty(): __UpperCamelCase =q.get() __UpperCamelCase =F'Enter the left node of {node_found.data}: ' __UpperCamelCase =input(SCREAMING_SNAKE_CASE__ ).strip().lower() or 'n' if check == "n": return tree_node __UpperCamelCase =TreeNode(int(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =left_node q.put(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =F'Enter the right node of {node_found.data}: ' __UpperCamelCase =input(SCREAMING_SNAKE_CASE__ ).strip().lower() or 'n' if check == "n": return tree_node __UpperCamelCase =TreeNode(int(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =right_node q.put(SCREAMING_SNAKE_CASE__ ) raise def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return print(node.data , end=',' ) pre_order(node.left ) pre_order(node.right ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return in_order(node.left ) print(node.data , end=',' ) in_order(node.right ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=',' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return __UpperCamelCase =queue.Queue() q.put(SCREAMING_SNAKE_CASE__ ) while not q.empty(): __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return __UpperCamelCase =queue.Queue() q.put(SCREAMING_SNAKE_CASE__ ) while not q.empty(): __UpperCamelCase =[] while not q.empty(): __UpperCamelCase =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(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return __UpperCamelCase =[] __UpperCamelCase =node while n or stack: while n: # start from root node, find its left child print(n.data , end=',' ) stack.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =n.left # end of while means current node doesn't have left child __UpperCamelCase =stack.pop() # start to traverse its right child __UpperCamelCase =n.right def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return __UpperCamelCase =[] __UpperCamelCase =node while n or stack: while n: stack.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =n.left __UpperCamelCase =stack.pop() print(n.data , end=',' ) __UpperCamelCase =n.right def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : TreeNode ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not node: return __UpperCamelCase , __UpperCamelCase =[], [] __UpperCamelCase =node stacka.append(SCREAMING_SNAKE_CASE__ ) while stacka: # to find the reversed order of post order, store it in stack2 __UpperCamelCase =stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(SCREAMING_SNAKE_CASE__ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=',' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" , SCREAMING_SNAKE_CASE__ : Optional[int]=50 , SCREAMING_SNAKE_CASE__ : Tuple="*" ): if not s: return "\n" + width * char __UpperCamelCase , __UpperCamelCase =divmod(width - len(SCREAMING_SNAKE_CASE__ ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) _A = 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())
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' 'The config can simply be saved and uploaded again to be fixed.' )
62
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __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 =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __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(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('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(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , 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 ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
from __future__ import annotations from collections import deque class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> Union[str, Any]: __UpperCamelCase =[] self.adlist.append( {'value': '', 'next_states': [], 'fail_state': 0, 'output': []} ) for keyword in keywords: self.add_keyword(A_ ) self.set_fail_transitions() def _a ( self , A_ , A_ ) -> int | None: for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def _a ( self , A_ ) -> None: __UpperCamelCase =0 for character in keyword: __UpperCamelCase =self.find_next_state(A_ , A_ ) if next_state is None: self.adlist.append( { 'value': character, 'next_states': [], 'fail_state': 0, 'output': [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) __UpperCamelCase =len(self.adlist ) - 1 else: __UpperCamelCase =next_state self.adlist[current_state]["output"].append(A_ ) def _a ( self ) -> None: __UpperCamelCase =deque() for node in self.adlist[0]["next_states"]: q.append(A_ ) __UpperCamelCase =0 while q: __UpperCamelCase =q.popleft() for child in self.adlist[r]["next_states"]: q.append(A_ ) __UpperCamelCase =self.adlist[r]['fail_state'] while ( self.find_next_state(A_ , self.adlist[child]['value'] ) is None and state != 0 ): __UpperCamelCase =self.adlist[state]['fail_state'] __UpperCamelCase =self.find_next_state( A_ , self.adlist[child]['value'] ) if self.adlist[child]["fail_state"] is None: __UpperCamelCase =0 __UpperCamelCase =( self.adlist[child]['output'] + self.adlist[self.adlist[child]['fail_state']]['output'] ) def _a ( self , A_ ) -> dict[str, list[int]]: __UpperCamelCase ={} # returns a dict with keywords and list of its occurrences __UpperCamelCase =0 for i in range(len(A_ ) ): while ( self.find_next_state(A_ , string[i] ) is None and current_state != 0 ): __UpperCamelCase =self.adlist[current_state]['fail_state'] __UpperCamelCase =self.find_next_state(A_ , string[i] ) if next_state is None: __UpperCamelCase =0 else: __UpperCamelCase =next_state for key in self.adlist[current_state]["output"]: if key not in result: __UpperCamelCase =[] result[key].append(i - len(A_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() _A = { 'bart': ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'bert': ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'bert-base-cased-finetuned-mrpc': ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'dpr': ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'gpt2': ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlnet': ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm': ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'xlm-roberta': ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'transfo-xl': ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'openai-gpt': ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'roberta': ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'layoutlm': ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), 'roberta-large-mnli': ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'camembert': ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'flaubert': ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert': ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'distilbert-base-distilled-squad': ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert': ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'lxmert-visual-feature-encoder': ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'ctrl': ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'albert': ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 't5': ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'electra': ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), 'wav2vec2': ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Optional[int]=True ): if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __UpperCamelCase =cached_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) __UpperCamelCase =config_class.from_json_file(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =True __UpperCamelCase =True print(F'Building TensorFlow model from configuration: {config}' ) __UpperCamelCase =model_class(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __UpperCamelCase =cached_file( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __UpperCamelCase =load_pytorch_checkpoint_in_tfa_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if compare_with_pt_model: __UpperCamelCase =tf_model(tf_model.dummy_inputs , training=SCREAMING_SNAKE_CASE__ ) # build the network __UpperCamelCase =torch.load(SCREAMING_SNAKE_CASE__ , map_location='cpu' ) __UpperCamelCase =pt_model_class.from_pretrained( pretrained_model_name_or_path=SCREAMING_SNAKE_CASE__ , config=SCREAMING_SNAKE_CASE__ , state_dict=SCREAMING_SNAKE_CASE__ ) with torch.no_grad(): __UpperCamelCase =pt_model(**pt_model.dummy_inputs ) __UpperCamelCase =pto[0].numpy() __UpperCamelCase =tfo[0].numpy() __UpperCamelCase =np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2E-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(SCREAMING_SNAKE_CASE__ , save_format='h5' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=False , ): if args_model_type is None: __UpperCamelCase =list(MODEL_CLASSES.keys() ) else: __UpperCamelCase =[args_model_type] for j, model_type in enumerate(SCREAMING_SNAKE_CASE__ , start=1 ): print('=' * 1_00 ) print(F' Converting model type {j}/{len(SCREAMING_SNAKE_CASE__ )}: {model_type}' ) print('=' * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __UpperCamelCase =list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __UpperCamelCase =model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , start=1 ): print('-' * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __UpperCamelCase =model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(SCREAMING_SNAKE_CASE__ )}: {model_shortcut_name} - model_type {model_type}' ) print('-' * 1_00 ) if config_shortcut_name in aws_config_map: __UpperCamelCase =cached_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) else: __UpperCamelCase =config_shortcut_name if model_shortcut_name in aws_model_maps: __UpperCamelCase =cached_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , force_download=not use_cached_models ) else: __UpperCamelCase =model_shortcut_name if os.path.isfile(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase ='converted_model' convert_pt_checkpoint_to_tf( model_type=SCREAMING_SNAKE_CASE__ , pytorch_checkpoint_path=SCREAMING_SNAKE_CASE__ , config_file=SCREAMING_SNAKE_CASE__ , tf_dump_path=os.path.join(SCREAMING_SNAKE_CASE__ , model_shortcut_name + '-tf_model.h5' ) , compare_with_pt_model=SCREAMING_SNAKE_CASE__ , ) if remove_cached_files: os.remove(SCREAMING_SNAKE_CASE__ ) os.remove(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_dump_path', default=None, type=str, required=True, help='Path to the output Tensorflow dump file.' ) parser.add_argument( '--model_type', default=None, type=str, help=( f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """ 'convert all the models from AWS.' ), ) parser.add_argument( '--pytorch_checkpoint_path', default=None, type=str, help=( 'Path to the PyTorch checkpoint path or shortcut name to download from AWS. ' 'If not given, will download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--config_file', default=None, type=str, help=( 'The config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture. If not given and ' '--pytorch_checkpoint_path is not given or is a shortcut name ' 'use the configuration associated to the shortcut name on the AWS' ), ) parser.add_argument( '--compare_with_pt_model', action='store_true', help='Compare Tensorflow and PyTorch model predictions.' ) parser.add_argument( '--use_cached_models', action='store_true', help='Use cached models if possible instead of updating to latest checkpoint versions.', ) parser.add_argument( '--remove_cached_files', action='store_true', help='Remove pytorch models after conversion (save memory when converting in batches).', ) parser.add_argument('--only_convert_finetuned_models', action='store_true', help='Only convert finetuned models.') _A = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : NDArray[floataa] , SCREAMING_SNAKE_CASE__ : NDArray[floataa] , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , ): __UpperCamelCase , __UpperCamelCase =coefficient_matrix.shape __UpperCamelCase , __UpperCamelCase =constant_matrix.shape if rowsa != colsa: __UpperCamelCase =F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}' raise ValueError(SCREAMING_SNAKE_CASE__ ) if colsa != 1: __UpperCamelCase =F'Constant matrix must be nx1 but received {rowsa}x{colsa}' raise ValueError(SCREAMING_SNAKE_CASE__ ) if rowsa != rowsa: __UpperCamelCase =( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' F'received {rowsa}x{colsa} and {rowsa}x{colsa}' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) != rowsa: __UpperCamelCase =( 'Number of initial values must be equal to number of rows in coefficient ' F'matrix but received {len(SCREAMING_SNAKE_CASE__ )} and {rowsa}' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) if iterations <= 0: raise ValueError('Iterations must be at least 1' ) __UpperCamelCase =np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) __UpperCamelCase , __UpperCamelCase =table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE__ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[] for row in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =0 for col in range(SCREAMING_SNAKE_CASE__ ): if col == row: __UpperCamelCase =table[row][col] elif col == cols - 1: __UpperCamelCase =table[row][col] else: temp += (-1) * table[row][col] * init_val[col] __UpperCamelCase =(temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =new_val return [float(SCREAMING_SNAKE_CASE__ ) for i in new_val] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : NDArray[floataa] ): __UpperCamelCase , __UpperCamelCase =table.shape __UpperCamelCase =True for i in range(0 , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('Coefficient matrix is not strictly diagonally dominant' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = DiTPipeline UpperCAmelCase__ : int = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS UpperCAmelCase__ : Any = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } UpperCAmelCase__ : int = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS UpperCAmelCase__ : List[Any] = False def _a ( self ) -> Optional[Any]: torch.manual_seed(0 ) __UpperCamelCase =TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=A_ , activation_fn='gelu-approximate' , num_embeds_ada_norm=1000 , norm_type='ada_norm_zero' , norm_elementwise_affine=A_ , ) __UpperCamelCase =AutoencoderKL() __UpperCamelCase =DDIMScheduler() __UpperCamelCase ={'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler} return components def _a ( self , A_ , A_=0 ) -> Union[str, Any]: if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase ={ 'class_labels': [1], 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def _a ( self ) -> Any: __UpperCamelCase ='cpu' __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =self.get_dummy_inputs(A_ ) __UpperCamelCase =pipe(**A_ ).images __UpperCamelCase =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) __UpperCamelCase =np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) __UpperCamelCase =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(A_ , 1E-3 ) def _a ( self ) -> Tuple: self._test_inference_batch_single_identical(relax_max_difference=A_ , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def _a ( self ) -> Union[str, Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[int]: super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> List[str]: __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' ) pipe.to('cuda' ) __UpperCamelCase =['vase', 'umbrella', 'white shark', 'white wolf'] __UpperCamelCase =pipe.get_label_ids(A_ ) __UpperCamelCase =pipe(A_ , generator=A_ , num_inference_steps=40 , output_type='np' ).images for word, image in zip(A_ , A_ ): __UpperCamelCase =load_numpy( f'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' ) assert np.abs((expected_image - image).max() ) < 1E-2 def _a ( self ) -> Any: __UpperCamelCase =DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' ) __UpperCamelCase =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('cuda' ) __UpperCamelCase =['vase', 'umbrella'] __UpperCamelCase =pipe.get_label_ids(A_ ) __UpperCamelCase =torch.manual_seed(0 ) __UpperCamelCase =pipe(A_ , generator=A_ , num_inference_steps=25 , output_type='np' ).images for word, image in zip(A_ , A_ ): __UpperCamelCase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' f'/dit/{word}_512.npy' ) assert np.abs((expected_image - image).max() ) < 1E-1
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
_A = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' _A = [{'type': 'code', 'content': INSTALL_CONTENT}] _A = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
62
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( 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: __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = "open-llama" def __init__( self , A_=100000 , A_=4096 , A_=11008 , A_=32 , A_=32 , A_="silu" , A_=2048 , A_=0.02 , A_=1E-6 , A_=True , A_=0 , A_=1 , A_=2 , A_=False , A_=True , A_=0.1 , A_=0.1 , A_=True , A_=True , A_=None , **A_ , ) -> List[Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_act __UpperCamelCase =initializer_range __UpperCamelCase =rms_norm_eps __UpperCamelCase =use_cache __UpperCamelCase =kwargs.pop( 'use_memorry_efficient_attention' , A_ ) __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_dropout_prob __UpperCamelCase =use_stable_embedding __UpperCamelCase =shared_input_output_embedding __UpperCamelCase =rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , tie_word_embeddings=A_ , **A_ , ) def _a ( self ) -> List[str]: if self.rope_scaling is None: return if not isinstance(self.rope_scaling , A_ ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'got {self.rope_scaling}' ) __UpperCamelCase =self.rope_scaling.get('type' , A_ ) __UpperCamelCase =self.rope_scaling.get('factor' , A_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}' ) if rope_scaling_factor is None or not isinstance(A_ , A_ ) or rope_scaling_factor <= 1.0: raise ValueError(f'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _A = { 'configuration_clip': [ 'CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPConfig', 'CLIPOnnxConfig', 'CLIPTextConfig', 'CLIPVisionConfig', ], 'processing_clip': ['CLIPProcessor'], 'tokenization_clip': ['CLIPTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['CLIPTokenizerFast'] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['CLIPFeatureExtractor'] _A = ['CLIPImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPModel', 'CLIPPreTrainedModel', 'CLIPTextModel', 'CLIPTextModelWithProjection', 'CLIPVisionModel', 'CLIPVisionModelWithProjection', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCLIPModel', 'TFCLIPPreTrainedModel', 'TFCLIPTextModel', 'TFCLIPVisionModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'FlaxCLIPModel', 'FlaxCLIPPreTrainedModel', 'FlaxCLIPTextModel', 'FlaxCLIPTextPreTrainedModel', 'FlaxCLIPVisionModel', 'FlaxCLIPVisionPreTrainedModel', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_ibert': ['IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'IBertConfig', 'IBertOnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'IBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'IBertForMaskedLM', 'IBertForMultipleChoice', 'IBertForQuestionAnswering', 'IBertForSequenceClassification', 'IBertForTokenClassification', 'IBertModel', 'IBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __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 =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int = 10_00 ): __UpperCamelCase =2**power __UpperCamelCase =str(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =list(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =0 for i in list_num: sum_of_num += int(SCREAMING_SNAKE_CASE__ ) return sum_of_num if __name__ == "__main__": _A = int(input('Enter the power of 2: ').strip()) print('2 ^ ', power, ' = ', 2**power) _A = solution(power) print('Sum of the digits is: ', result)
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple ): __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ ).read() _check_json_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __UpperCamelCase =features.copy() if features else default_expected_features __UpperCamelCase =( Features({feature: Value(SCREAMING_SNAKE_CASE__ ) for feature, dtype in features.items()} ) if features is not None else None ) __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read() _check_json_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} __UpperCamelCase =features.copy() if features else default_expected_features __UpperCamelCase =( Features({feature: Value(SCREAMING_SNAKE_CASE__ ) for feature, dtype in features.items()} ) if features is not None else None ) __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read() assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} __UpperCamelCase ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} __UpperCamelCase =features.copy() __UpperCamelCase =( Features({feature: Value(SCREAMING_SNAKE_CASE__ ) for feature, dtype in features.items()} ) if features is not None else None ) __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read() assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Any ): __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ ).read() _check_json_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int ): if issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =jsonl_path elif issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[jsonl_path] __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read() _check_json_dataset(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any]=("train",) ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for split in splits: __UpperCamelCase =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __UpperCamelCase =JsonDatasetReader({'train': jsonl_path} , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ ).read() _check_json_datasetdict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ): __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __UpperCamelCase =features.copy() if features else default_expected_features __UpperCamelCase =( Features({feature: Value(SCREAMING_SNAKE_CASE__ ) for feature, dtype in features.items()} ) if features is not None else None ) __UpperCamelCase =JsonDatasetReader({'train': jsonl_path} , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read() _check_json_datasetdict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if split: __UpperCamelCase ={split: jsonl_path} else: __UpperCamelCase ='train' __UpperCamelCase ={'train': jsonl_path, 'test': jsonl_path} __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} __UpperCamelCase =JsonDatasetReader(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ).read() _check_json_datasetdict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): return json.load(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any ): return [json.loads(SCREAMING_SNAKE_CASE__ ) for line in buffer] class UpperCAmelCase__ : """simple docstring""" @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def _a ( self , A_ , A_ , A_ ) -> List[str]: with io.BytesIO() as buffer: JsonDatasetWriter(A_ , A_ , lines=A_ ).write() buffer.seek(0 ) __UpperCamelCase =load_json_function(A_ ) assert isinstance(A_ , A_ ) assert isinstance(exported_content[0] , A_ ) assert len(A_ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(A_ , A_ , lines=A_ , orient=A_ ).write() buffer.seek(0 ) __UpperCamelCase =load_json(A_ ) assert isinstance(A_ , A_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(A_ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(A_ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def _a ( self , A_ , A_ , A_ ) -> List[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(A_ , A_ , lines=A_ , num_proc=2 ).write() buffer.seek(0 ) __UpperCamelCase =load_json_function(A_ ) assert isinstance(A_ , A_ ) assert isinstance(exported_content[0] , A_ ) assert len(A_ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> Tuple: with io.BytesIO() as buffer: JsonDatasetWriter(A_ , A_ , lines=A_ , orient=A_ , num_proc=2 ).write() buffer.seek(0 ) __UpperCamelCase =load_json(A_ ) assert isinstance(A_ , A_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(A_ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(A_ ) == 10 def _a ( self , A_ ) -> Optional[Any]: with pytest.raises(A_ ): with io.BytesIO() as buffer: JsonDatasetWriter(A_ , A_ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int: __UpperCamelCase =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' __UpperCamelCase =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(A_ , A_ , compression=A_ ).write() with fsspec.open(A_ , 'rb' , compression='infer' ) as f: __UpperCamelCase =f.read() with fsspec.open(A_ , 'rb' , compression='infer' ) as f: __UpperCamelCase =f.read() assert exported_content == original_content
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from __future__ import annotations def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =list(range(len(SCREAMING_SNAKE_CASE__ ) ) ) __UpperCamelCase =[v / w for v, w in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] index.sort(key=lambda SCREAMING_SNAKE_CASE__ : ratio[i] , reverse=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =0 __UpperCamelCase =[0] * len(SCREAMING_SNAKE_CASE__ ) for i in index: if weight[i] <= capacity: __UpperCamelCase =1 max_value += value[i] capacity -= weight[i] else: __UpperCamelCase =capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if height >= 1: move_tower(height - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) move_disk(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) move_tower(height - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] ): print('moving disk from' , SCREAMING_SNAKE_CASE__ , 'to' , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): __UpperCamelCase =int(input('Height of hanoi: ' ).strip() ) move_tower(SCREAMING_SNAKE_CASE__ , 'A' , 'B' , 'C' ) if __name__ == "__main__": main()
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
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'microsoft/conditional-detr-resnet-50': ( 'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json' ), } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : List[Any] = "conditional_detr" UpperCAmelCase__ : Optional[Any] = ["past_key_values"] UpperCAmelCase__ : int = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self , A_=True , A_=None , A_=3 , A_=300 , A_=6 , A_=2048 , A_=8 , A_=6 , A_=2048 , A_=8 , A_=0.0 , A_=0.0 , A_=True , A_="relu" , A_=256 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=1.0 , A_=False , A_="sine" , A_="resnet50" , A_=True , A_=False , A_=2 , A_=5 , A_=2 , A_=1 , A_=1 , A_=2 , A_=5 , A_=2 , A_=0.25 , **A_ , ) -> Dict: if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) __UpperCamelCase =CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(A_ , A_ ): __UpperCamelCase =backbone_config.get('model_type' ) __UpperCamelCase =CONFIG_MAPPING[backbone_model_type] __UpperCamelCase =config_class.from_dict(A_ ) __UpperCamelCase =use_timm_backbone __UpperCamelCase =backbone_config __UpperCamelCase =num_channels __UpperCamelCase =num_queries __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =init_xavier_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =encoder_layers __UpperCamelCase =auxiliary_loss __UpperCamelCase =position_embedding_type __UpperCamelCase =backbone __UpperCamelCase =use_pretrained_backbone __UpperCamelCase =dilation # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =mask_loss_coefficient __UpperCamelCase =dice_loss_coefficient __UpperCamelCase =cls_loss_coefficient __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =focal_alpha super().__init__(is_encoder_decoder=A_ , **A_ ) @property def _a ( self ) -> int: return self.encoder_attention_heads @property def _a ( self ) -> int: return self.d_model def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __UpperCamelCase =self.backbone_config.to_dict() __UpperCamelCase =self.__class__.model_type return output class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def _a ( self ) -> float: return 1E-5 @property def _a ( self ) -> int: return 12
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '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 _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig _A = logging.get_logger(__name__) # General docstring _A = 'ResNetConfig' # Base docstring _A = 'microsoft/resnet-50' _A = [1, 2048, 7, 7] # Image classification docstring _A = 'microsoft/resnet-50' _A = 'tiger cat' _A = [ 'microsoft/resnet-50', # See all resnet models at https://huggingface.co/models?filter=resnet ] class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ , A_ , A_ = 3 , A_ = 1 , A_ = "relu" ) -> Optional[Any]: super().__init__() __UpperCamelCase =nn.Convad( A_ , A_ , kernel_size=A_ , stride=A_ , padding=kernel_size // 2 , bias=A_ ) __UpperCamelCase =nn.BatchNormad(A_ ) __UpperCamelCase =ACTaFN[activation] if activation is not None else nn.Identity() def _a ( self , A_ ) -> Tensor: __UpperCamelCase =self.convolution(A_ ) __UpperCamelCase =self.normalization(A_ ) __UpperCamelCase =self.activation(A_ ) return hidden_state class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ ) -> int: super().__init__() __UpperCamelCase =ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) __UpperCamelCase =nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) __UpperCamelCase =config.num_channels def _a ( self , A_ ) -> Tensor: __UpperCamelCase =pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' ) __UpperCamelCase =self.embedder(A_ ) __UpperCamelCase =self.pooler(A_ ) return embedding class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ , A_ , A_ = 2 ) -> Optional[int]: super().__init__() __UpperCamelCase =nn.Convad(A_ , A_ , kernel_size=1 , stride=A_ , bias=A_ ) __UpperCamelCase =nn.BatchNormad(A_ ) def _a ( self , A_ ) -> Tensor: __UpperCamelCase =self.convolution(A_ ) __UpperCamelCase =self.normalization(A_ ) return hidden_state class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ , A_ , A_ = 1 , A_ = "relu" ) -> Tuple: super().__init__() __UpperCamelCase =in_channels != out_channels or stride != 1 __UpperCamelCase =( ResNetShortCut(A_ , A_ , stride=A_ ) if should_apply_shortcut else nn.Identity() ) __UpperCamelCase =nn.Sequential( ResNetConvLayer(A_ , A_ , stride=A_ ) , ResNetConvLayer(A_ , A_ , activation=A_ ) , ) __UpperCamelCase =ACTaFN[activation] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =hidden_state __UpperCamelCase =self.layer(A_ ) __UpperCamelCase =self.shortcut(A_ ) hidden_state += residual __UpperCamelCase =self.activation(A_ ) return hidden_state class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ , A_ , A_ = 1 , A_ = "relu" , A_ = 4 ) -> Tuple: super().__init__() __UpperCamelCase =in_channels != out_channels or stride != 1 __UpperCamelCase =out_channels // reduction __UpperCamelCase =( ResNetShortCut(A_ , A_ , stride=A_ ) if should_apply_shortcut else nn.Identity() ) __UpperCamelCase =nn.Sequential( ResNetConvLayer(A_ , A_ , kernel_size=1 ) , ResNetConvLayer(A_ , A_ , stride=A_ ) , ResNetConvLayer(A_ , A_ , kernel_size=1 , activation=A_ ) , ) __UpperCamelCase =ACTaFN[activation] def _a ( self , A_ ) -> int: __UpperCamelCase =hidden_state __UpperCamelCase =self.layer(A_ ) __UpperCamelCase =self.shortcut(A_ ) hidden_state += residual __UpperCamelCase =self.activation(A_ ) return hidden_state class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ , A_ , A_ , A_ = 2 , A_ = 2 , ) -> int: super().__init__() __UpperCamelCase =ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer __UpperCamelCase =nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(A_ , A_ , stride=A_ , activation=config.hidden_act ) , *[layer(A_ , A_ , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def _a ( self , A_ ) -> Tensor: __UpperCamelCase =input for layer in self.layers: __UpperCamelCase =layer(A_ ) return hidden_state class UpperCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self , A_ ) -> Any: super().__init__() __UpperCamelCase =nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( A_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) __UpperCamelCase =zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(A_ , config.depths[1:] ): self.stages.append(ResNetStage(A_ , A_ , A_ , depth=A_ ) ) def _a ( self , A_ , A_ = False , A_ = True ) -> BaseModelOutputWithNoAttention: __UpperCamelCase =() if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __UpperCamelCase =hidden_states + (hidden_state,) __UpperCamelCase =stage_module(A_ ) if output_hidden_states: __UpperCamelCase =hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=A_ , hidden_states=A_ , ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : List[Any] = ResNetConfig UpperCAmelCase__ : Any = "resnet" UpperCAmelCase__ : Optional[int] = "pixel_values" UpperCAmelCase__ : List[str] = True def _a ( self , A_ ) -> str: if isinstance(A_ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' ) elif isinstance(A_ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def _a ( self , A_ , A_=False ) -> str: if isinstance(A_ , A_ ): __UpperCamelCase =value _A = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _A = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare ResNet model outputting raw features without any specific head on top." , A_ , ) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ ) -> List[Any]: super().__init__(A_ ) __UpperCamelCase =config __UpperCamelCase =ResNetEmbeddings(A_ ) __UpperCamelCase =ResNetEncoder(A_ ) __UpperCamelCase =nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A_ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A_ , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def _a ( self , A_ , A_ = None , A_ = None ) -> BaseModelOutputWithPoolingAndNoAttention: __UpperCamelCase =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __UpperCamelCase =return_dict if return_dict is not None else self.config.use_return_dict __UpperCamelCase =self.embedder(A_ ) __UpperCamelCase =self.encoder( A_ , output_hidden_states=A_ , return_dict=A_ ) __UpperCamelCase =encoder_outputs[0] __UpperCamelCase =self.pooler(A_ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A_ , pooler_output=A_ , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( "\n ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , A_ , ) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ ) -> List[Any]: super().__init__(A_ ) __UpperCamelCase =config.num_labels __UpperCamelCase =ResNetModel(A_ ) # classification head __UpperCamelCase =nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A_ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def _a ( self , A_ = None , A_ = None , A_ = None , A_ = None , ) -> ImageClassifierOutputWithNoAttention: __UpperCamelCase =return_dict if return_dict is not None else self.config.use_return_dict __UpperCamelCase =self.resnet(A_ , output_hidden_states=A_ , return_dict=A_ ) __UpperCamelCase =outputs.pooler_output if return_dict else outputs[1] __UpperCamelCase =self.classifier(A_ ) __UpperCamelCase =None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __UpperCamelCase ='regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __UpperCamelCase ='single_label_classification' else: __UpperCamelCase ='multi_label_classification' if self.config.problem_type == "regression": __UpperCamelCase =MSELoss() if self.num_labels == 1: __UpperCamelCase =loss_fct(logits.squeeze() , labels.squeeze() ) else: __UpperCamelCase =loss_fct(A_ , A_ ) elif self.config.problem_type == "single_label_classification": __UpperCamelCase =CrossEntropyLoss() __UpperCamelCase =loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __UpperCamelCase =BCEWithLogitsLoss() __UpperCamelCase =loss_fct(A_ , A_ ) if not return_dict: __UpperCamelCase =(logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A_ , logits=A_ , hidden_states=outputs.hidden_states ) @add_start_docstrings( "\n ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n " , A_ , ) class UpperCAmelCase__ ( A_ , A_ ): """simple docstring""" def __init__( self , A_ ) -> List[Any]: super().__init__(A_ ) super()._init_backbone(A_ ) __UpperCamelCase =[config.embedding_size] + config.hidden_sizes __UpperCamelCase =ResNetEmbeddings(A_ ) __UpperCamelCase =ResNetEncoder(A_ ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A_ ) @replace_return_docstrings(output_type=A_ , config_class=_CONFIG_FOR_DOC ) def _a ( self , A_ , A_ = None , A_ = None ) -> BackboneOutput: __UpperCamelCase =return_dict if return_dict is not None else self.config.use_return_dict __UpperCamelCase =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __UpperCamelCase =self.embedder(A_ ) __UpperCamelCase =self.encoder(A_ , output_hidden_states=A_ , return_dict=A_ ) __UpperCamelCase =outputs.hidden_states __UpperCamelCase =() for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: __UpperCamelCase =(feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=A_ , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=A_ , )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=4 , ) -> Union[str, Any]: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =seq_length __UpperCamelCase =is_training __UpperCamelCase =use_attention_mask __UpperCamelCase =use_token_type_ids __UpperCamelCase =use_labels __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =type_vocab_size __UpperCamelCase =type_sequence_label_size __UpperCamelCase =initializer_range __UpperCamelCase =num_choices def _a ( self ) -> Dict: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase =None if self.use_attention_mask: __UpperCamelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase =None if self.use_token_type_ids: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase =AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =config_and_inputs __UpperCamelCase ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def _a ( self ) -> Tuple: __UpperCamelCase =FlaxAlbertModelTester(self ) @slow def _a ( self ) -> str: for model_class_name in self.all_model_classes: __UpperCamelCase =model_class_name.from_pretrained('albert-base-v2' ) __UpperCamelCase =model(np.ones((1, 1) ) ) self.assertIsNotNone(A_ ) @require_flax class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def _a ( self ) -> str: __UpperCamelCase =FlaxAlbertModel.from_pretrained('albert-base-v2' ) __UpperCamelCase =np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __UpperCamelCase =np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __UpperCamelCase =model(A_ , attention_mask=A_ )[0] __UpperCamelCase =(1, 11, 768) self.assertEqual(output.shape , A_ ) __UpperCamelCase =np.array( [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , A_ , atol=1E-4 ) )
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=True , A_=True , A_=99 , A_=32 , A_=2 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ) -> Tuple: __UpperCamelCase =parent __UpperCamelCase =13 __UpperCamelCase =7 __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =99 __UpperCamelCase =32 __UpperCamelCase =2 __UpperCamelCase =4 __UpperCamelCase =37 __UpperCamelCase ='gelu' __UpperCamelCase =0.1 __UpperCamelCase =0.1 __UpperCamelCase =512 __UpperCamelCase =16 __UpperCamelCase =2 __UpperCamelCase =0.02 __UpperCamelCase =3 __UpperCamelCase =4 __UpperCamelCase =None def _a ( self ) -> List[Any]: __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 =None if self.use_token_type_ids: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase =ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase =RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=A_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> int: __UpperCamelCase =TFRoFormerModel(config=A_ ) __UpperCamelCase ={'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __UpperCamelCase =[input_ids, input_mask] __UpperCamelCase =model(A_ ) __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> int: __UpperCamelCase =True __UpperCamelCase =TFRoFormerForCausalLM(config=A_ ) __UpperCamelCase ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __UpperCamelCase =model(A_ )['logits'] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Union[str, Any]: __UpperCamelCase =TFRoFormerForMaskedLM(config=A_ ) __UpperCamelCase ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Dict: __UpperCamelCase =self.num_labels __UpperCamelCase =TFRoFormerForSequenceClassification(config=A_ ) __UpperCamelCase ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> List[Any]: __UpperCamelCase =self.num_choices __UpperCamelCase =TFRoFormerForMultipleChoice(config=A_ ) __UpperCamelCase =tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase =tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase =tf.tile(tf.expand_dims(A_ , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase ={ 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Tuple: __UpperCamelCase =self.num_labels __UpperCamelCase =TFRoFormerForTokenClassification(config=A_ ) __UpperCamelCase ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> List[Any]: __UpperCamelCase =TFRoFormerForQuestionAnswering(config=A_ ) __UpperCamelCase ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _a ( self ) -> Dict: __UpperCamelCase =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) =config_and_inputs __UpperCamelCase ={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) UpperCAmelCase__ : int = ( { "feature-extraction": TFRoFormerModel, "fill-mask": TFRoFormerForMaskedLM, "question-answering": TFRoFormerForQuestionAnswering, "text-classification": TFRoFormerForSequenceClassification, "text-generation": TFRoFormerForCausalLM, "token-classification": TFRoFormerForTokenClassification, "zero-shot": TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : Optional[Any] = False def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> List[Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def _a ( self ) -> str: __UpperCamelCase =TFRoFormerModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , hidden_size=37 ) def _a ( self ) -> Tuple: self.config_tester.run_common_tests() def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A_ ) def _a ( self ) -> Any: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A_ ) def _a ( self ) -> int: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A_ ) def _a ( self ) -> Dict: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A_ ) @slow def _a ( self ) -> Union[str, Any]: __UpperCamelCase =TFRoFormerModel.from_pretrained('junnyu/roformer_chinese_base' ) self.assertIsNotNone(A_ ) @require_tf class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def _a ( self ) -> Any: __UpperCamelCase =TFRoFormerForMaskedLM.from_pretrained('junnyu/roformer_chinese_base' ) __UpperCamelCase =tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase =model(A_ )[0] # TODO Replace vocab size __UpperCamelCase =50000 __UpperCamelCase =[1, 6, vocab_size] self.assertEqual(output.shape , A_ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. __UpperCamelCase =tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , A_ , atol=1E-4 ) @require_tf class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Any = 1e-4 def _a ( self ) -> Any: __UpperCamelCase =tf.constant([[4, 10]] ) __UpperCamelCase =TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) __UpperCamelCase =emba(input_ids.shape ) __UpperCamelCase =tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(A_ , A_ , atol=self.tolerance ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) __UpperCamelCase =TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) __UpperCamelCase =emba.weight[:3, :5] tf.debugging.assert_near(A_ , A_ , atol=self.tolerance ) @require_tf class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = 1e-4 def _a ( self ) -> Optional[int]: # 2,12,16,64 __UpperCamelCase =tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 __UpperCamelCase =-tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 __UpperCamelCase =TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) __UpperCamelCase =embed_positions([2, 16, 768] )[None, None, :, :] __UpperCamelCase , __UpperCamelCase =TFRoFormerSelfAttention.apply_rotary_position_embeddings( A_ , A_ , A_ ) __UpperCamelCase =tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) __UpperCamelCase =tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , A_ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , A_ , atol=self.tolerance )
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =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 __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =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()
62
1
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =filter(lambda SCREAMING_SNAKE_CASE__ : p.requires_grad , model.parameters() ) __UpperCamelCase =sum([np.prod(p.size() ) for p in model_parameters] ) return params _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ): if metric == "rouge2": __UpperCamelCase ='{val_avg_rouge2:.4f}-{step_count}' elif metric == "bleu": __UpperCamelCase ='{val_avg_bleu:.4f}-{step_count}' elif metric == "em": __UpperCamelCase ='{val_avg_em:.4f}-{step_count}' else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' ' function.' ) __UpperCamelCase =ModelCheckpoint( dirpath=SCREAMING_SNAKE_CASE__ , filename=SCREAMING_SNAKE_CASE__ , monitor=F'val_{metric}' , mode='max' , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ): return EarlyStopping( monitor=F'val_{metric}' , mode='min' if 'loss' in metric else 'max' , patience=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , ) class UpperCAmelCase__ ( pl.Callback ): """simple docstring""" def _a ( self , A_ , A_ ) -> Dict: __UpperCamelCase ={f'lr_group_{i}': param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(A_ ) @rank_zero_only def _a ( self , A_ , A_ , A_ , A_=True ) -> None: logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) __UpperCamelCase =trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']} ) # Log results __UpperCamelCase =Path(pl_module.hparams.output_dir ) if type_path == "test": __UpperCamelCase =od / 'test_results.txt' __UpperCamelCase =od / 'test_generations.txt' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __UpperCamelCase =od / f'{type_path}_results/{trainer.global_step:05d}.txt' __UpperCamelCase =od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=A_ ) generations_file.parent.mkdir(exist_ok=A_ ) with open(A_ , 'a+' ) as writer: for key in sorted(A_ ): if key in ["log", "progress_bar", "preds"]: continue __UpperCamelCase =metrics[key] if isinstance(A_ , torch.Tensor ): __UpperCamelCase =val.item() __UpperCamelCase =f'{key}: {val:.6f}\n' writer.write(A_ ) if not save_generations: return if "preds" in metrics: __UpperCamelCase ='\n'.join(metrics['preds'] ) generations_file.open('w+' ).write(A_ ) @rank_zero_only def _a ( self , A_ , A_ ) -> Tuple: try: __UpperCamelCase =pl_module.model.model.num_parameters() except AttributeError: __UpperCamelCase =pl_module.model.num_parameters() __UpperCamelCase =count_trainable_parameters(A_ ) # mp stands for million parameters trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6} ) @rank_zero_only def _a ( self , A_ , A_ ) -> List[str]: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(A_ , A_ , 'test' ) @rank_zero_only def _a ( self , A_ , A_ ) -> Union[str, Any]: save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = "swinv2" UpperCAmelCase__ : Dict = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , A_=224 , A_=4 , A_=3 , A_=96 , A_=[2, 2, 6, 2] , A_=[3, 6, 12, 24] , A_=7 , A_=4.0 , A_=True , A_=0.0 , A_=0.0 , A_=0.1 , A_="gelu" , A_=False , A_=0.02 , A_=1E-5 , A_=32 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =embed_dim __UpperCamelCase =depths __UpperCamelCase =len(A_ ) __UpperCamelCase =num_heads __UpperCamelCase =window_size __UpperCamelCase =mlp_ratio __UpperCamelCase =qkv_bias __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =drop_path_rate __UpperCamelCase =hidden_act __UpperCamelCase =use_absolute_embeddings __UpperCamelCase =layer_norm_eps __UpperCamelCase =initializer_range __UpperCamelCase =encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __UpperCamelCase =int(embed_dim * 2 ** (len(A_ ) - 1) ) __UpperCamelCase =(0, 0, 0, 0)
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' 'The config can simply be saved and uploaded again to be fixed.' )
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('iterations must be defined as integers' ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not number >= 1: raise ValueError( 'starting number must be\n and integer and be more than 0' ) if not iterations >= 1: raise ValueError('Iterations must be done more than 0 times to play FizzBuzz' ) __UpperCamelCase ='' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(SCREAMING_SNAKE_CASE__ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __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(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('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(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , 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 ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'huggingface/informer-tourism-monthly': ( 'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json' ), # See all Informer models at https://huggingface.co/models?filter=informer } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = "informer" UpperCAmelCase__ : Optional[int] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers", } def __init__( self , A_ = None , A_ = None , A_ = "student_t" , A_ = "nll" , A_ = 1 , A_ = None , A_ = "mean" , A_ = 0 , A_ = 0 , A_ = 0 , A_ = 0 , A_ = None , A_ = None , A_ = 64 , A_ = 32 , A_ = 32 , A_ = 2 , A_ = 2 , A_ = 2 , A_ = 2 , A_ = True , A_ = "gelu" , A_ = 0.05 , A_ = 0.1 , A_ = 0.1 , A_ = 0.1 , A_ = 0.1 , A_ = 100 , A_ = 0.02 , A_=True , A_ = "prob" , A_ = 5 , A_ = True , **A_ , ) -> str: # time series specific configuration __UpperCamelCase =prediction_length __UpperCamelCase =context_length or prediction_length __UpperCamelCase =distribution_output __UpperCamelCase =loss __UpperCamelCase =input_size __UpperCamelCase =num_time_features __UpperCamelCase =lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] __UpperCamelCase =scaling __UpperCamelCase =num_dynamic_real_features __UpperCamelCase =num_static_real_features __UpperCamelCase =num_static_categorical_features # set cardinality 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`' ) __UpperCamelCase =cardinality else: __UpperCamelCase =[0] # set embedding_dimension 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`' ) __UpperCamelCase =embedding_dimension else: __UpperCamelCase =[min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __UpperCamelCase =num_parallel_samples # Transformer architecture configuration __UpperCamelCase =input_size * len(self.lags_sequence ) + self._number_of_features __UpperCamelCase =d_model __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_attention_heads __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =decoder_layers __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =use_cache # Informer __UpperCamelCase =attention_type __UpperCamelCase =sampling_factor __UpperCamelCase =distil super().__init__(is_encoder_decoder=A_ , **A_ ) @property def _a ( self ) -> int: 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 )
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
from queue import PriorityQueue from typing import Any import numpy as np def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : set , SCREAMING_SNAKE_CASE__ : set , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : PriorityQueue , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : float | int , ): for nxt, d in graph[v]: if nxt in visited_forward: continue __UpperCamelCase =cst_fwd.get(SCREAMING_SNAKE_CASE__ , np.inf ) __UpperCamelCase =cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __UpperCamelCase =new_cost_f __UpperCamelCase =v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __UpperCamelCase =cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : dict ): __UpperCamelCase =-1 __UpperCamelCase =set() __UpperCamelCase =set() __UpperCamelCase ={source: 0} __UpperCamelCase ={destination: 0} __UpperCamelCase ={source: None} __UpperCamelCase ={destination: None} __UpperCamelCase =PriorityQueue() __UpperCamelCase =PriorityQueue() __UpperCamelCase =np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __UpperCamelCase , __UpperCamelCase =queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =pass_and_relaxation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) __UpperCamelCase =pass_and_relaxation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __UpperCamelCase =shortest_distance return shortest_path_distance _A = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } _A = { 'B': [['E', 1]], 'C': [['B', 1]], 'D': [['C', 1]], 'F': [['D', 1], ['G', 1]], 'E': [[None, np.inf]], 'G': [['E', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model _A = '0.12' # assumed parallelism: 8 if is_torch_available(): import torch def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[int]=None ): if rng is None: __UpperCamelCase =random.Random() __UpperCamelCase =1 for dim in shape: total_dims *= dim __UpperCamelCase =[] for _ in range(SCREAMING_SNAKE_CASE__ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCamelCase =np.array(SCREAMING_SNAKE_CASE__ , dtype=jnp.intaa ).reshape(SCREAMING_SNAKE_CASE__ ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=None ): __UpperCamelCase =ids_tensor(SCREAMING_SNAKE_CASE__ , vocab_size=2 , rng=SCREAMING_SNAKE_CASE__ ) # make sure that at least one token is attended to for each batch __UpperCamelCase =1 return attn_mask @require_flax class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str = None UpperCAmelCase__ : Dict = () def _a ( self ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCamelCase =2 __UpperCamelCase =inputs['input_ids'].shape[-1] // 2 __UpperCamelCase =inputs['input_ids'][:max_batch_size, :sequence_length] __UpperCamelCase =jnp.ones_like(A_ ) __UpperCamelCase =attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCamelCase =input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCamelCase =config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def _a ( self ) -> Any: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =False __UpperCamelCase =max_length __UpperCamelCase =0 for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCamelCase =getattr(A_ , A_ ) __UpperCamelCase =pt_model_class(A_ ).eval() __UpperCamelCase =load_flax_weights_in_pytorch_model(A_ , flax_model.params ) __UpperCamelCase =flax_model.generate(A_ ).sequences __UpperCamelCase =pt_model.generate(torch.tensor(A_ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCamelCase =flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def _a ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =False __UpperCamelCase =max_length for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> int: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =True __UpperCamelCase =max_length for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =False __UpperCamelCase =max_length __UpperCamelCase =2 for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> Optional[Any]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =False __UpperCamelCase =max_length __UpperCamelCase =2 __UpperCamelCase =2 for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def _a ( self ) -> Optional[Any]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =True __UpperCamelCase =max_length __UpperCamelCase =0.8 __UpperCamelCase =10 __UpperCamelCase =0.3 __UpperCamelCase =1 __UpperCamelCase =8 __UpperCamelCase =9 for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =max_length __UpperCamelCase =1 __UpperCamelCase =8 __UpperCamelCase =9 for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() __UpperCamelCase =max_length __UpperCamelCase =2 __UpperCamelCase =1 __UpperCamelCase =8 __UpperCamelCase =9 for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> Dict: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCamelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCamelCase =False __UpperCamelCase =max_length for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ , attention_mask=A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ , attention_mask=A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCamelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCamelCase =True __UpperCamelCase =max_length for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ , attention_mask=A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ , attention_mask=A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def _a ( self ) -> int: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =self._get_input_ids_and_config() # pad attention mask on the left __UpperCamelCase =attention_mask.at[(0, 0)].set(0 ) __UpperCamelCase =2 __UpperCamelCase =max_length for model_class in self.all_generative_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =model.generate(A_ , attention_mask=A_ ).sequences self.assertEqual(generation_outputs.shape[-1] , A_ ) __UpperCamelCase =jit(model.generate ) __UpperCamelCase =jit_generate(A_ , attention_mask=A_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-bert' ) __UpperCamelCase =FlaxAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-bert-flax-only' ) __UpperCamelCase ='Hello world' __UpperCamelCase =tokenizer(A_ , return_tensors='np' ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(A_ , 'do_samples' ): model.generate(A_ , do_samples=A_ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(A_ , 'foo' ): __UpperCamelCase ={'foo': 'bar'} model.generate(A_ , **A_ )
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
from __future__ import annotations def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase , __UpperCamelCase =set(SCREAMING_SNAKE_CASE__ ), [start] while stack: __UpperCamelCase =stack.pop() explored.add(SCREAMING_SNAKE_CASE__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(SCREAMING_SNAKE_CASE__ ) return explored _A = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
from __future__ import annotations def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[] create_all_state(1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , [] , SCREAMING_SNAKE_CASE__ ) return result def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , ): if level == 0: total_list.append(current_list[:] ) return for i in range(SCREAMING_SNAKE_CASE__ , total_number - level + 2 ): current_list.append(SCREAMING_SNAKE_CASE__ ) create_all_state(i + 1 , SCREAMING_SNAKE_CASE__ , level - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) current_list.pop() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): for i in total_list: print(*SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = 4 _A = 2 _A = generate_all_combinations(n, k) print_all_state(total_list)
62
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( 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: __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_xlm_roberta': [ 'XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaConfig', 'XLMRobertaOnnxConfig', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['XLMRobertaTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['XLMRobertaTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaForCausalLM', 'XLMRobertaForMaskedLM', 'XLMRobertaForMultipleChoice', 'XLMRobertaForQuestionAnswering', 'XLMRobertaForSequenceClassification', 'XLMRobertaForTokenClassification', 'XLMRobertaModel', 'XLMRobertaPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXLMRobertaForCausalLM', 'TFXLMRobertaForMaskedLM', 'TFXLMRobertaForMultipleChoice', 'TFXLMRobertaForQuestionAnswering', 'TFXLMRobertaForSequenceClassification', 'TFXLMRobertaForTokenClassification', 'TFXLMRobertaModel', 'TFXLMRobertaPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxXLMRobertaForMaskedLM', 'FlaxXLMRobertaForCausalLM', 'FlaxXLMRobertaForMultipleChoice', 'FlaxXLMRobertaForQuestionAnswering', 'FlaxXLMRobertaForSequenceClassification', 'FlaxXLMRobertaForTokenClassification', 'FlaxXLMRobertaModel', 'FlaxXLMRobertaPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _A = logging.get_logger(__name__) class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ , A_ , **A_ ) -> Optional[Any]: __UpperCamelCase =feature_size __UpperCamelCase =sampling_rate __UpperCamelCase =padding_value __UpperCamelCase =kwargs.pop('padding_side' , 'right' ) __UpperCamelCase =kwargs.pop('return_attention_mask' , A_ ) super().__init__(**A_ ) def _a ( self , A_ , A_ = True , A_ = None , A_ = False , A_ = None , A_ = None , A_ = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(A_ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): __UpperCamelCase ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) __UpperCamelCase =processed_features[self.model_input_names[0]] __UpperCamelCase =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(A_ ) == 0: if return_attention_mask: __UpperCamelCase =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __UpperCamelCase =required_input[0] if isinstance(A_ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __UpperCamelCase =0 while len(required_input[index] ) == 0: index += 1 if index < len(A_ ): __UpperCamelCase =required_input[index][0] if return_tensors is None: if is_tf_tensor(A_ ): __UpperCamelCase ='tf' elif is_torch_tensor(A_ ): __UpperCamelCase ='pt' elif isinstance(A_ , (int, float, list, tuple, np.ndarray) ): __UpperCamelCase ='np' else: raise ValueError( f'type of {first_element} unknown: {type(A_ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): __UpperCamelCase =to_numpy(A_ ) else: __UpperCamelCase =[to_numpy(A_ ) for v in value] # Convert padding_strategy in PaddingStrategy __UpperCamelCase =self._get_padding_strategies(padding=A_ , max_length=A_ ) __UpperCamelCase =processed_features[self.model_input_names[0]] __UpperCamelCase =len(A_ ) if not all(len(A_ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) __UpperCamelCase =[] for i in range(A_ ): __UpperCamelCase ={k: v[i] for k, v in processed_features.items()} # truncation __UpperCamelCase =self._truncate( A_ , max_length=A_ , pad_to_multiple_of=A_ , truncation=A_ , ) truncated_inputs.append(A_ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __UpperCamelCase =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __UpperCamelCase =PaddingStrategy.MAX_LENGTH __UpperCamelCase ={} for i in range(A_ ): # padding __UpperCamelCase =self._pad( truncated_inputs[i] , max_length=A_ , padding_strategy=A_ , pad_to_multiple_of=A_ , return_attention_mask=A_ , ) for key, value in outputs.items(): if key not in batch_outputs: __UpperCamelCase =[] if value.dtype is np.dtype(np.floataa ): __UpperCamelCase =value.astype(np.floataa ) batch_outputs[key].append(A_ ) return BatchFeature(A_ , tensor_type=A_ ) def _a ( self , A_ , A_ = None , A_ = PaddingStrategy.DO_NOT_PAD , A_ = None , A_ = None , ) -> dict: __UpperCamelCase =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __UpperCamelCase =len(A_ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __UpperCamelCase =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __UpperCamelCase =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(A_ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __UpperCamelCase =np.ones(len(A_ ) , dtype=np.intaa ) if needs_to_be_padded: __UpperCamelCase =max_length - len(A_ ) if self.padding_side == "right": if return_attention_mask: __UpperCamelCase =np.pad( processed_features['attention_mask'] , (0, difference) ) __UpperCamelCase =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __UpperCamelCase =np.pad( A_ , A_ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __UpperCamelCase =np.pad( processed_features['attention_mask'] , (difference, 0) ) __UpperCamelCase =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __UpperCamelCase =np.pad( A_ , A_ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def _a ( self , A_ , A_ = None , A_ = None , A_ = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) __UpperCamelCase =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __UpperCamelCase =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __UpperCamelCase =len(A_ ) > max_length if needs_to_be_truncated: __UpperCamelCase =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __UpperCamelCase =processed_features['attention_mask'][:max_length] return processed_features def _a ( self , A_=False , A_=None ) -> Optional[int]: # Get padding strategy if padding is not False: if padding is True: __UpperCamelCase =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(A_ , A_ ): __UpperCamelCase =PaddingStrategy(A_ ) elif isinstance(A_ , A_ ): __UpperCamelCase =padding else: __UpperCamelCase =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import requests _A = 'YOUR API KEY' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str = giphy_api_key ): __UpperCamelCase ='+'.join(query.split() ) __UpperCamelCase =F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' __UpperCamelCase =requests.get(SCREAMING_SNAKE_CASE__ ).json()['data'] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
import math def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(SCREAMING_SNAKE_CASE__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float = 0.1 ): __UpperCamelCase =3 __UpperCamelCase =3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(SCREAMING_SNAKE_CASE__ ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
import sys from collections import defaultdict class UpperCAmelCase__ : """simple docstring""" def __init__( self ) -> List[str]: __UpperCamelCase =[] def _a ( self , A_ ) -> List[Any]: return self.node_position[vertex] def _a ( self , A_ , A_ ) -> List[Any]: __UpperCamelCase =pos def _a ( self , A_ , A_ , A_ , A_ ) -> List[Any]: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __UpperCamelCase =2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __UpperCamelCase =2 * start + 1 else: __UpperCamelCase =2 * start + 2 if heap[smallest_child] < heap[start]: __UpperCamelCase , __UpperCamelCase =heap[smallest_child], positions[smallest_child] __UpperCamelCase , __UpperCamelCase =( heap[start], positions[start], ) __UpperCamelCase , __UpperCamelCase =temp, tempa __UpperCamelCase =self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , A_ ) self.top_to_bottom(A_ , A_ , A_ , A_ ) def _a ( self , A_ , A_ , A_ , A_ ) -> int: __UpperCamelCase =position[index] while index != 0: __UpperCamelCase =int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __UpperCamelCase =heap[parent] __UpperCamelCase =position[parent] self.set_position(position[parent] , A_ ) else: __UpperCamelCase =val __UpperCamelCase =temp self.set_position(A_ , A_ ) break __UpperCamelCase =parent else: __UpperCamelCase =val __UpperCamelCase =temp self.set_position(A_ , 0 ) def _a ( self , A_ , A_ ) -> List[str]: __UpperCamelCase =len(A_ ) // 2 - 1 for i in range(A_ , -1 , -1 ): self.top_to_bottom(A_ , A_ , len(A_ ) , A_ ) def _a ( self , A_ , A_ ) -> str: __UpperCamelCase =positions[0] __UpperCamelCase =sys.maxsize self.top_to_bottom(A_ , 0 , len(A_ ) , A_ ) return temp def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =Heap() __UpperCamelCase =[0] * len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[-1] * len(SCREAMING_SNAKE_CASE__ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __UpperCamelCase =[] # Heap of Distance of vertices from their neighboring vertex __UpperCamelCase =[] for vertex in range(len(SCREAMING_SNAKE_CASE__ ) ): distance_tv.append(sys.maxsize ) positions.append(SCREAMING_SNAKE_CASE__ ) heap.node_position.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =1 __UpperCamelCase =sys.maxsize for neighbor, distance in adjacency_list[0]: __UpperCamelCase =0 __UpperCamelCase =distance heap.heapify(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(1 , len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =heap.delete_minimum(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __UpperCamelCase =1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(SCREAMING_SNAKE_CASE__ )] ): __UpperCamelCase =distance heap.bottom_to_top( SCREAMING_SNAKE_CASE__ , heap.get_position(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > _A = int(input('Enter number of edges: ').strip()) _A = defaultdict(list) for _ in range(edges_number): _A = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __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 =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_logger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] ): __UpperCamelCase =MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError('Quantized models are not supported.' ) __UpperCamelCase =re.match(r'^mobilenet_v1_([^_]*)_([^_]*)$' , SCREAMING_SNAKE_CASE__ ) if matches: __UpperCamelCase =float(matches[1] ) __UpperCamelCase =int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __UpperCamelCase =10_01 __UpperCamelCase ='imagenet-1k-id2label.json' __UpperCamelCase ='huggingface/label-files' __UpperCamelCase =json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) ) __UpperCamelCase ={int(SCREAMING_SNAKE_CASE__ ) + 1: v for k, v in idalabel.items()} __UpperCamelCase ='background' __UpperCamelCase =idalabel __UpperCamelCase ={v: k for k, v in idalabel.items()} return config def _UpperCAmelCase ( ): __UpperCamelCase ='http://images.cocodataset.org/val2017/000000039769.jpg' __UpperCamelCase =Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int=False ): __UpperCamelCase =get_mobilenet_va_config(SCREAMING_SNAKE_CASE__ ) # Load 🤗 model __UpperCamelCase =MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE__ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __UpperCamelCase =MobileNetVaImageProcessor( crop_size={'width': config.image_size, 'height': config.image_size} , size={'shortest_edge': config.image_size + 32} , ) __UpperCamelCase =image_processor(images=prepare_img() , return_tensors='pt' ) __UpperCamelCase =model(**SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =outputs.logits assert logits.shape == (1, 10_01) if model_name == "mobilenet_v1_1.0_224": __UpperCamelCase =torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": __UpperCamelCase =torch.tensor([-3.9440, -2.3141, -0.3333] ) else: __UpperCamelCase =None if expected_logits is not None: assert torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('Pushing to the hub...' ) __UpperCamelCase ='google/' + model_name image_processor.push_to_hub(SCREAMING_SNAKE_CASE__ ) model.push_to_hub(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) _A = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format='%(message)s') def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray ): return input_array.reshape((input_array.size, 1) ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =np.nan for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =features[:, labels == i] __UpperCamelCase =data.mean(1 ) # Centralize the data of class i __UpperCamelCase =data - column_reshape(SCREAMING_SNAKE_CASE__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(SCREAMING_SNAKE_CASE__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) __UpperCamelCase =np.dot(SCREAMING_SNAKE_CASE__ , centered_data.T ) return covariance_sum / features.shape[1] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =features.mean(1 ) __UpperCamelCase =np.nan for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =features[:, labels == i] __UpperCamelCase =data.shape[1] __UpperCamelCase =data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ ) , (column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) __UpperCamelCase =device_data * np.dot( column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ ) , (column_reshape(SCREAMING_SNAKE_CASE__ ) - column_reshape(SCREAMING_SNAKE_CASE__ )).T , ) return covariance_sum / features.shape[1] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): # Check if the features have been loaded if features.any(): __UpperCamelCase =features.mean(1 ) # Center the dataset __UpperCamelCase =features - np.reshape(SCREAMING_SNAKE_CASE__ , (data_mean.size, 1) ) __UpperCamelCase =np.dot(SCREAMING_SNAKE_CASE__ , centered_data.T ) / features.shape[1] __UpperCamelCase , __UpperCamelCase =np.linalg.eigh(SCREAMING_SNAKE_CASE__ ) # Take all the columns in the reverse order (-1), and then takes only the first __UpperCamelCase =eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space __UpperCamelCase =np.dot(filtered_eigenvectors.T , SCREAMING_SNAKE_CASE__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=SCREAMING_SNAKE_CASE__ ) logging.error('Dataset empty' ) raise AssertionError def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert classes > dimensions # Check if features have been already loaded if features.any: __UpperCamelCase , __UpperCamelCase =eigh( covariance_between_classes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , covariance_within_classes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) __UpperCamelCase =eigenvectors[:, ::-1][:, :dimensions] __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =np.linalg.svd(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =svd_matrix[:, 0:dimensions] __UpperCamelCase =np.dot(filtered_svd_matrix.T , SCREAMING_SNAKE_CASE__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=SCREAMING_SNAKE_CASE__ ) logging.error('Dataset empty' ) raise AssertionError def _UpperCAmelCase ( ): # Create dummy dataset with 2 classes and 3 features __UpperCamelCase =np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) __UpperCamelCase =np.array([0, 0, 0, 1, 1] ) __UpperCamelCase =2 __UpperCamelCase =2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(SCREAMING_SNAKE_CASE__ ) as error_info: __UpperCamelCase =linear_discriminant_analysis( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _UpperCAmelCase ( ): __UpperCamelCase =np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) __UpperCamelCase =2 __UpperCamelCase =np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(SCREAMING_SNAKE_CASE__ ) as error_info: __UpperCamelCase =principal_component_analysis(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : int = KandinskyImgaImgPipeline UpperCAmelCase__ : List[Any] = ["prompt", "image_embeds", "negative_image_embeds", "image"] UpperCAmelCase__ : str = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] UpperCAmelCase__ : Optional[int] = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] UpperCAmelCase__ : Optional[Any] = False @property def _a ( self ) -> Optional[Any]: return 32 @property def _a ( self ) -> Dict: return 32 @property def _a ( self ) -> List[str]: return self.time_input_dim @property def _a ( self ) -> Union[str, Any]: return self.time_input_dim * 4 @property def _a ( self ) -> List[str]: return 100 @property def _a ( self ) -> str: __UpperCamelCase =XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base' ) return tokenizer @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase =MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , ) __UpperCamelCase =MultilingualCLIP(A_ ) __UpperCamelCase =text_encoder.eval() return text_encoder @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase ={ 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'text_image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'text_image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } __UpperCamelCase =UNetaDConditionModel(**A_ ) return model @property def _a ( self ) -> Any: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _a ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase =VQModel(**self.dummy_movq_kwargs ) return model def _a ( self ) -> Any: __UpperCamelCase =self.dummy_text_encoder __UpperCamelCase =self.dummy_tokenizer __UpperCamelCase =self.dummy_unet __UpperCamelCase =self.dummy_movq __UpperCamelCase ={ 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.0_0085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } __UpperCamelCase =DDIMScheduler(**A_ ) __UpperCamelCase ={ 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def _a ( self , A_ , A_=0 ) -> int: __UpperCamelCase =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(A_ ) ).to(A_ ) __UpperCamelCase =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(A_ ) # create init_image __UpperCamelCase =floats_tensor((1, 3, 64, 64) , rng=random.Random(A_ ) ).to(A_ ) __UpperCamelCase =image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCamelCase =Image.fromarray(np.uinta(A_ ) ).convert('RGB' ).resize((256, 256) ) if str(A_ ).startswith('mps' ): __UpperCamelCase =torch.manual_seed(A_ ) else: __UpperCamelCase =torch.Generator(device=A_ ).manual_seed(A_ ) __UpperCamelCase ={ 'prompt': 'horse', 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def _a ( self ) -> Dict: __UpperCamelCase ='cpu' __UpperCamelCase =self.get_dummy_components() __UpperCamelCase =self.pipeline_class(**A_ ) __UpperCamelCase =pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) __UpperCamelCase =pipe(**self.get_dummy_inputs(A_ ) ) __UpperCamelCase =output.images __UpperCamelCase =pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] __UpperCamelCase =image[0, -3:, -3:, -1] __UpperCamelCase =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __UpperCamelCase =np.array( [0.6147_4943, 0.607_3539, 0.4330_8544, 0.592_8269, 0.4749_3595, 0.4675_5973, 0.461_3838, 0.4536_8797, 0.5011_9233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self ) -> List[str]: __UpperCamelCase =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/kandinsky_img2img_frog.npy' ) __UpperCamelCase =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) __UpperCamelCase ='A red cartoon frog, 4k' __UpperCamelCase =KandinskyPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-prior' , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) __UpperCamelCase =KandinskyImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1' , torch_dtype=torch.floataa ) __UpperCamelCase =pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) __UpperCamelCase =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase , __UpperCamelCase =pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __UpperCamelCase =pipeline( A_ , image=A_ , image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='np' , ) __UpperCamelCase =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A_ , A_ )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from typing import List, Optional, Tuple, Union import torch from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ ) -> str: super().__init__() # make sure scheduler can always be converted to DDIM __UpperCamelCase =DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=A_ , scheduler=A_ ) @torch.no_grad() def __call__( self , A_ = 1 , A_ = None , A_ = 0.0 , A_ = 50 , A_ = None , A_ = "pil" , A_ = True , ) -> Union[ImagePipelineOutput, Tuple]: # Sample gaussian noise to begin loop if isinstance(self.unet.config.sample_size , A_ ): __UpperCamelCase =( batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size, ) else: __UpperCamelCase =(batch_size, self.unet.config.in_channels, *self.unet.config.sample_size) if isinstance(A_ , A_ ) and len(A_ ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(A_ )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) __UpperCamelCase =randn_tensor(A_ , generator=A_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(A_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output __UpperCamelCase =self.unet(A_ , A_ ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 __UpperCamelCase =self.scheduler.step( A_ , A_ , A_ , eta=A_ , use_clipped_model_output=A_ , generator=A_ ).prev_sample __UpperCamelCase =(image / 2 + 0.5).clamp(0 , 1 ) __UpperCamelCase =image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __UpperCamelCase =self.numpy_to_pil(A_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A_ )
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
import math def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): if ( not isinstance(SCREAMING_SNAKE_CASE__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return apparent_power * power_factor def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): if ( not isinstance(SCREAMING_SNAKE_CASE__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError('power_factor must be a valid float value between -1 and 1.' ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
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
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class UpperCAmelCase__ ( A_ ): """simple docstring""" def __init__( self , A_ , A_ ) -> Union[str, Any]: __UpperCamelCase =params __UpperCamelCase =np.array(A_ ) __UpperCamelCase =np.array([len(A_ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self , A_ ) -> List[str]: return (self.token_ids[index], self.lengths[index]) def __len__( self ) -> Optional[Any]: return len(self.lengths ) def _a ( self ) -> Any: assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.params.max_model_input_size __UpperCamelCase =self.lengths > max_len logger.info(f'Splitting {sum(A_ )} too long sequences.' ) def divide_chunks(A_ , A_ ): return [l[i : i + n] for i in range(0 , len(A_ ) , A_ )] __UpperCamelCase =[] __UpperCamelCase =[] if self.params.mlm: __UpperCamelCase , __UpperCamelCase =self.params.special_tok_ids['cls_token'], self.params.special_tok_ids['sep_token'] else: __UpperCamelCase , __UpperCamelCase =self.params.special_tok_ids['bos_token'], self.params.special_tok_ids['eos_token'] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: __UpperCamelCase =[] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: __UpperCamelCase =np.insert(A_ , 0 , A_ ) if sub_s[-1] != sep_id: __UpperCamelCase =np.insert(A_ , len(A_ ) , A_ ) assert len(A_ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(A_ ) new_tok_ids.extend(A_ ) new_lengths.extend([len(A_ ) for l in sub_seqs] ) __UpperCamelCase =np.array(A_ ) __UpperCamelCase =np.array(A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =len(self ) __UpperCamelCase =self.lengths > 11 __UpperCamelCase =self.token_ids[indices] __UpperCamelCase =self.lengths[indices] __UpperCamelCase =len(self ) logger.info(f'Remove {init_size - new_size} too short (<=11 tokens) sequences.' ) def _a ( self ) -> int: if "unk_token" not in self.params.special_tok_ids: return else: __UpperCamelCase =self.params.special_tok_ids['unk_token'] __UpperCamelCase =len(self ) __UpperCamelCase =np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) __UpperCamelCase =(unk_occs / self.lengths) < 0.5 __UpperCamelCase =self.token_ids[indices] __UpperCamelCase =self.lengths[indices] __UpperCamelCase =len(self ) logger.info(f'Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).' ) def _a ( self ) -> int: if not self.params.is_master: return logger.info(f'{len(self )} sequences' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def _a ( self , A_ ) -> int: __UpperCamelCase =[t[0] for t in batch] __UpperCamelCase =[t[1] for t in batch] assert len(A_ ) == len(A_ ) # Max for paddings __UpperCamelCase =max(A_ ) # Pad token ids if self.params.mlm: __UpperCamelCase =self.params.special_tok_ids['pad_token'] else: __UpperCamelCase =self.params.special_tok_ids['unk_token'] __UpperCamelCase =[list(t.astype(A_ ) ) + [pad_idx] * (max_seq_len_ - len(A_ )) for t in token_ids] assert len(tk_ ) == len(A_ ) assert all(len(A_ ) == max_seq_len_ for t in tk_ ) __UpperCamelCase =torch.tensor(tk_ ) # (bs, max_seq_len_) __UpperCamelCase =torch.tensor(A_ ) # (bs) return tk_t, lg_t
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '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 _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from string import ascii_uppercase _A = {str(ord(c) - 55): c for c in ascii_uppercase} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('int() can\'t convert non-string with explicit base' ) if num < 0: raise ValueError('parameter must be positive int' ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('\'str\' object cannot be interpreted as an integer' ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('\'float\' object cannot be interpreted as an integer' ) if base in (0, 1): raise ValueError('base must be >= 2' ) if base > 36: raise ValueError('base must be <= 36' ) __UpperCamelCase ='' __UpperCamelCase =0 __UpperCamelCase =0 while div != 1: __UpperCamelCase , __UpperCamelCase =divmod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if base >= 11 and 9 < mod < 36: __UpperCamelCase =ALPHABET_VALUES[str(SCREAMING_SNAKE_CASE__ )] else: __UpperCamelCase =str(SCREAMING_SNAKE_CASE__ ) new_value += actual_value __UpperCamelCase =num // base __UpperCamelCase =div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(SCREAMING_SNAKE_CASE__ ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import tensorflow as tf from ...tf_utils import shape_list class UpperCAmelCase__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self , A_ , A_ , A_ , A_ , A_=1 , A_=False , **A_ ) -> Union[str, Any]: super().__init__(**A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =d_embed __UpperCamelCase =d_proj __UpperCamelCase =cutoffs + [vocab_size] __UpperCamelCase =[0] + self.cutoffs __UpperCamelCase =div_val __UpperCamelCase =self.cutoffs[0] __UpperCamelCase =len(self.cutoffs ) - 1 __UpperCamelCase =self.shortlist_size + self.n_clusters __UpperCamelCase =keep_order __UpperCamelCase =[] __UpperCamelCase =[] def _a ( self , A_ ) -> List[str]: if self.n_clusters > 0: __UpperCamelCase =self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='zeros' , trainable=A_ , name='cluster_weight' ) __UpperCamelCase =self.add_weight( shape=(self.n_clusters,) , initializer='zeros' , trainable=A_ , name='cluster_bias' ) if self.div_val == 1: for i in range(len(self.cutoffs ) ): if self.d_proj != self.d_embed: __UpperCamelCase =self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='zeros' , trainable=A_ , name=f'out_projs_._{i}' , ) self.out_projs.append(A_ ) else: self.out_projs.append(A_ ) __UpperCamelCase =self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='zeros' , trainable=A_ , name=f'out_layers_._{i}_._weight' , ) __UpperCamelCase =self.add_weight( shape=(self.vocab_size,) , initializer='zeros' , trainable=A_ , name=f'out_layers_._{i}_._bias' , ) self.out_layers.append((weight, bias) ) else: for i in range(len(self.cutoffs ) ): __UpperCamelCase , __UpperCamelCase =self.cutoff_ends[i], self.cutoff_ends[i + 1] __UpperCamelCase =self.d_embed // (self.div_val**i) __UpperCamelCase =self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='zeros' , trainable=A_ , name=f'out_projs_._{i}' ) self.out_projs.append(A_ ) __UpperCamelCase =self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='zeros' , trainable=A_ , name=f'out_layers_._{i}_._weight' , ) __UpperCamelCase =self.add_weight( shape=(r_idx - l_idx,) , initializer='zeros' , trainable=A_ , name=f'out_layers_._{i}_._bias' , ) self.out_layers.append((weight, bias) ) super().build(A_ ) @staticmethod def _a ( A_ , A_ , A_ , A_=None ) -> List[Any]: __UpperCamelCase =x if proj is not None: __UpperCamelCase =tf.einsum('ibd,ed->ibe' , A_ , A_ ) return tf.einsum('ibd,nd->ibn' , A_ , A_ ) + b @staticmethod def _a ( A_ , A_ ) -> Dict: __UpperCamelCase =shape_list(A_ ) __UpperCamelCase =tf.range(lp_size[0] , dtype=target.dtype ) __UpperCamelCase =tf.stack([r, target] , 1 ) return tf.gather_nd(A_ , A_ ) def _a ( self , A_ , A_ , A_=True , A_=False ) -> str: __UpperCamelCase =0 if self.n_clusters == 0: __UpperCamelCase =self._logit(A_ , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0] ) if target is not None: __UpperCamelCase =tf.nn.sparse_softmax_cross_entropy_with_logits(labels=A_ , logits=A_ ) __UpperCamelCase =tf.nn.log_softmax(A_ , axis=-1 ) else: __UpperCamelCase =shape_list(A_ ) __UpperCamelCase =[] __UpperCamelCase =tf.zeros(hidden_sizes[:2] ) for i in range(len(self.cutoffs ) ): __UpperCamelCase , __UpperCamelCase =self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: __UpperCamelCase =(target >= l_idx) & (target < r_idx) __UpperCamelCase =tf.where(A_ ) __UpperCamelCase =tf.boolean_mask(A_ , A_ ) - l_idx if self.div_val == 1: __UpperCamelCase =self.out_layers[0][0][l_idx:r_idx] __UpperCamelCase =self.out_layers[0][1][l_idx:r_idx] else: __UpperCamelCase =self.out_layers[i][0] __UpperCamelCase =self.out_layers[i][1] if i == 0: __UpperCamelCase =tf.concat([cur_W, self.cluster_weight] , 0 ) __UpperCamelCase =tf.concat([cur_b, self.cluster_bias] , 0 ) __UpperCamelCase =self._logit(A_ , A_ , A_ , self.out_projs[0] ) __UpperCamelCase =tf.nn.log_softmax(A_ ) out.append(head_logprob[..., : self.cutoffs[0]] ) if target is not None: __UpperCamelCase =tf.boolean_mask(A_ , A_ ) __UpperCamelCase =self._gather_logprob(A_ , A_ ) else: __UpperCamelCase =self._logit(A_ , A_ , A_ , self.out_projs[i] ) __UpperCamelCase =tf.nn.log_softmax(A_ ) __UpperCamelCase =self.cutoffs[0] + i - 1 # No probability for the head cluster __UpperCamelCase =head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(A_ ) if target is not None: __UpperCamelCase =tf.boolean_mask(A_ , A_ ) __UpperCamelCase =tf.boolean_mask(A_ , A_ ) __UpperCamelCase =self._gather_logprob(A_ , A_ ) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(A_ , -cur_logprob , shape_list(A_ ) ) __UpperCamelCase =tf.concat(A_ , axis=-1 ) if target is not None: if return_mean: __UpperCamelCase =tf.reduce_mean(A_ ) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(A_ ) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(A_ , name=self.name , aggregation='mean' if return_mean else '' ) return out
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list] ): __UpperCamelCase =current_set.copy() for row_index, row in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =row[0] for column_index, column in enumerate(SCREAMING_SNAKE_CASE__ ): if magnitude == 0: __UpperCamelCase =column continue __UpperCamelCase =column / magnitude # Subtract to cancel term __UpperCamelCase =current_set[0] __UpperCamelCase =[first_row] __UpperCamelCase =current_set[1::] for row in current_set: __UpperCamelCase =[] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(SCREAMING_SNAKE_CASE__ ) continue for column_index in range(len(SCREAMING_SNAKE_CASE__ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(SCREAMING_SNAKE_CASE__ ) # Create next recursion iteration set if len(final_set[0] ) != 3: __UpperCamelCase =final_set[0] __UpperCamelCase =[] __UpperCamelCase =[] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) __UpperCamelCase =simplify(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =resultant return final_set def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list] ): if len(SCREAMING_SNAKE_CASE__ ) == 0: raise IndexError('solve_simultaneous() requires n lists of length n+1' ) __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) + 1 if any(len(SCREAMING_SNAKE_CASE__ ) != _length for item in equations ): raise IndexError('solve_simultaneous() requires n lists of length n+1' ) for row in equations: if any(not isinstance(SCREAMING_SNAKE_CASE__ , (int, float) ) for column in row ): raise ValueError('solve_simultaneous() requires lists of integers' ) if len(SCREAMING_SNAKE_CASE__ ) == 1: return [equations[0][-1] / equations[0][0]] __UpperCamelCase =equations.copy() if any(0 in row for row in data_set ): __UpperCamelCase =data_set.copy() __UpperCamelCase =[] for row_index, row in enumerate(SCREAMING_SNAKE_CASE__ ): if 0 not in row: __UpperCamelCase =data_set.pop(SCREAMING_SNAKE_CASE__ ) break if not full_row: raise ValueError('solve_simultaneous() requires at least 1 full equation' ) data_set.insert(0 , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =data_set.copy() __UpperCamelCase =simplify(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =simplified[::-1] __UpperCamelCase =[] for row in simplified: __UpperCamelCase =row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue __UpperCamelCase =row.copy()[: len(SCREAMING_SNAKE_CASE__ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(SCREAMING_SNAKE_CASE__ ) == 0: solutions.append(0 ) continue __UpperCamelCase =temp_row[1::] __UpperCamelCase =temp_row[::-1] for column_index, column in enumerate(SCREAMING_SNAKE_CASE__ ): current_solution -= column * solutions[column_index] solutions.append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for item in solutions: final.append(float(round(SCREAMING_SNAKE_CASE__ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() _A = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =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 __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =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()
62
1
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print('Googling.....') _A = 'https://www.google.com/search?q=' + ' '.join(sys.argv[1:]) _A = requests.get(url, headers={'UserAgent': UserAgent().random}) # res.raise_for_status() with open('project1a.html', 'wb') as out_file: # only for knowing the class for data in res.iter_content(1_0000): out_file.write(data) _A = BeautifulSoup(res.text, 'html.parser') _A = list(soup.select('.eZt8xd'))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get('href')) else: webbrowser.open(f"""https://google.com{link.get('href')}""")
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # 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 = '.' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) _A = [ 'Assert', 'AssignVariableOp', 'EmptyTensorList', 'MergeV2Checkpoints', 'ReadVariableOp', 'ResourceGather', 'RestoreV2', 'SaveV2', 'ShardedFilename', 'StatefulPartitionedCall', 'StaticRegexFullMatch', 'VarHandleOp', ] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =SavedModel() __UpperCamelCase =[] with open(os.path.join(SCREAMING_SNAKE_CASE__ , 'utils' , 'tf_ops' , 'onnx.json' ) ) as f: __UpperCamelCase =json.load(SCREAMING_SNAKE_CASE__ )['opsets'] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(SCREAMING_SNAKE_CASE__ )] ) with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: saved_model.ParseFromString(f.read() ) __UpperCamelCase =set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want __UpperCamelCase =sorted(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(SCREAMING_SNAKE_CASE__ ) if strict and len(SCREAMING_SNAKE_CASE__ ) > 0: raise Exception(F'Found the following incompatible ops for the opset {opset}:\n' + incompatible_ops ) elif len(SCREAMING_SNAKE_CASE__ ) > 0: print(F'Found the following incompatible ops for the opset {opset}:' ) print(*SCREAMING_SNAKE_CASE__ , sep='\n' ) else: print(F'The saved model {saved_model_path} can properly be converted with ONNX.' ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument('--saved_model_path', help='Path of the saved model to check (the .pb file).') parser.add_argument( '--opset', default=12, type=int, help='The ONNX opset against which the model has to be tested.' ) parser.add_argument( '--framework', choices=['onnx'], default='onnx', help='Frameworks against which to test the saved model.' ) parser.add_argument( '--strict', action='store_true', help='Whether make the checking strict (raise errors) or not (raise warnings)' ) _A = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' 'The config can simply be saved and uploaded again to be fixed.' )
62
1
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
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __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(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('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(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , 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 ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_unispeech': ['UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST', 'UniSpeechForCTC', 'UniSpeechForPreTraining', 'UniSpeechForSequenceClassification', 'UniSpeechModel', 'UniSpeechPreTrainedModel', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
from __future__ import annotations def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase , __UpperCamelCase =position __UpperCamelCase =[ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] __UpperCamelCase =[] for position in positions: __UpperCamelCase , __UpperCamelCase =position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(SCREAMING_SNAKE_CASE__ ) return permissible_positions def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): if is_complete(SCREAMING_SNAKE_CASE__ ): return True for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase , __UpperCamelCase =position if board[y][x] == 0: __UpperCamelCase =curr + 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ): return True __UpperCamelCase =0 return False def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ): return board __UpperCamelCase =0 __UpperCamelCase =F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
import sys _A = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = N ): __UpperCamelCase =-sys.maxsize - 1 for i in range(len(SCREAMING_SNAKE_CASE__ ) - 12 ): __UpperCamelCase =1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: __UpperCamelCase =product return largest_product if __name__ == "__main__": print(f"""{solution() = }""")
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( 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: __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() _A = logging.get_logger('transformers.models.encodec') _A = { 'quantizer.vq.layers.*._codebook.inited': 'quantizer.layers.*.codebook.inited', 'quantizer.vq.layers.*._codebook.cluster_size': 'quantizer.layers.*.codebook.cluster_size', 'quantizer.vq.layers.*._codebook.embed': 'quantizer.layers.*.codebook.embed', 'quantizer.vq.layers.*._codebook.embed_avg': 'quantizer.layers.*.codebook.embed_avg', } _A = { 'encoder.model.0.conv.conv': 'encoder.layers.0.conv', 'encoder.model.1.block.1.conv.conv': 'encoder.layers.1.block.1.conv', 'encoder.model.1.block.3.conv.conv': 'encoder.layers.1.block.3.conv', 'encoder.model.1.shortcut.conv.conv': 'encoder.layers.1.shortcut.conv', 'encoder.model.3.conv.conv': 'encoder.layers.3.conv', 'encoder.model.4.block.1.conv.conv': 'encoder.layers.4.block.1.conv', 'encoder.model.4.block.3.conv.conv': 'encoder.layers.4.block.3.conv', 'encoder.model.4.shortcut.conv.conv': 'encoder.layers.4.shortcut.conv', 'encoder.model.6.conv.conv': 'encoder.layers.6.conv', 'encoder.model.7.block.1.conv.conv': 'encoder.layers.7.block.1.conv', 'encoder.model.7.block.3.conv.conv': 'encoder.layers.7.block.3.conv', 'encoder.model.7.shortcut.conv.conv': 'encoder.layers.7.shortcut.conv', 'encoder.model.9.conv.conv': 'encoder.layers.9.conv', 'encoder.model.10.block.1.conv.conv': 'encoder.layers.10.block.1.conv', 'encoder.model.10.block.3.conv.conv': 'encoder.layers.10.block.3.conv', 'encoder.model.10.shortcut.conv.conv': 'encoder.layers.10.shortcut.conv', 'encoder.model.12.conv.conv': 'encoder.layers.12.conv', 'encoder.model.13.lstm': 'encoder.layers.13.lstm', 'encoder.model.15.conv.conv': 'encoder.layers.15.conv', } _A = { 'encoder.model.0.conv.norm': 'encoder.layers.0.norm', 'encoder.model.1.block.1.conv.norm': 'encoder.layers.1.block.1.norm', 'encoder.model.1.block.3.conv.norm': 'encoder.layers.1.block.3.norm', 'encoder.model.1.shortcut.conv.norm': 'encoder.layers.1.shortcut.norm', 'encoder.model.3.conv.norm': 'encoder.layers.3.norm', 'encoder.model.4.block.1.conv.norm': 'encoder.layers.4.block.1.norm', 'encoder.model.4.block.3.conv.norm': 'encoder.layers.4.block.3.norm', 'encoder.model.4.shortcut.conv.norm': 'encoder.layers.4.shortcut.norm', 'encoder.model.6.conv.norm': 'encoder.layers.6.norm', 'encoder.model.7.block.1.conv.norm': 'encoder.layers.7.block.1.norm', 'encoder.model.7.block.3.conv.norm': 'encoder.layers.7.block.3.norm', 'encoder.model.7.shortcut.conv.norm': 'encoder.layers.7.shortcut.norm', 'encoder.model.9.conv.norm': 'encoder.layers.9.norm', 'encoder.model.10.block.1.conv.norm': 'encoder.layers.10.block.1.norm', 'encoder.model.10.block.3.conv.norm': 'encoder.layers.10.block.3.norm', 'encoder.model.10.shortcut.conv.norm': 'encoder.layers.10.shortcut.norm', 'encoder.model.12.conv.norm': 'encoder.layers.12.norm', 'encoder.model.15.conv.norm': 'encoder.layers.15.norm', } _A = { 'decoder.model.0.conv.conv': 'decoder.layers.0.conv', 'decoder.model.1.lstm': 'decoder.layers.1.lstm', 'decoder.model.3.convtr.convtr': 'decoder.layers.3.conv', 'decoder.model.4.block.1.conv.conv': 'decoder.layers.4.block.1.conv', 'decoder.model.4.block.3.conv.conv': 'decoder.layers.4.block.3.conv', 'decoder.model.4.shortcut.conv.conv': 'decoder.layers.4.shortcut.conv', 'decoder.model.6.convtr.convtr': 'decoder.layers.6.conv', 'decoder.model.7.block.1.conv.conv': 'decoder.layers.7.block.1.conv', 'decoder.model.7.block.3.conv.conv': 'decoder.layers.7.block.3.conv', 'decoder.model.7.shortcut.conv.conv': 'decoder.layers.7.shortcut.conv', 'decoder.model.9.convtr.convtr': 'decoder.layers.9.conv', 'decoder.model.10.block.1.conv.conv': 'decoder.layers.10.block.1.conv', 'decoder.model.10.block.3.conv.conv': 'decoder.layers.10.block.3.conv', 'decoder.model.10.shortcut.conv.conv': 'decoder.layers.10.shortcut.conv', 'decoder.model.12.convtr.convtr': 'decoder.layers.12.conv', 'decoder.model.13.block.1.conv.conv': 'decoder.layers.13.block.1.conv', 'decoder.model.13.block.3.conv.conv': 'decoder.layers.13.block.3.conv', 'decoder.model.13.shortcut.conv.conv': 'decoder.layers.13.shortcut.conv', 'decoder.model.15.conv.conv': 'decoder.layers.15.conv', } _A = { 'decoder.model.0.conv.norm': 'decoder.layers.0.norm', 'decoder.model.3.convtr.norm': 'decoder.layers.3.norm', 'decoder.model.4.block.1.conv.norm': 'decoder.layers.4.block.1.norm', 'decoder.model.4.block.3.conv.norm': 'decoder.layers.4.block.3.norm', 'decoder.model.4.shortcut.conv.norm': 'decoder.layers.4.shortcut.norm', 'decoder.model.6.convtr.norm': 'decoder.layers.6.norm', 'decoder.model.7.block.1.conv.norm': 'decoder.layers.7.block.1.norm', 'decoder.model.7.block.3.conv.norm': 'decoder.layers.7.block.3.norm', 'decoder.model.7.shortcut.conv.norm': 'decoder.layers.7.shortcut.norm', 'decoder.model.9.convtr.norm': 'decoder.layers.9.norm', 'decoder.model.10.block.1.conv.norm': 'decoder.layers.10.block.1.norm', 'decoder.model.10.block.3.conv.norm': 'decoder.layers.10.block.3.norm', 'decoder.model.10.shortcut.conv.norm': 'decoder.layers.10.shortcut.norm', 'decoder.model.12.convtr.norm': 'decoder.layers.12.norm', 'decoder.model.13.block.1.conv.norm': 'decoder.layers.13.block.1.norm', 'decoder.model.13.block.3.conv.norm': 'decoder.layers.13.block.3.norm', 'decoder.model.13.shortcut.conv.norm': 'decoder.layers.13.shortcut.norm', 'decoder.model.15.conv.norm': 'decoder.layers.15.norm', } _A = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } _A = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } _A = [] _A = [] def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] ): for attribute in key.split('.' ): __UpperCamelCase =getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if weight_type is not None: __UpperCamelCase =getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).shape else: __UpperCamelCase =hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": __UpperCamelCase =value elif weight_type == "weight_g": __UpperCamelCase =value elif weight_type == "weight_v": __UpperCamelCase =value elif weight_type == "bias": __UpperCamelCase =value elif weight_type == "running_mean": __UpperCamelCase =value elif weight_type == "running_var": __UpperCamelCase =value elif weight_type == "num_batches_tracked": __UpperCamelCase =value elif weight_type == "weight_ih_l0": __UpperCamelCase =value elif weight_type == "weight_hh_l0": __UpperCamelCase =value elif weight_type == "bias_ih_l0": __UpperCamelCase =value elif weight_type == "bias_hh_l0": __UpperCamelCase =value elif weight_type == "weight_ih_l1": __UpperCamelCase =value elif weight_type == "weight_hh_l1": __UpperCamelCase =value elif weight_type == "bias_ih_l1": __UpperCamelCase =value elif weight_type == "bias_hh_l1": __UpperCamelCase =value else: __UpperCamelCase =value logger.info(F'{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ): for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: __UpperCamelCase , __UpperCamelCase =key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ): __UpperCamelCase =[] if model_name == "encodec_24khz" or "encodec_32khz": __UpperCamelCase =MAPPING_24K elif model_name == "encodec_48khz": __UpperCamelCase =MAPPING_48K else: raise ValueError(F'Unsupported model: {model_name}' ) for name, value in orig_dict.items(): if should_ignore(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): logger.info(F'{name} was ignored' ) continue __UpperCamelCase =False for key, mapped_key in MAPPING.items(): if "*" in key: __UpperCamelCase , __UpperCamelCase =key.split('.*.' ) if prefix in name and suffix in name: __UpperCamelCase =suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue __UpperCamelCase =True if "*" in mapped_key: __UpperCamelCase =name.split(SCREAMING_SNAKE_CASE__ )[0].split('.' )[-2] __UpperCamelCase =mapped_key.replace('*' , SCREAMING_SNAKE_CASE__ ) if "weight_g" in name: __UpperCamelCase ='weight_g' elif "weight_v" in name: __UpperCamelCase ='weight_v' elif "weight_ih_l0" in name: __UpperCamelCase ='weight_ih_l0' elif "weight_hh_l0" in name: __UpperCamelCase ='weight_hh_l0' elif "bias_ih_l0" in name: __UpperCamelCase ='bias_ih_l0' elif "bias_hh_l0" in name: __UpperCamelCase ='bias_hh_l0' elif "weight_ih_l1" in name: __UpperCamelCase ='weight_ih_l1' elif "weight_hh_l1" in name: __UpperCamelCase ='weight_hh_l1' elif "bias_ih_l1" in name: __UpperCamelCase ='bias_ih_l1' elif "bias_hh_l1" in name: __UpperCamelCase ='bias_hh_l1' elif "bias" in name: __UpperCamelCase ='bias' elif "weight" in name: __UpperCamelCase ='weight' elif "running_mean" in name: __UpperCamelCase ='running_mean' elif "running_var" in name: __UpperCamelCase ='running_var' elif "num_batches_tracked" in name: __UpperCamelCase ='num_batches_tracked' else: __UpperCamelCase =None set_recursively(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE__ ) logger.warning(F'Unused weights: {unused_weights}' ) @torch.no_grad() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : int=None , ): if config_path is not None: __UpperCamelCase =EncodecConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) else: __UpperCamelCase =EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": __UpperCamelCase =[8, 5, 4, 4] __UpperCamelCase =[2.2] __UpperCamelCase =64 __UpperCamelCase =3_20_00 __UpperCamelCase =20_48 __UpperCamelCase =False __UpperCamelCase =False __UpperCamelCase =False elif model_name == "encodec_48khz": __UpperCamelCase =[8, 5, 4, 2] __UpperCamelCase =[3.0, 6.0, 12.0, 24.0] __UpperCamelCase =4_80_00 __UpperCamelCase =2 __UpperCamelCase =False __UpperCamelCase ='time_group_norm' __UpperCamelCase =True __UpperCamelCase =1.0 __UpperCamelCase =0.01 else: raise ValueError(F'Unknown model name: {model_name}' ) __UpperCamelCase =EncodecModel(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =torch.load(SCREAMING_SNAKE_CASE__ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights __UpperCamelCase =original_checkpoint['best_state'] recursively_load_weights(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(SCREAMING_SNAKE_CASE__ ) model.push_to_hub(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument( '--model', default='encodec_24khz', type=str, help='The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.', ) parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) _A = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
62
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( 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: __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): _A = 'pt' elif is_tf_available(): _A = 'tf' else: _A = 'jax' class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[Any] = PerceiverTokenizer UpperCAmelCase__ : Optional[Any] = False def _a ( self ) -> Dict: super().setUp() __UpperCamelCase =PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _a ( self ) -> int: return PerceiverTokenizer.from_pretrained('deepmind/language-perceiver' ) def _a ( self , **A_ ) -> PerceiverTokenizer: return self.tokenizer_class.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ , A_=False , A_=20 , A_=5 ) -> Tuple[str, list]: # XXX The default common tokenizer tests assume that every ID is decodable on its own. # This assumption is invalid for Perceiver because single bytes might not be # valid utf-8 (byte 128 for instance). # Here we're overriding the smallest possible method to provide # a clean sequence without making the same assumption. __UpperCamelCase =[] for i in range(len(A_ ) ): try: __UpperCamelCase =tokenizer.decode([i] , clean_up_tokenization_spaces=A_ ) except UnicodeDecodeError: pass toks.append((i, tok) ) __UpperCamelCase =list(filter(lambda A_ : re.match(r'^[ a-zA-Z]+$' , t[1] ) , A_ ) ) __UpperCamelCase =list(filter(lambda A_ : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=A_ ) , A_ ) ) if max_length is not None and len(A_ ) > max_length: __UpperCamelCase =toks[:max_length] if min_length is not None and len(A_ ) < min_length and len(A_ ) > 0: while len(A_ ) < min_length: __UpperCamelCase =toks + toks # toks_str = [t[1] for t in toks] __UpperCamelCase =[t[0] for t in toks] # Ensure consistency __UpperCamelCase =tokenizer.decode(A_ , clean_up_tokenization_spaces=A_ ) if " " not in output_txt and len(A_ ) > 1: __UpperCamelCase =( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=A_ ) + ' ' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=A_ ) ) if with_prefix_space: __UpperCamelCase =' ' + output_txt __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) return output_txt, output_ids def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.perceiver_tokenizer __UpperCamelCase ='Unicode €.' __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =[4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded['input_ids'] , A_ ) # decoding __UpperCamelCase =tokenizer.decode(A_ ) self.assertEqual(A_ , '[CLS]Unicode €.[SEP]' ) __UpperCamelCase =tokenizer('e è é ê ë' ) __UpperCamelCase =[4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded['input_ids'] , A_ ) # decoding __UpperCamelCase =tokenizer.decode(A_ ) self.assertEqual(A_ , '[CLS]e è é ê ë[SEP]' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë' ) ) , '[CLS]e è é ê ë[SEP]' ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.perceiver_tokenizer __UpperCamelCase =['A long paragraph for summarization.', 'Another paragraph for summarization.'] # fmt: off __UpperCamelCase =[4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on __UpperCamelCase =tokenizer(A_ , padding=A_ , return_tensors=A_ ) self.assertIsInstance(A_ , A_ ) if FRAMEWORK != "jax": __UpperCamelCase =list(batch.input_ids.numpy()[0] ) else: __UpperCamelCase =list(batch.input_ids.tolist()[0] ) self.assertListEqual(A_ , A_ ) self.assertEqual((2, 38) , batch.input_ids.shape ) self.assertEqual((2, 38) , batch.attention_mask.shape ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.perceiver_tokenizer __UpperCamelCase =['A long paragraph for summarization.', 'Another paragraph for summarization.'] __UpperCamelCase =tokenizer(A_ , padding=A_ , return_tensors=A_ ) # check if input_ids are returned and no decoder_input_ids self.assertIn('input_ids' , A_ ) self.assertIn('attention_mask' , A_ ) self.assertNotIn('decoder_input_ids' , A_ ) self.assertNotIn('decoder_attention_mask' , A_ ) def _a ( self ) -> Any: __UpperCamelCase =self.perceiver_tokenizer __UpperCamelCase =[ 'Summary of the text.', 'Another summary.', ] __UpperCamelCase =tokenizer( text_target=A_ , max_length=32 , padding='max_length' , truncation=A_ , return_tensors=A_ ) self.assertEqual(32 , targets['input_ids'].shape[1] ) def _a ( self ) -> Tuple: # safety check on max_len default value so we are sure the test works __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =' He is very happy, UNwant\u00E9d,running' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) tokenizer.save_pretrained(A_ ) __UpperCamelCase =tokenizer.__class__.from_pretrained(A_ ) __UpperCamelCase =after_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) shutil.rmtree(A_ ) __UpperCamelCase =self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =' He is very happy, UNwant\u00E9d,running' tokenizer.add_tokens(['bim', 'bambam'] ) __UpperCamelCase =tokenizer.additional_special_tokens additional_special_tokens.append('new_additional_special_token' ) tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens} ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) tokenizer.save_pretrained(A_ ) __UpperCamelCase =tokenizer.__class__.from_pretrained(A_ ) __UpperCamelCase =after_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) self.assertIn('new_additional_special_token' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) __UpperCamelCase =tokenizer.__class__.from_pretrained(A_ , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(A_ ) def _a ( self ) -> Any: __UpperCamelCase =[] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(A_ ) with open(os.path.join(A_ , 'special_tokens_map.json' ) , encoding='utf-8' ) as json_file: __UpperCamelCase =json.load(A_ ) with open(os.path.join(A_ , 'tokenizer_config.json' ) , encoding='utf-8' ) as json_file: __UpperCamelCase =json.load(A_ ) __UpperCamelCase =[f'<extra_id_{i}>' for i in range(125 )] __UpperCamelCase =added_tokens_extra_ids + [ 'an_additional_special_token' ] __UpperCamelCase =added_tokens_extra_ids + [ 'an_additional_special_token' ] with open(os.path.join(A_ , 'special_tokens_map.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(A_ , A_ ) with open(os.path.join(A_ , 'tokenizer_config.json' ) , 'w' , encoding='utf-8' ) as outfile: json.dump(A_ , A_ ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files __UpperCamelCase =tokenizer_class.from_pretrained( A_ , ) self.assertIn( 'an_additional_special_token' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['an_additional_special_token'] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token'] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained __UpperCamelCase =added_tokens_extra_ids + [AddedToken('a_new_additional_special_token' , lstrip=A_ )] __UpperCamelCase =tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , ) self.assertIn('a_new_additional_special_token' , tokenizer.additional_special_tokens ) self.assertEqual( ['a_new_additional_special_token'] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['a_new_additional_special_token'] ) ) , ) def _a ( self ) -> Dict: __UpperCamelCase =self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178] ) , '�' ) def _a ( self ) -> Union[str, Any]: pass def _a ( self ) -> Optional[Any]: pass def _a ( self ) -> int: pass def _a ( self ) -> List[Any]: pass def _a ( self ) -> Optional[Any]: # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character # strings and special added tokens as tokens __UpperCamelCase =self.get_tokenizers(fast=A_ , do_lower_case=A_ ) for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase =['[CLS]', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '[SEP]'] __UpperCamelCase =tokenizer.convert_tokens_to_string(A_ ) self.assertIsInstance(A_ , A_ )
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_logger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False ): __UpperCamelCase ='backbone.' if is_semantic else '' __UpperCamelCase =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'{prefix}blocks.{i}.norm1.weight', F'beit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'{prefix}blocks.{i}.norm1.bias', F'beit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'{prefix}blocks.{i}.attn.proj.weight', F'beit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'{prefix}blocks.{i}.attn.proj.bias', F'beit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'{prefix}blocks.{i}.norm2.weight', F'beit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'{prefix}blocks.{i}.norm2.bias', F'beit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc1.weight', F'beit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc1.bias', F'beit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc2.weight', F'beit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'{prefix}blocks.{i}.mlp.fc2.bias', F'beit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ (F'{prefix}cls_token', 'beit.embeddings.cls_token'), (F'{prefix}patch_embed.proj.weight', 'beit.embeddings.patch_embeddings.projection.weight'), (F'{prefix}patch_embed.proj.bias', 'beit.embeddings.patch_embeddings.projection.bias'), (F'{prefix}pos_embed', 'beit.embeddings.position_embeddings'), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ('mask_token', 'beit.embeddings.mask_token'), ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ] ) else: # layernorm + classification head rename_keys.extend( [ ('fc_norm.weight', 'beit.pooler.layernorm.weight'), ('fc_norm.bias', 'beit.pooler.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ] ) return rename_keys def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : int=False ): for i in range(config.num_hidden_layers ): __UpperCamelCase ='backbone.' if is_semantic else '' # queries, keys and values __UpperCamelCase =state_dict.pop(F'{prefix}blocks.{i}.attn.qkv.weight' ) __UpperCamelCase =state_dict.pop(F'{prefix}blocks.{i}.attn.q_bias' ) __UpperCamelCase =state_dict.pop(F'{prefix}blocks.{i}.attn.v_bias' ) __UpperCamelCase =in_proj_weight[ : config.hidden_size, : ] __UpperCamelCase =q_bias __UpperCamelCase =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __UpperCamelCase =in_proj_weight[ -config.hidden_size :, : ] __UpperCamelCase =v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained __UpperCamelCase =state_dict.pop(F'{prefix}blocks.{i}.gamma_1' ) __UpperCamelCase =state_dict.pop(F'{prefix}blocks.{i}.gamma_2' ) __UpperCamelCase =gamma_a __UpperCamelCase =gamma_a def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =dct.pop(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =val def _UpperCAmelCase ( ): __UpperCamelCase ='http://images.cocodataset.org/val2017/000000039769.jpg' __UpperCamelCase =Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False ): __UpperCamelCase =False if 'rvlcdip' in checkpoint_url else True __UpperCamelCase =BeitConfig(use_absolute_position_embeddings=SCREAMING_SNAKE_CASE__ , use_mask_token=SCREAMING_SNAKE_CASE__ ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: __UpperCamelCase =10_24 __UpperCamelCase =40_96 __UpperCamelCase =24 __UpperCamelCase =16 # labels if "rvlcdip" in checkpoint_url: __UpperCamelCase =16 __UpperCamelCase ='huggingface/label-files' __UpperCamelCase ='rvlcdip-id2label.json' __UpperCamelCase =json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) , 'r' ) ) __UpperCamelCase ={int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} __UpperCamelCase =idalabel __UpperCamelCase ={v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys __UpperCamelCase =torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='cpu' )['model'] __UpperCamelCase =create_rename_keys(SCREAMING_SNAKE_CASE__ , has_lm_head=SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) read_in_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , has_lm_head=SCREAMING_SNAKE_CASE__ ) # load HuggingFace model __UpperCamelCase =BeitForMaskedImageModeling(SCREAMING_SNAKE_CASE__ ) if has_lm_head else BeitForImageClassification(SCREAMING_SNAKE_CASE__ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # Check outputs on an image __UpperCamelCase =BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =prepare_img() __UpperCamelCase =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) __UpperCamelCase =encoding['pixel_values'] __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =outputs.logits # verify logits __UpperCamelCase =[1, 16] if 'rvlcdip' in checkpoint_url else [1, 1_96, 81_92] assert logits.shape == torch.Size(SCREAMING_SNAKE_CASE__ ), "Shape of logits not as expected" Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: if has_lm_head: __UpperCamelCase ='dit-base' if 'base' in checkpoint_url else 'dit-large' else: __UpperCamelCase ='dit-base-finetuned-rvlcdip' if 'dit-b' in checkpoint_url else 'dit-large-finetuned-rvlcdip' image_processor.push_to_hub( repo_path_or_name=Path(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , organization='nielsr' , commit_message='Add image processor' , use_temp_dir=SCREAMING_SNAKE_CASE__ , ) model.push_to_hub( repo_path_or_name=Path(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , organization='nielsr' , commit_message='Add model' , use_temp_dir=SCREAMING_SNAKE_CASE__ , ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument( '--checkpoint_url', default='https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth', type=str, help='URL to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument( '--push_to_hub', action='store_true', ) _A = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __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 =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging _A = logging.get_logger(__name__) class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str UpperCAmelCase__ : str = None @staticmethod def _a ( ) -> Optional[int]: raise NotImplementedError def _a ( self , A_ , A_ , A_ , **A_ ) -> Dict: raise NotImplementedError def _a ( self , A_ ) -> List[Any]: raise NotImplementedError def _a ( self ) -> str: if not self.is_available(): raise RuntimeError( f'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' ) @classmethod def _a ( cls ) -> int: return f'`pip install {cls.pip_package or cls.name}`' class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Dict = "optuna" @staticmethod def _a ( ) -> Union[str, Any]: return is_optuna_available() def _a ( self , A_ , A_ , A_ , **A_ ) -> List[Any]: return run_hp_search_optuna(A_ , A_ , A_ , **A_ ) def _a ( self , A_ ) -> Dict: return default_hp_space_optuna(A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Tuple = "ray" UpperCAmelCase__ : str = "'ray[tune]'" @staticmethod def _a ( ) -> str: return is_ray_available() def _a ( self , A_ , A_ , A_ , **A_ ) -> str: return run_hp_search_ray(A_ , A_ , A_ , **A_ ) def _a ( self , A_ ) -> List[Any]: return default_hp_space_ray(A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = "sigopt" @staticmethod def _a ( ) -> Tuple: return is_sigopt_available() def _a ( self , A_ , A_ , A_ , **A_ ) -> int: return run_hp_search_sigopt(A_ , A_ , A_ , **A_ ) def _a ( self , A_ ) -> Union[str, Any]: return default_hp_space_sigopt(A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : List[Any] = "wandb" @staticmethod def _a ( ) -> Any: return is_wandb_available() def _a ( self , A_ , A_ , A_ , **A_ ) -> Optional[Any]: return run_hp_search_wandb(A_ , A_ , A_ , **A_ ) def _a ( self , A_ ) -> List[str]: return default_hp_space_wandb(A_ ) _A = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def _UpperCAmelCase ( ): __UpperCamelCase =[backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(SCREAMING_SNAKE_CASE__ ) > 0: __UpperCamelCase =available_backends[0].name if len(SCREAMING_SNAKE_CASE__ ) > 1: logger.info( F'{len(SCREAMING_SNAKE_CASE__ )} hyperparameter search backends available. Using {name} as the default.' ) return name raise RuntimeError( 'No hyperparameter search backend available.\n' + '\n'.join( F' - To install {backend.name} run {backend.pip_install()}' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
import math import sys def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase ='' try: with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as binary_file: __UpperCamelCase =binary_file.read() for dat in data: __UpperCamelCase =F'{dat:08b}' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase ={'0': '0', '1': '1'} __UpperCamelCase , __UpperCamelCase ='', '' __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __UpperCamelCase =lexicon[curr_string] result += last_match_id __UpperCamelCase =last_match_id + '0' if math.loga(SCREAMING_SNAKE_CASE__ ).is_integer(): __UpperCamelCase ={} for curr_key in list(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =lexicon.pop(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =new_lex __UpperCamelCase =last_match_id + '1' index += 1 __UpperCamelCase ='' return result def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =8 try: with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as opened_file: __UpperCamelCase =[ to_write[i : i + byte_length] for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_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[:-1]: opened_file.write(int(SCREAMING_SNAKE_CASE__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =0 for letter in data_bits: if letter == "1": break counter += 1 __UpperCamelCase =data_bits[counter:] __UpperCamelCase =data_bits[counter + 1 :] return data_bits def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =read_file_binary(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =remove_prefix(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =decompress_data(SCREAMING_SNAKE_CASE__ ) write_file_binary(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCAmelCase__ ( A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = VQModel UpperCAmelCase__ : str = "sample" @property def _a ( self , A_=(32, 32) ) -> str: __UpperCamelCase =4 __UpperCamelCase =3 __UpperCamelCase =floats_tensor((batch_size, num_channels) + sizes ).to(A_ ) return {"sample": image} @property def _a ( self ) -> str: return (3, 32, 32) @property def _a ( self ) -> Optional[int]: return (3, 32, 32) def _a ( self ) -> Optional[Any]: __UpperCamelCase ={ 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } __UpperCamelCase =self.dummy_input return init_dict, inputs_dict def _a ( self ) -> str: pass def _a ( self ) -> List[str]: pass def _a ( self ) -> int: __UpperCamelCase , __UpperCamelCase =VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=A_ ) self.assertIsNotNone(A_ ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(A_ ) __UpperCamelCase =model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _a ( self ) -> Tuple: __UpperCamelCase =VQModel.from_pretrained('fusing/vqgan-dummy' ) model.to(A_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) __UpperCamelCase =torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) __UpperCamelCase =image.to(A_ ) with torch.no_grad(): __UpperCamelCase =model(A_ ).sample __UpperCamelCase =output[0, -1, -3:, -3:].flatten().cpu() # fmt: off __UpperCamelCase =torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(A_ , A_ , atol=1E-3 ) )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
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 UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = "unispeech" def __init__( self , A_=32 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.1 , A_=0.1 , A_=0.02 , A_=1E-5 , A_="group" , A_="gelu" , A_=(512, 512, 512, 512, 512, 512, 512) , A_=(5, 2, 2, 2, 2, 2, 2) , A_=(10, 3, 3, 3, 3, 2, 2) , A_=False , A_=128 , A_=16 , A_=False , A_=True , A_=0.05 , A_=10 , A_=2 , A_=0.0 , A_=10 , A_=0 , A_=320 , A_=2 , A_=0.1 , A_=100 , A_=256 , A_=256 , A_=0.1 , A_="mean" , A_=False , A_=False , A_=256 , A_=80 , A_=0 , A_=1 , A_=2 , A_=0.5 , **A_ , ) -> int: super().__init__(**A_ , pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =feat_extract_norm __UpperCamelCase =feat_extract_activation __UpperCamelCase =list(A_ ) __UpperCamelCase =list(A_ ) __UpperCamelCase =list(A_ ) __UpperCamelCase =conv_bias __UpperCamelCase =num_conv_pos_embeddings __UpperCamelCase =num_conv_pos_embedding_groups __UpperCamelCase =len(self.conv_dim ) __UpperCamelCase =num_hidden_layers __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =num_attention_heads __UpperCamelCase =hidden_dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =feat_proj_dropout __UpperCamelCase =final_dropout __UpperCamelCase =layerdrop __UpperCamelCase =layer_norm_eps __UpperCamelCase =initializer_range __UpperCamelCase =num_ctc_classes __UpperCamelCase =vocab_size __UpperCamelCase =do_stable_layer_norm __UpperCamelCase =use_weighted_layer_sum __UpperCamelCase =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 __UpperCamelCase =apply_spec_augment __UpperCamelCase =mask_time_prob __UpperCamelCase =mask_time_length __UpperCamelCase =mask_time_min_masks __UpperCamelCase =mask_feature_prob __UpperCamelCase =mask_feature_length __UpperCamelCase =mask_feature_min_masks # parameters for pretraining with codevector quantized representations __UpperCamelCase =num_codevectors_per_group __UpperCamelCase =num_codevector_groups __UpperCamelCase =contrastive_logits_temperature __UpperCamelCase =feat_quantizer_dropout __UpperCamelCase =num_negatives __UpperCamelCase =codevector_dim __UpperCamelCase =proj_codevector_dim __UpperCamelCase =diversity_loss_weight # ctc loss __UpperCamelCase =ctc_loss_reduction __UpperCamelCase =ctc_zero_infinity # pretraining loss __UpperCamelCase =replace_prob @property def _a ( self ) -> Any: return functools.reduce(operator.mul , self.conv_stride , 1 )
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
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
import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin _A = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _A = 25_6047 _A = 25_6145 @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = NllbTokenizer UpperCAmelCase__ : Any = NllbTokenizerFast UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : Dict = {} def _a ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase =NllbTokenizer(A_ , keep_accents=A_ ) tokenizer.save_pretrained(self.tmpdirname ) def _a ( self ) -> Optional[int]: __UpperCamelCase =NllbTokenizer(A_ , keep_accents=A_ ) __UpperCamelCase =tokenizer.tokenize('This is a test' ) self.assertListEqual(A_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __UpperCamelCase =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( A_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual( A_ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def _a ( self ) -> int: __UpperCamelCase =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-nllb', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) __UpperCamelCase =self.tokenizer_class.from_pretrained(A_ , **A_ ) __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =tokenizer_r.save_pretrained(A_ ) __UpperCamelCase =tokenizer_p.save_pretrained(A_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) __UpperCamelCase =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(A_ , A_ ) # Checks everything loads correctly in the same way __UpperCamelCase =tokenizer_r.from_pretrained(A_ ) __UpperCamelCase =tokenizer_p.from_pretrained(A_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A_ , A_ ) ) shutil.rmtree(A_ ) # Save tokenizer rust, legacy_format=True __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =tokenizer_r.save_pretrained(A_ , legacy_format=A_ ) __UpperCamelCase =tokenizer_p.save_pretrained(A_ ) # Checks it save with the same files self.assertSequenceEqual(A_ , A_ ) # Checks everything loads correctly in the same way __UpperCamelCase =tokenizer_r.from_pretrained(A_ ) __UpperCamelCase =tokenizer_p.from_pretrained(A_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A_ , A_ ) ) shutil.rmtree(A_ ) # Save tokenizer rust, legacy_format=False __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =tokenizer_r.save_pretrained(A_ , legacy_format=A_ ) __UpperCamelCase =tokenizer_p.save_pretrained(A_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __UpperCamelCase =tokenizer_r.from_pretrained(A_ ) __UpperCamelCase =tokenizer_p.from_pretrained(A_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A_ , A_ ) ) shutil.rmtree(A_ ) @require_torch def _a ( self ) -> List[Any]: if not self.test_seqaseq: return __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __UpperCamelCase =[ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for' ' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons' ' will only worsen the violence and misery for millions of people.', ] __UpperCamelCase =[ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al' ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi' ' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] try: __UpperCamelCase =tokenizer.prepare_seqaseq_batch( src_texts=A_ , tgt_texts=A_ , max_length=3 , max_target_length=10 , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='ron_Latn' , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __UpperCamelCase =tokenizer.prepare_seqaseq_batch( A_ , tgt_texts=A_ , max_length=3 , return_tensors='pt' ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __UpperCamelCase =tokenizer.prepare_seqaseq_batch( src_texts=A_ , max_length=3 , max_target_length=10 , return_tensors='pt' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn('decoder_input_ids' , A_ ) @unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' ) def _a ( self ) -> List[Any]: pass def _a ( self ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =[AddedToken('<special>' , lstrip=A_ )] __UpperCamelCase =self.rust_tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , **A_ ) __UpperCamelCase =tokenizer_r.encode('Hey this is a <special> token' ) __UpperCamelCase =tokenizer_r.encode('<special>' , add_special_tokens=A_ )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __UpperCamelCase =self.rust_tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , **A_ , ) __UpperCamelCase =self.tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , **A_ ) __UpperCamelCase =tokenizer_p.encode('Hey this is a <special> token' ) __UpperCamelCase =tokenizer_cr.encode('Hey this is a <special> token' ) self.assertEqual(A_ , A_ ) self.assertEqual(A_ , A_ ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "facebook/nllb-200-distilled-600M" UpperCAmelCase__ : int = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] UpperCAmelCase__ : List[str] = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] UpperCAmelCase__ : Optional[Any] = [ 2_5_6_0_4_7, 1_6_2_9_7, 1_3_4_4_0_8, 8_1_6_5, 2_4_8_0_6_6, 1_4_7_3_4, 9_5_0, 1_1_3_5, 1_0_5_7_2_1, 3_5_7_3, 8_3, 2_7_3_5_2, 1_0_8, 4_9_4_8_6, 2, ] @classmethod def _a ( cls ) -> List[Any]: __UpperCamelCase =NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang='eng_Latn' , tgt_lang='ron_Latn' ) __UpperCamelCase =1 return cls def _a ( self ) -> Tuple: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] , 256001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] , 256002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] , 256057 ) def _a ( self ) -> Dict: __UpperCamelCase =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , A_ ) def _a ( self ) -> List[str]: self.assertIn(A_ , self.tokenizer.all_special_ids ) # fmt: off __UpperCamelCase =[RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: on __UpperCamelCase =self.tokenizer.decode(A_ , skip_special_tokens=A_ ) __UpperCamelCase =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=A_ ) self.assertEqual(A_ , A_ ) self.assertNotIn(self.tokenizer.eos_token , A_ ) def _a ( self ) -> Any: __UpperCamelCase =['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , A_ ) __UpperCamelCase =10 __UpperCamelCase =self.tokenizer(A_ , max_length=A_ , truncation=A_ ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , A_ ) self.assertEqual(len(A_ ) , A_ ) def _a ( self ) -> List[str]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [256203, 3] ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(A_ ) __UpperCamelCase =NllbTokenizer.from_pretrained(A_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , A_ ) @require_torch def _a ( self ) -> Dict: __UpperCamelCase =self.tokenizer( self.src_text , text_target=self.tgt_text , padding=A_ , truncation=A_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __UpperCamelCase =shift_tokens_right( batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['ron_Latn'] ) self.assertIsInstance(A_ , A_ ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __UpperCamelCase =batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , A_ ) self.assertEqual(A_ , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def _a ( self ) -> Any: __UpperCamelCase =self.tokenizer(self.src_text , padding=A_ , truncation=A_ , max_length=3 , return_tensors='pt' ) __UpperCamelCase =self.tokenizer( text_target=self.tgt_text , padding=A_ , truncation=A_ , max_length=10 , return_tensors='pt' ) __UpperCamelCase =targets['input_ids'] __UpperCamelCase =shift_tokens_right( A_ , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( nested_simplify(A_ ) , { # A, test, EOS, en_XX 'input_ids': [[256047, 70, 7356, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 256057, } , ) @require_torch def _a ( self ) -> Optional[int]: __UpperCamelCase =True __UpperCamelCase =self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047] ) __UpperCamelCase =False __UpperCamelCase =self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2] )
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _A = {'configuration_vit_mae': ['VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMAEConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMAEForPreTraining', 'ViTMAELayer', 'ViTMAEModel', 'ViTMAEPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '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 _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
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 UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "char" UpperCAmelCase__ : List[str] = "bpe" UpperCAmelCase__ : Tuple = "wp" _A = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = ["image_processor", "char_tokenizer"] UpperCAmelCase__ : str = "ViTImageProcessor" UpperCAmelCase__ : Optional[Any] = "MgpstrTokenizer" def __init__( self , A_=None , A_=None , **A_ ) -> Union[str, Any]: __UpperCamelCase =None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , A_ , ) __UpperCamelCase =kwargs.pop('feature_extractor' ) __UpperCamelCase =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`.' ) __UpperCamelCase =tokenizer __UpperCamelCase =AutoTokenizer.from_pretrained('gpt2' ) __UpperCamelCase =AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(A_ , A_ ) def __call__( self , A_=None , A_=None , A_=None , **A_ ) -> Any: 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: __UpperCamelCase =self.image_processor(A_ , return_tensors=A_ , **A_ ) if text is not None: __UpperCamelCase =self.char_tokenizer(A_ , return_tensors=A_ , **A_ ) if text is None: return inputs elif images is None: return encodings else: __UpperCamelCase =encodings['input_ids'] return inputs def _a ( self , A_ ) -> int: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =sequences __UpperCamelCase =char_preds.size(0 ) __UpperCamelCase , __UpperCamelCase =self._decode_helper(A_ , 'char' ) __UpperCamelCase , __UpperCamelCase =self._decode_helper(A_ , 'bpe' ) __UpperCamelCase , __UpperCamelCase =self._decode_helper(A_ , 'wp' ) __UpperCamelCase =[] __UpperCamelCase =[] for i in range(A_ ): __UpperCamelCase =[char_scores[i], bpe_scores[i], wp_scores[i]] __UpperCamelCase =[char_strs[i], bpe_strs[i], wp_strs[i]] __UpperCamelCase =scores.index(max(A_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __UpperCamelCase ={} __UpperCamelCase =final_strs __UpperCamelCase =final_scores __UpperCamelCase =char_strs __UpperCamelCase =bpe_strs __UpperCamelCase =wp_strs return out def _a ( self , A_ , A_ ) -> str: if format == DecodeType.CHARACTER: __UpperCamelCase =self.char_decode __UpperCamelCase =1 __UpperCamelCase ='[s]' elif format == DecodeType.BPE: __UpperCamelCase =self.bpe_decode __UpperCamelCase =2 __UpperCamelCase ='#' elif format == DecodeType.WORDPIECE: __UpperCamelCase =self.wp_decode __UpperCamelCase =102 __UpperCamelCase ='[SEP]' else: raise ValueError(f'Format {format} is not supported.' ) __UpperCamelCase , __UpperCamelCase =[], [] __UpperCamelCase =pred_logits.size(0 ) __UpperCamelCase =pred_logits.size(1 ) __UpperCamelCase , __UpperCamelCase =pred_logits.topk(1 , dim=-1 , largest=A_ , sorted=A_ ) __UpperCamelCase =preds_index.view(-1 , A_ )[:, 1:] __UpperCamelCase =decoder(A_ ) __UpperCamelCase , __UpperCamelCase =torch.nn.functional.softmax(A_ , dim=2 ).max(dim=2 ) __UpperCamelCase =preds_max_prob[:, 1:] for index in range(A_ ): __UpperCamelCase =preds_str[index].find(A_ ) __UpperCamelCase =preds_str[index][:pred_eos] __UpperCamelCase =preds_index[index].cpu().tolist() __UpperCamelCase =pred_index.index(A_ ) if eos_token in pred_index else -1 __UpperCamelCase =preds_max_prob[index][: pred_eos_index + 1] __UpperCamelCase =pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(A_ ) conf_scores.append(A_ ) return dec_strs, conf_scores def _a ( self , A_ ) -> int: __UpperCamelCase =[seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(A_ )] return decode_strs def _a ( self , A_ ) -> str: return self.bpe_tokenizer.batch_decode(A_ ) def _a ( self , A_ ) -> Optional[int]: __UpperCamelCase =[seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(A_ )] return decode_strs
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_jukebox': [ 'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'JukeboxConfig', 'JukeboxPriorConfig', 'JukeboxVQVAEConfig', ], 'tokenization_jukebox': ['JukeboxTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'JukeboxModel', 'JukeboxPreTrainedModel', 'JukeboxVQVAE', 'JukeboxPrior', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): if n_term == "": return [] __UpperCamelCase =[] for temp in range(int(SCREAMING_SNAKE_CASE__ ) ): series.append(F'1/{temp + 1}' if series else '1' ) return series if __name__ == "__main__": _A = input('Enter the last number (nth term) of the Harmonic Series') print('Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n') print(harmonic_series(nth_term))
62
from typing import TYPE_CHECKING from ...utils import _LazyModule _A = {'tokenization_wav2vec2_phoneme': ['Wav2Vec2PhonemeCTCTokenizer']} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _A = '\\n Text data.\n Second line of data.' _A = 'file' @pytest.fixture(scope='session' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] ): __UpperCamelCase =tmp_path_factory.mktemp('data' ) / (FILE_PATH + '.zstd') __UpperCamelCase =bytes(SCREAMING_SNAKE_CASE__ , 'utf-8' ) with zstd.open(SCREAMING_SNAKE_CASE__ , 'wb' ) as f: f.write(SCREAMING_SNAKE_CASE__ ) return path @pytest.fixture def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE__ ) , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE__ ) return FILE_PATH @pytest.mark.parametrize('compression_format' , ['gzip', 'xz', 'zstd'] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any ): __UpperCamelCase ={'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path} __UpperCamelCase =input_paths[compression_format] __UpperCamelCase =tmp_path / 'cache' __UpperCamelCase =DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE__ , extract_compressed_file=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =cached_path(SCREAMING_SNAKE_CASE__ , download_config=SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.read() with open(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize('default_extracted' , [True, False] ) @pytest.mark.parametrize('default_cache_dir' , [True, False] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ): __UpperCamelCase ='custom_cache' __UpperCamelCase ='custom_extracted_dir' __UpperCamelCase =tmp_path / 'custom_extracted_path' if default_extracted: __UpperCamelCase =('downloads' if default_cache_dir else custom_cache_dir, 'extracted') else: monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR' , SCREAMING_SNAKE_CASE__ ) monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __UpperCamelCase =xz_file __UpperCamelCase =( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =cached_path(SCREAMING_SNAKE_CASE__ , download_config=SCREAMING_SNAKE_CASE__ ) assert Path(SCREAMING_SNAKE_CASE__ ).parent.parts[-2:] == expected def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): # absolute path __UpperCamelCase =str(Path(SCREAMING_SNAKE_CASE__ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE__ ) == text_file # relative path __UpperCamelCase =str(Path(SCREAMING_SNAKE_CASE__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE__ ) == text_file def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): # absolute path __UpperCamelCase =str(tmp_path.resolve() / '__missing_file__.txt' ) with pytest.raises(SCREAMING_SNAKE_CASE__ ): cached_path(SCREAMING_SNAKE_CASE__ ) # relative path __UpperCamelCase ='./__missing_file__.txt' with pytest.raises(SCREAMING_SNAKE_CASE__ ): cached_path(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.read() assert output_file_content == FILE_CONTENT @patch('datasets.config.HF_DATASETS_OFFLINE' , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): with pytest.raises(SCREAMING_SNAKE_CASE__ ): cached_path('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] ): __UpperCamelCase =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(SCREAMING_SNAKE_CASE__ ): http_get('https://huggingface.co' , temp_file=SCREAMING_SNAKE_CASE__ ) with pytest.raises(SCREAMING_SNAKE_CASE__ ): http_head('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): __UpperCamelCase =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(SCREAMING_SNAKE_CASE__ ): ftp_get('ftp://huggingface.co' , temp_file=SCREAMING_SNAKE_CASE__ ) with pytest.raises(SCREAMING_SNAKE_CASE__ ): ftp_head('ftp://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(SCREAMING_SNAKE_CASE__ ): fsspec_get('s3://huggingface.co' , temp_file=SCREAMING_SNAKE_CASE__ ) with pytest.raises(SCREAMING_SNAKE_CASE__ ): fsspec_head('s3://huggingface.co' )
62
from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ ) -> float: return 0.0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) __UpperCamelCase =max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =np.abs(np.fft.fft(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =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 __UpperCamelCase =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 _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : FilterType , SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =5_12 __UpperCamelCase =[1] + [0] * (size - 1) __UpperCamelCase =[filter_type.process(SCREAMING_SNAKE_CASE__ ) for item in inputs] __UpperCamelCase =[0] * (samplerate - size) # zero-padding outputs += filler __UpperCamelCase =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()
62
1
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'): _A = True from torch.cuda.amp import autocast _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : Any=None ): return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE__ ) @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) UpperCAmelCase__ : Optional[str] = field( default=A_ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) UpperCAmelCase__ : Optional[bool] = field( default=A_ , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) UpperCAmelCase__ : Optional[float] = field( default=0.1 , metadata={"help": "The dropout ratio for the attention probabilities."} ) UpperCAmelCase__ : Optional[float] = field( default=0.1 , metadata={"help": "The dropout ratio for activations inside the fully connected layer."} ) UpperCAmelCase__ : Optional[float] = field( default=0.1 , metadata={ "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler." } , ) UpperCAmelCase__ : Optional[float] = field( default=0.1 , metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."} , ) UpperCAmelCase__ : Optional[float] = field( default=0.05 , metadata={ "help": ( "Propability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." ) } , ) UpperCAmelCase__ : Optional[float] = field(default=0.0 , metadata={"help": "The LayerDrop probability."} ) @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : Optional[str] = field( default=A_ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) UpperCAmelCase__ : Optional[str] = field( default="train+validation" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) UpperCAmelCase__ : bool = field( default=A_ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) UpperCAmelCase__ : Optional[int] = field( default=A_ , metadata={"help": "The number of processes to use for the preprocessing."} , ) UpperCAmelCase__ : Optional[int] = field( default=A_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) UpperCAmelCase__ : Optional[int] = field( default=A_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." ) } , ) UpperCAmelCase__ : List[str] = list_field( default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"] , metadata={"help": "A list of characters to remove from the transcripts."} , ) @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : WavaVecaProcessor UpperCAmelCase__ : Union[bool, str] = True UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : Optional[int] = None def __call__( self , A_ ) -> Dict[str, torch.Tensor]: # split inputs and labels since they have to be of different lenghts and need # different padding methods __UpperCamelCase =[{'input_values': feature['input_values']} for feature in features] __UpperCamelCase =[{'input_ids': feature['labels']} for feature in features] __UpperCamelCase =self.processor.pad( A_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) __UpperCamelCase =self.processor.pad( labels=A_ , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='pt' , ) # replace padding with -100 to ignore loss correctly __UpperCamelCase =labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) __UpperCamelCase =labels return batch class UpperCAmelCase__ ( A_ ): """simple docstring""" def _a ( self , A_ , A_ ) -> torch.Tensor: model.train() __UpperCamelCase =self._prepare_inputs(A_ ) if self.use_amp: with autocast(): __UpperCamelCase =self.compute_loss(A_ , A_ ) else: __UpperCamelCase =self.compute_loss(A_ , A_ ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": __UpperCamelCase =loss.mean() elif model.module.config.ctc_loss_reduction == "sum": __UpperCamelCase =loss.sum() / (inputs['labels'] >= 0).sum() else: raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']' ) if self.args.gradient_accumulation_steps > 1: __UpperCamelCase =loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(A_ ).backward() elif self.use_apex: with amp.scale_loss(A_ , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(A_ ) else: loss.backward() return loss.detach() def _UpperCAmelCase ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __UpperCamelCase =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =parser.parse_args_into_dataclasses() # Detecting last checkpoint. __UpperCamelCase =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __UpperCamelCase =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s' , SCREAMING_SNAKE_CASE__ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: __UpperCamelCase =datasets.load_dataset( 'common_voice' , data_args.dataset_config_name , split=data_args.train_split_name ) __UpperCamelCase =datasets.load_dataset('common_voice' , data_args.dataset_config_name , split='test' ) # Create and save tokenizer __UpperCamelCase =F'[{"".join(data_args.chars_to_ignore )}]' def remove_special_characters(SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =re.sub(SCREAMING_SNAKE_CASE__ , '' , batch['sentence'] ).lower() + ' ' return batch __UpperCamelCase =train_dataset.map(SCREAMING_SNAKE_CASE__ , remove_columns=['sentence'] ) __UpperCamelCase =eval_dataset.map(SCREAMING_SNAKE_CASE__ , remove_columns=['sentence'] ) def extract_all_chars(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __UpperCamelCase =' '.join(batch['text'] ) __UpperCamelCase =list(set(SCREAMING_SNAKE_CASE__ ) ) return {"vocab": [vocab], "all_text": [all_text]} __UpperCamelCase =train_dataset.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , batch_size=-1 , keep_in_memory=SCREAMING_SNAKE_CASE__ , remove_columns=train_dataset.column_names , ) __UpperCamelCase =train_dataset.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , batch_size=-1 , keep_in_memory=SCREAMING_SNAKE_CASE__ , remove_columns=eval_dataset.column_names , ) __UpperCamelCase =list(set(vocab_train['vocab'][0] ) | set(vocab_test['vocab'][0] ) ) __UpperCamelCase ={v: k for k, v in enumerate(SCREAMING_SNAKE_CASE__ )} __UpperCamelCase =vocab_dict[' '] del vocab_dict[" "] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) with open('vocab.json' , 'w' ) as vocab_file: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __UpperCamelCase =WavaVecaCTCTokenizer( 'vocab.json' , unk_token='[UNK]' , pad_token='[PAD]' , word_delimiter_token='|' , ) __UpperCamelCase =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0.0 , do_normalize=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='mean' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: __UpperCamelCase =min(len(SCREAMING_SNAKE_CASE__ ) , data_args.max_train_samples ) __UpperCamelCase =train_dataset.select(range(SCREAMING_SNAKE_CASE__ ) ) if data_args.max_val_samples is not None: __UpperCamelCase =eval_dataset.select(range(data_args.max_val_samples ) ) __UpperCamelCase =torchaudio.transforms.Resample(4_80_00 , 1_60_00 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(SCREAMING_SNAKE_CASE__ : Tuple ): __UpperCamelCase , __UpperCamelCase =torchaudio.load(batch['path'] ) __UpperCamelCase =resampler(SCREAMING_SNAKE_CASE__ ).squeeze().numpy() __UpperCamelCase =1_60_00 __UpperCamelCase =batch['text'] return batch __UpperCamelCase =train_dataset.map( SCREAMING_SNAKE_CASE__ , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) __UpperCamelCase =eval_dataset.map( SCREAMING_SNAKE_CASE__ , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(SCREAMING_SNAKE_CASE__ : List[Any] ): # check that all files have the correct sampling rate assert ( len(set(batch['sampling_rate'] ) ) == 1 ), F'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.' __UpperCamelCase =processor( audio=batch['speech'] , text=batch['target_text'] , sampling_rate=batch['sampling_rate'][0] ) batch.update(SCREAMING_SNAKE_CASE__ ) return batch __UpperCamelCase =train_dataset.map( SCREAMING_SNAKE_CASE__ , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=SCREAMING_SNAKE_CASE__ , num_proc=data_args.preprocessing_num_workers , ) __UpperCamelCase =eval_dataset.map( SCREAMING_SNAKE_CASE__ , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=SCREAMING_SNAKE_CASE__ , num_proc=data_args.preprocessing_num_workers , ) # Metric __UpperCamelCase =datasets.load_metric('wer' ) def compute_metrics(SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =pred.predictions __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=-1 ) __UpperCamelCase =processor.tokenizer.pad_token_id __UpperCamelCase =processor.batch_decode(SCREAMING_SNAKE_CASE__ ) # we do not want to group tokens when computing the metrics __UpperCamelCase =processor.batch_decode(pred.label_ids , group_tokens=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =wer_metric.compute(predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__ ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator __UpperCamelCase =DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # Initialize our Trainer __UpperCamelCase =CTCTrainer( model=SCREAMING_SNAKE_CASE__ , data_collator=SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , compute_metrics=SCREAMING_SNAKE_CASE__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: __UpperCamelCase =last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): __UpperCamelCase =model_args.model_name_or_path else: __UpperCamelCase =None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) __UpperCamelCase =trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__ ) trainer.save_model() __UpperCamelCase =train_result.metrics __UpperCamelCase =( data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) trainer.log_metrics('train' , SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('train' , SCREAMING_SNAKE_CASE__ ) trainer.save_state() # Evaluation __UpperCamelCase ={} if training_args.do_eval: logger.info('*** Evaluate ***' ) __UpperCamelCase =trainer.evaluate() __UpperCamelCase =data_args.max_val_samples if data_args.max_val_samples is not None else len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) trainer.log_metrics('eval' , SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('eval' , SCREAMING_SNAKE_CASE__ ) return results if __name__ == "__main__": main()
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = {'configuration_sew': ['SEW_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SEWConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'SEW_PRETRAINED_MODEL_ARCHIVE_LIST', 'SEWForCTC', 'SEWForSequenceClassification', 'SEWModel', 'SEWPreTrainedModel', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _A = 16 _A = 32 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Accelerator , SCREAMING_SNAKE_CASE__ : DatasetDict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : int = 16 ): __UpperCamelCase =AutoTokenizer.from_pretrained('bert-base-cased' ) __UpperCamelCase =DatasetDict( { 'train': dataset['train'].select(SCREAMING_SNAKE_CASE__ ), 'validation': dataset['train'].select(SCREAMING_SNAKE_CASE__ ), 'test': dataset['validation'], } ) def tokenize_function(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): # max_length=None => use the model max length (it's actually the default) __UpperCamelCase =tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __UpperCamelCase =datasets.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __UpperCamelCase =tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(SCREAMING_SNAKE_CASE__ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. __UpperCamelCase =1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __UpperCamelCase =16 elif accelerator.mixed_precision != "no": __UpperCamelCase =8 else: __UpperCamelCase =None return tokenizer.pad( SCREAMING_SNAKE_CASE__ , padding='longest' , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_tensors='pt' , ) # Instantiate dataloaders. __UpperCamelCase =DataLoader( tokenized_datasets['train'] , shuffle=SCREAMING_SNAKE_CASE__ , collate_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader( tokenized_datasets['validation'] , shuffle=SCREAMING_SNAKE_CASE__ , collate_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader( tokenized_datasets['test'] , shuffle=SCREAMING_SNAKE_CASE__ , collate_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader, test_dataloader def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict ): # New Code # __UpperCamelCase =[] # Download the dataset __UpperCamelCase =load_dataset('glue' , 'mrpc' ) # Create our splits __UpperCamelCase =StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator __UpperCamelCase =Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __UpperCamelCase =config['lr'] __UpperCamelCase =int(config['num_epochs'] ) __UpperCamelCase =int(config['seed'] ) __UpperCamelCase =int(config['batch_size'] ) __UpperCamelCase =evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation __UpperCamelCase =1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __UpperCamelCase =batch_size // MAX_GPU_BATCH_SIZE __UpperCamelCase =MAX_GPU_BATCH_SIZE set_seed(SCREAMING_SNAKE_CASE__ ) # New Code # # Create our folds: __UpperCamelCase =kfold.split(np.zeros(datasets['train'].num_rows ) , datasets['train']['label'] ) __UpperCamelCase =[] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =get_fold_dataloaders( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __UpperCamelCase =AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=SCREAMING_SNAKE_CASE__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __UpperCamelCase =model.to(accelerator.device ) # Instantiate optimizer __UpperCamelCase =AdamW(params=model.parameters() , lr=SCREAMING_SNAKE_CASE__ ) # Instantiate scheduler __UpperCamelCase =get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__ , num_warmup_steps=1_00 , num_training_steps=(len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =accelerator.prepare( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Now we train the model for epoch in range(SCREAMING_SNAKE_CASE__ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __UpperCamelCase =model(**SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =outputs.loss __UpperCamelCase =loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __UpperCamelCase =model(**SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =outputs.logits.argmax(dim=-1 ) __UpperCamelCase , __UpperCamelCase =accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__ , ) __UpperCamelCase =metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , SCREAMING_SNAKE_CASE__ ) # New Code # # We also run predictions on the test set at the very end __UpperCamelCase =[] for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __UpperCamelCase =model(**SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =outputs.logits __UpperCamelCase , __UpperCamelCase =accelerator.gather_for_metrics((predictions, batch['labels']) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: __UpperCamelCase =torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) __UpperCamelCase =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) __UpperCamelCase =metric.compute(predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__ ) accelerator.print('Average test metrics from all folds:' , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) # New Code # parser.add_argument('--num_folds' , type=SCREAMING_SNAKE_CASE__ , default=3 , help='The number of splits to perform across the dataset' ) __UpperCamelCase =parser.parse_args() __UpperCamelCase ={'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
62
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "mvp" UpperCAmelCase__ : Tuple = ["past_key_values"] UpperCAmelCase__ : Union[str, Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self , A_=50267 , A_=1024 , A_=12 , A_=4096 , A_=16 , A_=12 , A_=4096 , A_=16 , A_=0.0 , A_=0.0 , A_="gelu" , A_=1024 , A_=0.1 , A_=0.0 , A_=0.0 , A_=0.02 , A_=0.0 , A_=False , A_=True , A_=1 , A_=0 , A_=2 , A_=True , A_=2 , A_=2 , A_=False , A_=100 , A_=800 , **A_ , ) -> Union[str, Any]: __UpperCamelCase =vocab_size __UpperCamelCase =max_position_embeddings __UpperCamelCase =d_model __UpperCamelCase =encoder_ffn_dim __UpperCamelCase =encoder_layers __UpperCamelCase =encoder_attention_heads __UpperCamelCase =decoder_ffn_dim __UpperCamelCase =decoder_layers __UpperCamelCase =decoder_attention_heads __UpperCamelCase =dropout __UpperCamelCase =attention_dropout __UpperCamelCase =activation_dropout __UpperCamelCase =activation_function __UpperCamelCase =init_std __UpperCamelCase =encoder_layerdrop __UpperCamelCase =decoder_layerdrop __UpperCamelCase =classifier_dropout __UpperCamelCase =use_cache __UpperCamelCase =encoder_layers __UpperCamelCase =scale_embedding # scale factor will be sqrt(d_model) if True __UpperCamelCase =use_prompt __UpperCamelCase =prompt_length __UpperCamelCase =prompt_mid_dim super().__init__( pad_token_id=A_ , bos_token_id=A_ , eos_token_id=A_ , is_encoder_decoder=A_ , decoder_start_token_id=A_ , forced_eos_token_id=A_ , **A_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , A_ ): __UpperCamelCase =self.bos_token_id warnings.warn( f'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' 'The config can simply be saved and uploaded again to be fixed.' )
62
1
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _A = get_tests_dir('fixtures/spiece.model') @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : List[str] = DebertaVaTokenizer UpperCAmelCase__ : Tuple = DebertaVaTokenizerFast UpperCAmelCase__ : Optional[int] = True UpperCAmelCase__ : Optional[Any] = True def _a ( self ) -> List[str]: super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase =DebertaVaTokenizer(A_ , unk_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def _a ( self , A_ ) -> Dict: __UpperCamelCase ='this is a test' __UpperCamelCase ='this is a test' return input_text, output_text def _a ( self ) -> Tuple: __UpperCamelCase ='<pad>' __UpperCamelCase =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_ ) , A_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_ ) , A_ ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '[PAD]' ) self.assertEqual(len(A_ ) , 30001 ) def _a ( self ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 30000 ) def _a ( self ) -> List[Any]: # fmt: off __UpperCamelCase =' \tHeLLo!how \n Are yoU? ' __UpperCamelCase =['▁hello', '!', 'how', '▁are', '▁you', '?'] # fmt: on __UpperCamelCase =DebertaVaTokenizer(A_ , do_lower_case=A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , do_lower_case=A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def _a ( self ) -> Optional[int]: pass @unittest.skip('There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.' ) def _a ( self ) -> str: pass def _a ( self ) -> Dict: # fmt: off __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __UpperCamelCase =DebertaVaTokenizer(A_ , split_by_punct=A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , split_by_punct=A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Optional[int]: # fmt: off __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =['▁i', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __UpperCamelCase =DebertaVaTokenizer(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Any: # fmt: off __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on __UpperCamelCase =DebertaVaTokenizer(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Union[str, Any]: # fmt: off __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on __UpperCamelCase =DebertaVaTokenizer(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Tuple: # fmt: off __UpperCamelCase =' \tHeLLo!how \n Are yoU? ' __UpperCamelCase =['▁', '<unk>', 'e', '<unk>', 'o', '!', 'how', '▁', '<unk>', 're', '▁yo', '<unk>', '?'] # fmt: on __UpperCamelCase =DebertaVaTokenizer(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , do_lower_case=A_ , split_by_punct=A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =tokenizer.convert_ids_to_tokens(tokenizer.encode(A_ , add_special_tokens=A_ ) ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(A_ , add_special_tokens=A_ ) ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =self.get_rust_tokenizer() __UpperCamelCase =tokenizer.encode(A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase ='This is a test' __UpperCamelCase =[13, 1, 4398, 25, 21, 1289] __UpperCamelCase =['▁', 'T', 'his', '▁is', '▁a', '▁test'] __UpperCamelCase =['▁', '<unk>', 'his', '▁is', '▁a', '▁test'] __UpperCamelCase =DebertaVaTokenizer(A_ , keep_accents=A_ ) __UpperCamelCase =DebertaVaTokenizerFast(A_ , keep_accents=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual(A_ , A_ ) # fmt: off __UpperCamelCase ='I was born in 92000, and this is falsé.' __UpperCamelCase =[13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] __UpperCamelCase =['▁', 'I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.', ] __UpperCamelCase =['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =rust_tokenizer.convert_ids_to_tokens(A_ ) self.assertListEqual(A_ , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =DebertaVaTokenizer(A_ ) __UpperCamelCase =tokenizer.encode('sequence builders' ) __UpperCamelCase =tokenizer.encode('multi-sequence build' ) __UpperCamelCase =tokenizer.build_inputs_with_special_tokens(A_ ) __UpperCamelCase =tokenizer.build_inputs_with_special_tokens(A_ , A_ ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , A_ ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , A_ , ) @slow def _a ( self ) -> Optional[int]: # fmt: off __UpperCamelCase ={'input_ids': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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], [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, 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=A_ , model_name='microsoft/deberta-v2-xlarge' , revision='ad6e42c1532ddf3a15c39246b63f5559d558b670' , )
62
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Dict = GPTaTokenizer UpperCAmelCase__ : Any = GPTaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : int = {"add_prefix_space": True} UpperCAmelCase__ : Any = False def _a ( self ) -> Optional[int]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __UpperCamelCase =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __UpperCamelCase =dict(zip(A_ , range(len(A_ ) ) ) ) __UpperCamelCase =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __UpperCamelCase ={'unk_token': '<unk>'} __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(A_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(A_ ) ) def _a ( self , **A_ ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , **A_ ) -> Optional[Any]: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='lower newer' __UpperCamelCase ='lower newer' return input_text, output_text def _a ( self ) -> List[Any]: __UpperCamelCase =GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __UpperCamelCase ='lower newer' __UpperCamelCase =['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) self.assertListEqual(A_ , A_ ) __UpperCamelCase =tokens + [tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self ) -> int: if not self.test_rust_tokenizer: return __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase ='lower newer' # Testing tokenization __UpperCamelCase =tokenizer.tokenize(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.tokenize(A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids without special tokens __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ , add_special_tokens=A_ ) self.assertListEqual(A_ , A_ ) # Testing conversion to ids with special tokens __UpperCamelCase =self.get_rust_tokenizer(add_prefix_space=A_ ) __UpperCamelCase =tokenizer.encode(A_ , add_prefix_space=A_ ) __UpperCamelCase =rust_tokenizer.encode(A_ ) self.assertListEqual(A_ , A_ ) # Testing the unknown token __UpperCamelCase =tokens + [rust_tokenizer.unk_token] __UpperCamelCase =[14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(A_ ) , A_ ) def _a ( self , *A_ , **A_ ) -> Optional[int]: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _a ( self , A_=15 ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('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(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Simple input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) # Pair input self.assertRaises(A_ , tokenizer_r.encode , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises(A_ , tokenizer_r.encode_plus , A_ , max_length=A_ , padding='max_length' ) # Pair input self.assertRaises( A_ , tokenizer_r.batch_encode_plus , A_ , max_length=A_ , padding='max_length' , ) def _a ( self ) -> int: __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input looooooooong', 'This is a simple input'] __UpperCamelCase =('This is a simple input', 'This is a pair') __UpperCamelCase =[ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __UpperCamelCase =tokenizer.pad_token_id __UpperCamelCase =tokenizer(A_ , padding='max_length' , max_length=30 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , return_tensors='np' ) __UpperCamelCase =tokenizer(*A_ , padding='max_length' , max_length=60 , return_tensors='np' ) __UpperCamelCase =tokenizer(A_ , padding=A_ , truncate=A_ , 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 ) -> Union[str, Any]: __UpperCamelCase ='$$$' __UpperCamelCase =GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=A_ , add_bos_token=A_ ) __UpperCamelCase ='This is a simple input' __UpperCamelCase =['This is a simple input 1', 'This is a simple input 2'] __UpperCamelCase =tokenizer.bos_token_id __UpperCamelCase =tokenizer(A_ ) __UpperCamelCase =tokenizer(A_ ) self.assertEqual(out_s.input_ids[0] , A_ ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __UpperCamelCase =tokenizer.decode(out_s.input_ids ) __UpperCamelCase =tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , A_ ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Any: # TODO: change to self.get_tokenizers() when the fast version is implemented __UpperCamelCase =[self.get_tokenizer(do_lower_case=A_ , add_bos_token=A_ )] for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): __UpperCamelCase ='Encode this.' __UpperCamelCase ='This one too please.' __UpperCamelCase =tokenizer.encode(A_ , add_special_tokens=A_ ) encoded_sequence += tokenizer.encode(A_ , add_special_tokens=A_ ) __UpperCamelCase =tokenizer.encode_plus( A_ , A_ , add_special_tokens=A_ , return_special_tokens_mask=A_ , ) __UpperCamelCase =encoded_sequence_dict['input_ids'] __UpperCamelCase =encoded_sequence_dict['special_tokens_mask'] self.assertEqual(len(A_ ) , len(A_ ) ) __UpperCamelCase =[ (x if not special_tokens_mask[i] else None) for i, x in enumerate(A_ ) ] __UpperCamelCase =[x for x in filtered_sequence if x is not None] self.assertEqual(A_ , A_ ) @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Optional[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('test_opt' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./test_opt' ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) def _a ( self ) -> Dict: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , use_slow=A_ ) __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # Same as above self.assertEqual(A_ , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip('This test is failing because of a bug in the fast tokenizer' ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('facebook/opt-350m' , from_slow=A_ ) __UpperCamelCase ='bos' __UpperCamelCase =tokenizer.get_vocab()['bos'] __UpperCamelCase ='A photo of a cat' __UpperCamelCase =tokenizer.encode( A_ , ) # We changed the bos token self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained('./tok' ) __UpperCamelCase =AutoTokenizer.from_pretrained('./tok' ) self.assertTrue(tokenizer.is_fast ) __UpperCamelCase =tokenizer.encode( A_ , ) self.assertEqual(A_ , [31957, 250, 1345, 9, 10, 4758] )
62
1
from ....configuration_utils import PretrainedConfig from ....utils import logging _A = logging.get_logger(__name__) # TODO: upload to AWS _A = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = "retribert" def __init__( self , A_=30522 , A_=768 , A_=8 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1E-12 , A_=True , A_=128 , A_=0 , **A_ , ) -> List[str]: super().__init__(pad_token_id=A_ , **A_ ) __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_size __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =share_encoders __UpperCamelCase =projection_dim
62
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ = None ) -> None: if components is None: __UpperCamelCase =[] __UpperCamelCase =list(A_ ) def __len__( self ) -> int: return len(self.__components ) def __str__( self ) -> str: return "(" + ",".join(map(A_ , self.__components ) ) + ")" def __add__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] + other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: raise Exception('must have the same size' ) def __sub__( self , A_ ) -> Vector: __UpperCamelCase =len(self ) if size == len(A_ ): __UpperCamelCase =[self.__components[i] - other.component(A_ ) for i in range(A_ )] return Vector(A_ ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , A_ ) -> Vector: ... @overload def __mul__( self , A_ ) -> float: ... def __mul__( self , A_ ) -> float | Vector: if isinstance(A_ , (float, int) ): __UpperCamelCase =[c * other for c in self.__components] return Vector(A_ ) elif isinstance(A_ , A_ ) and len(self ) == len(A_ ): __UpperCamelCase =len(self ) __UpperCamelCase =[self.__components[i] * other.component(A_ ) for i in range(A_ )] return sum(A_ ) else: # error case raise Exception('invalid operand!' ) def _a ( self ) -> Vector: return Vector(self.__components ) def _a ( self , A_ ) -> float: if isinstance(A_ , A_ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _a ( self , A_ , A_ ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __UpperCamelCase =value def _a ( self ) -> float: if len(self.__components ) == 0: raise Exception('Vector is empty' ) __UpperCamelCase =[c**2 for c in self.__components] return math.sqrt(sum(A_ ) ) def _a ( self , A_ , A_ = False ) -> float: __UpperCamelCase =self * other __UpperCamelCase =self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __UpperCamelCase =[0] * dimension __UpperCamelCase =1 return Vector(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Vector , SCREAMING_SNAKE_CASE__ : Vector ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_ , A_ ) -> None: __UpperCamelCase =matrix __UpperCamelCase =w __UpperCamelCase =h def __str__( self ) -> str: __UpperCamelCase ='' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] + other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , A_ ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __UpperCamelCase =[] for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] - other.component(A_ , A_ ) for j in range(self.__width ) ] matrix.append(A_ ) return Matrix(A_ , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , A_ ) -> Matrix: ... @overload def __mul__( self , A_ ) -> Vector: ... def __mul__( self , A_ ) -> Vector | Matrix: if isinstance(A_ , A_ ): # matrix-vector if len(A_ ) == self.__width: __UpperCamelCase =zero_vector(self.__height ) for i in range(self.__height ): __UpperCamelCase =[ self.__matrix[i][j] * other.component(A_ ) for j in range(self.__width ) ] ans.change_component(A_ , sum(A_ ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(A_ , (int, float) ): # matrix-scalar __UpperCamelCase =[ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(A_ , self.__width , self.__height ) return None def _a ( self ) -> int: return self.__height def _a ( self ) -> int: return self.__width def _a ( self , A_ , A_ ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ , A_ ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __UpperCamelCase =value else: raise Exception('change_component: indices out of bounds' ) def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) __UpperCamelCase =self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(A_ ) ): __UpperCamelCase =minor[i][:y] + minor[i][y + 1 :] return Matrix(A_ , self.__width - 1 , self.__height - 1 ).determinant() def _a ( self , A_ , A_ ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(A_ , A_ ) else: raise Exception('Indices out of bounds' ) def _a ( self ) -> float: if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __UpperCamelCase =[ self.__matrix[0][y] * self.cofactor(0 , A_ ) for y in range(self.__width ) ] return sum(A_ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =[[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): random.seed(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
62
1
from string import ascii_lowercase, ascii_uppercase def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str ): if not sentence: return "" __UpperCamelCase =dict(zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
62
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
1
from __future__ import annotations class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =data __UpperCamelCase =None __UpperCamelCase =None def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Node | None ): # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Node | None ): return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Node ): if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def _UpperCAmelCase ( ): # Main function for testing. __UpperCamelCase =Node(1 ) __UpperCamelCase =Node(2 ) __UpperCamelCase =Node(3 ) __UpperCamelCase =Node(4 ) __UpperCamelCase =Node(5 ) __UpperCamelCase =Node(6 ) __UpperCamelCase =Node(7 ) __UpperCamelCase =Node(8 ) __UpperCamelCase =Node(9 ) print(is_full_binary_tree(SCREAMING_SNAKE_CASE__ ) ) print(depth_of_tree(SCREAMING_SNAKE_CASE__ ) ) print('Tree is: ' ) display(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
62
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _A = logging.get_logger(__name__) _A = '▁' _A = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} _A = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } _A = {'vinai/bartpho-syllable': 1024} class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = ["input_ids", "attention_mask"] def __init__( self , A_ , A_ , A_="<s>" , A_="</s>" , A_="</s>" , A_="<s>" , A_="<unk>" , A_="<pad>" , A_="<mask>" , A_ = None , **A_ , ) -> None: # Mask token behave like a normal word, i.e. include the space before it __UpperCamelCase =AddedToken(A_ , lstrip=A_ , rstrip=A_ ) if isinstance(A_ , A_ ) else mask_token __UpperCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A_ , eos_token=A_ , unk_token=A_ , sep_token=A_ , cls_token=A_ , pad_token=A_ , mask_token=A_ , sp_model_kwargs=self.sp_model_kwargs , **A_ , ) __UpperCamelCase =vocab_file __UpperCamelCase =monolingual_vocab_file __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility __UpperCamelCase ={} __UpperCamelCase =0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =cnt cnt += 1 with open(A_ , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): __UpperCamelCase =line.strip().split()[0] __UpperCamelCase =len(self.fairseq_tokens_to_ids ) if str(A_ ) not in self.fairseq_tokens_to_ids: __UpperCamelCase =len(self.fairseq_tokens_to_ids ) __UpperCamelCase ={v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Any: __UpperCamelCase =self.__dict__.copy() __UpperCamelCase =None __UpperCamelCase =self.sp_model.serialized_model_proto() return state def __setstate__( self , A_ ) -> List[str]: __UpperCamelCase =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __UpperCamelCase ={} __UpperCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , A_ , A_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCamelCase =[self.cls_token_id] __UpperCamelCase =[self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , A_ , A_ = None , A_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A_ , token_ids_a=A_ , already_has_special_tokens=A_ ) if token_ids_a is None: return [1] + ([0] * len(A_ )) + [1] return [1] + ([0] * len(A_ )) + [1, 1] + ([0] * len(A_ )) + [1] def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> Any: return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> Union[str, Any]: __UpperCamelCase ={self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , A_ ) -> List[str]: return self.sp_model.encode(A_ , out_type=A_ ) def _a ( self , A_ ) -> str: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , A_ ) -> int: return self.fairseq_ids_to_tokens[index] def _a ( self , A_ ) -> List[Any]: __UpperCamelCase =''.join(A_ ).replace(A_ , ' ' ).strip() return out_string def _a ( self , A_ , A_ = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) __UpperCamelCase =os.path.join( A_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ , 'wb' ) as fi: __UpperCamelCase =self.sp_model.serialized_model_proto() fi.write(A_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( A_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , A_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(A_ , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(A_ )} \n' ) return out_vocab_file, out_monolingual_vocab_file
62
1
_A = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _A = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) order.append(SCREAMING_SNAKE_CASE__ ) return order def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[bool] ): __UpperCamelCase =True __UpperCamelCase =[vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return component def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : dict[int, list[int]] ): __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] __UpperCamelCase ={vert: [] for vert in range(len(SCREAMING_SNAKE_CASE__ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE__ ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) * [False] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __UpperCamelCase =order[len(SCREAMING_SNAKE_CASE__ ) - i - 1] if not visited[vert]: __UpperCamelCase =find_components(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) components_list.append(SCREAMING_SNAKE_CASE__ ) return components_list
62
from numpy import exp, pi, sqrt def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : float = 1.0 ): return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
62
1
from sklearn.metrics import fa_score import datasets _A = '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n' _A = '\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {\'f1\': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results[\'f1\'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric("f1")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results[\'f1\'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n >>> print(round(results[\'f1\'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n >>> print(round(results[\'f1\'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {\'f1\': array([0.8, 0. , 0. ])}\n' _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 UpperCAmelCase__ ( datasets.Metric ): """simple docstring""" def _a ( self ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def _a ( self , A_ , A_ , A_=None , A_=1 , A_="binary" , A_=None ) -> Tuple: __UpperCamelCase =fa_score( A_ , A_ , labels=A_ , pos_label=A_ , average=A_ , sample_weight=A_ ) return {"f1": float(A_ ) if score.size == 1 else score}
62
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _A = logging.get_logger(__name__) if is_vision_available(): import PIL class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BICUBIC , A_ = True , A_ = None , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = None , A_ = True , **A_ , ) -> None: super().__init__(**A_ ) __UpperCamelCase =size if size is not None else {'shortest_edge': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) __UpperCamelCase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ , param_name='crop_size' ) __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =resample __UpperCamelCase =do_center_crop __UpperCamelCase =crop_size __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_normalize __UpperCamelCase =image_mean if image_mean is not None else OPENAI_CLIP_MEAN __UpperCamelCase =image_std if image_std is not None else OPENAI_CLIP_STD __UpperCamelCase =do_convert_rgb def _a ( self , A_ , A_ , A_ = PILImageResampling.BICUBIC , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ , default_to_square=A_ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __UpperCamelCase =get_resize_output_image_size(A_ , size=size['shortest_edge'] , default_to_square=A_ ) return resize(A_ , size=A_ , resample=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: __UpperCamelCase =get_size_dict(A_ ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys (height, width). Got {size.keys()}' ) return center_crop(A_ , size=(size['height'], size['width']) , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ = None , **A_ , ) -> Union[str, Any]: return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _a ( self , A_ , A_ , A_ , A_ = None , **A_ , ) -> np.ndarray: return normalize(A_ , mean=A_ , std=A_ , data_format=A_ , **A_ ) def _a ( 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: __UpperCamelCase =do_resize if do_resize is not None else self.do_resize __UpperCamelCase =size if size is not None else self.size __UpperCamelCase =get_size_dict(A_ , param_name='size' , default_to_square=A_ ) __UpperCamelCase =resample if resample is not None else self.resample __UpperCamelCase =do_center_crop if do_center_crop is not None else self.do_center_crop __UpperCamelCase =crop_size if crop_size is not None else self.crop_size __UpperCamelCase =get_size_dict(A_ , param_name='crop_size' , default_to_square=A_ ) __UpperCamelCase =do_rescale if do_rescale is not None else self.do_rescale __UpperCamelCase =rescale_factor if rescale_factor is not None else self.rescale_factor __UpperCamelCase =do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase =image_mean if image_mean is not None else self.image_mean __UpperCamelCase =image_std if image_std is not None else self.image_std __UpperCamelCase =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase =make_list_of_images(A_ ) if not valid_images(A_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase =[convert_to_rgb(A_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase =[to_numpy_array(A_ ) for image in images] if do_resize: __UpperCamelCase =[self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: __UpperCamelCase =[self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: __UpperCamelCase =[self.rescale(image=A_ , scale=A_ ) for image in images] if do_normalize: __UpperCamelCase =[self.normalize(image=A_ , mean=A_ , std=A_ ) for image in images] __UpperCamelCase =[to_channel_dimension_format(A_ , A_ ) for image in images] __UpperCamelCase ={'pixel_values': images} return BatchFeature(data=A_ , tensor_type=A_ )
62
1
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[int] ): # Check if the input is valid if not len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =equationa __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =equationa # Calculate the determinants of the matrices __UpperCamelCase =aa * ba - aa * ba __UpperCamelCase =ca * ba - ca * ba __UpperCamelCase =aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: __UpperCamelCase =determinant_x / determinant __UpperCamelCase =determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
62
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "yolos" def __init__( self , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=[512, 864] , A_=16 , A_=3 , A_=True , A_=100 , A_=True , A_=False , A_=1 , A_=5 , A_=2 , A_=5 , A_=2 , A_=0.1 , **A_ , ) -> Any: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =qkv_bias __UpperCamelCase =num_detection_tokens __UpperCamelCase =use_mid_position_embeddings __UpperCamelCase =auxiliary_loss # Hungarian matcher __UpperCamelCase =class_cost __UpperCamelCase =bbox_cost __UpperCamelCase =giou_cost # Loss coefficients __UpperCamelCase =bbox_loss_coefficient __UpperCamelCase =giou_loss_coefficient __UpperCamelCase =eos_coefficient class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : str = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4 @property def _a ( self ) -> int: return 12
62
1
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function _A = 1.0_54_57_18_17e-34 # unit of ℏ : J * s _A = 3e8 # unit of c : m * s^-1 def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): if (force, area, distance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if force < 0: raise ValueError('Magnitude of force can not be negative' ) if distance < 0: raise ValueError('Distance can not be negative' ) if area < 0: raise ValueError('Area can not be negative' ) if force == 0: __UpperCamelCase =(REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_40 * (distance) ** 4 ) return {"force": force} elif area == 0: __UpperCamelCase =(2_40 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: __UpperCamelCase =( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_40 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError('One and only one argument must be 0' ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
62
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
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 KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
62
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
1
from __future__ import annotations import math class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =size # approximate the overall size of segment tree with given value __UpperCamelCase =[0 for i in range(0 , 4 * size )] # create array to store lazy update __UpperCamelCase =[0 for i in range(0 , 4 * size )] __UpperCamelCase =[0 for i in range(0 , 4 * size )] # flag for lazy update def _a ( self , A_ ) -> int: return idx * 2 def _a ( self , A_ ) -> int: return idx * 2 + 1 def _a ( self , A_ , A_ , A_ , A_ ) -> None: if left_element == right_element: __UpperCamelCase =a[left_element - 1] else: __UpperCamelCase =(left_element + right_element) // 2 self.build(self.left(A_ ) , A_ , A_ , A_ ) self.build(self.right(A_ ) , mid + 1 , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ ) -> bool: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: __UpperCamelCase =val if left_element != right_element: __UpperCamelCase =val __UpperCamelCase =val __UpperCamelCase =True __UpperCamelCase =True return True __UpperCamelCase =(left_element + right_element) // 2 self.update(self.left(A_ ) , A_ , A_ , A_ , A_ , A_ ) self.update(self.right(A_ ) , mid + 1 , A_ , A_ , A_ , A_ ) __UpperCamelCase =max( self.segment_tree[self.left(A_ )] , self.segment_tree[self.right(A_ )] ) return True def _a ( self , A_ , A_ , A_ , A_ , A_ ) -> int | float: if self.flag[idx] is True: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =False if left_element != right_element: __UpperCamelCase =self.lazy[idx] __UpperCamelCase =self.lazy[idx] __UpperCamelCase =True __UpperCamelCase =True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] __UpperCamelCase =(left_element + right_element) // 2 __UpperCamelCase =self.query(self.left(A_ ) , A_ , A_ , A_ , A_ ) __UpperCamelCase =self.query(self.right(A_ ) , mid + 1 , A_ , A_ , A_ ) return max(A_ , A_ ) def __str__( self ) -> str: return str([self.query(1 , 1 , self.size , A_ , A_ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": _A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] _A = 15 _A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
62
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "" ): __UpperCamelCase =url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __UpperCamelCase =BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __UpperCamelCase =soup.find_all('td' , attrs='titleColumn' ) __UpperCamelCase =soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str = "IMDb_Top_250_Movies.csv" ): __UpperCamelCase =get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __UpperCamelCase =csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
62
1
import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class UpperCAmelCase__ : """simple docstring""" @staticmethod def _a ( *A_ , **A_ ) -> Union[str, Any]: pass def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Image ): __UpperCamelCase =hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def _a ( self , A_ , A_ , A_ ) -> Tuple: __UpperCamelCase =DepthEstimationPipeline(model=A_ , image_processor=A_ ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _a ( self , A_ , A_ ) -> Tuple: __UpperCamelCase =depth_estimator('./tests/fixtures/tests_samples/COCO/000000039769.png' ) self.assertEqual({'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )} , A_ ) import datasets __UpperCamelCase =datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' ) __UpperCamelCase =depth_estimator( [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] ) self.assertEqual( [ {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, ] , A_ , ) @require_tf @unittest.skip('Depth estimation is not implemented in TF' ) def _a ( self ) -> Optional[Any]: pass @slow @require_torch def _a ( self ) -> Tuple: __UpperCamelCase ='Intel/dpt-large' __UpperCamelCase =pipeline('depth-estimation' , model=A_ ) __UpperCamelCase =depth_estimator('http://images.cocodataset.org/val2017/000000039769.jpg' ) __UpperCamelCase =hashimage(outputs['depth'] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['predicted_depth'].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['predicted_depth'].min().item() ) , 2.662 ) @require_torch def _a ( self ) -> List[Any]: # This is highly irregular to have no small tests. self.skipTest('There is not hf-internal-testing tiny model for either GLPN nor DPT' )
62
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _A = logging.get_logger(__name__) _A = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip_vision_model" def __init__( self , A_=1408 , A_=6144 , A_=39 , A_=16 , A_=224 , A_=14 , A_="gelu" , A_=1E-6 , A_=0.0 , A_=1E-10 , A_=True , **A_ , ) -> Tuple: super().__init__(**A_ ) __UpperCamelCase =hidden_size __UpperCamelCase =intermediate_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =patch_size __UpperCamelCase =image_size __UpperCamelCase =initializer_range __UpperCamelCase =attention_dropout __UpperCamelCase =layer_norm_eps __UpperCamelCase =hidden_act __UpperCamelCase =qkv_bias @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "instructblip_qformer" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=0.02 , A_=1E-12 , A_=0 , A_="absolute" , A_=2 , A_=1408 , **A_ , ) -> Optional[Any]: super().__init__(pad_token_id=A_ , **A_ ) __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 =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =position_embedding_type __UpperCamelCase =cross_attention_frequency __UpperCamelCase =encoder_hidden_size @classmethod def _a ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) __UpperCamelCase , __UpperCamelCase =cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __UpperCamelCase =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "instructblip" UpperCAmelCase__ : Optional[Any] = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> List[str]: super().__init__(**A_ ) if vision_config is None: __UpperCamelCase ={} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __UpperCamelCase ={} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __UpperCamelCase ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __UpperCamelCase =InstructBlipVisionConfig(**A_ ) __UpperCamelCase =InstructBlipQFormerConfig(**A_ ) __UpperCamelCase =text_config['model_type'] if 'model_type' in text_config else 'opt' __UpperCamelCase =CONFIG_MAPPING[text_model_type](**A_ ) __UpperCamelCase =self.text_config.tie_word_embeddings __UpperCamelCase =self.text_config.is_encoder_decoder __UpperCamelCase =num_query_tokens __UpperCamelCase =self.vision_config.hidden_size __UpperCamelCase =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __UpperCamelCase =1.0 __UpperCamelCase =0.02 @classmethod def _a ( cls , A_ , A_ , A_ , **A_ , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =copy.deepcopy(self.__dict__ ) __UpperCamelCase =self.vision_config.to_dict() __UpperCamelCase =self.qformer_config.to_dict() __UpperCamelCase =self.text_config.to_dict() __UpperCamelCase =self.__class__.model_type return output
62
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _A = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self , A_ , A_=7 , A_=3 , A_=30 , A_=400 , A_=True , A_=None , A_=True , A_=[0.5, 0.5, 0.5] , A_=[0.5, 0.5, 0.5] , A_=True , A_=1 / 255 , A_=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __UpperCamelCase =size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =num_channels __UpperCamelCase =min_resolution __UpperCamelCase =max_resolution __UpperCamelCase =do_resize __UpperCamelCase =size __UpperCamelCase =do_normalize __UpperCamelCase =image_mean __UpperCamelCase =image_std __UpperCamelCase =do_rescale __UpperCamelCase =rescale_factor __UpperCamelCase =do_pad def _a ( self ) -> Any: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _a ( self , A_ , A_=False ) -> Optional[int]: if not batched: __UpperCamelCase =image_inputs[0] if isinstance(A_ , Image.Image ): __UpperCamelCase , __UpperCamelCase =image.size else: __UpperCamelCase , __UpperCamelCase =image.shape[1], image.shape[2] if w < h: __UpperCamelCase =int(self.size['shortest_edge'] * h / w ) __UpperCamelCase =self.size['shortest_edge'] elif w > h: __UpperCamelCase =self.size['shortest_edge'] __UpperCamelCase =int(self.size['shortest_edge'] * w / h ) else: __UpperCamelCase =self.size['shortest_edge'] __UpperCamelCase =self.size['shortest_edge'] else: __UpperCamelCase =[] for image in image_inputs: __UpperCamelCase , __UpperCamelCase =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __UpperCamelCase =max(A_ , key=lambda A_ : item[0] )[0] __UpperCamelCase =max(A_ , key=lambda A_ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : int = DeformableDetrImageProcessor if is_vision_available() else None def _a ( self ) -> str: __UpperCamelCase =DeformableDetrImageProcessingTester(self ) @property def _a ( self ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def _a ( self ) -> int: __UpperCamelCase =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A_ , 'image_mean' ) ) self.assertTrue(hasattr(A_ , 'image_std' ) ) self.assertTrue(hasattr(A_ , 'do_normalize' ) ) self.assertTrue(hasattr(A_ , 'do_resize' ) ) self.assertTrue(hasattr(A_ , 'do_rescale' ) ) self.assertTrue(hasattr(A_ , 'do_pad' ) ) self.assertTrue(hasattr(A_ , 'size' ) ) def _a ( self ) -> str: __UpperCamelCase =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , A_ ) __UpperCamelCase =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A_ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , A_ ) def _a ( self ) -> Optional[int]: pass def _a ( self ) -> Tuple: # 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=A_ ) for image in image_inputs: self.assertIsInstance(A_ , Image.Image ) # Test not batched input __UpperCamelCase =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ , batched=A_ ) __UpperCamelCase =image_processing(A_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ) -> Dict: # 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=A_ , numpify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , np.ndarray ) # Test not batched input __UpperCamelCase =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase =image_processing(A_ , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ , batched=A_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _a ( self ) -> List[Any]: # 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=A_ , torchify=A_ ) for image in image_inputs: self.assertIsInstance(A_ , torch.Tensor ) # Test not batched input __UpperCamelCase =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase =image_processing(A_ , return_tensors='pt' ).pixel_values __UpperCamelCase , __UpperCamelCase =self.image_processor_tester.get_expected_values(A_ , batched=A_ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _a ( self ) -> Optional[Any]: # prepare image and target __UpperCamelCase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __UpperCamelCase =json.loads(f.read() ) __UpperCamelCase ={'image_id': 39769, 'annotations': target} # encode them __UpperCamelCase =DeformableDetrImageProcessor() __UpperCamelCase =image_processing(images=A_ , annotations=A_ , return_tensors='pt' ) # verify pixel values __UpperCamelCase =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , A_ ) __UpperCamelCase =torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , A_ , atol=1E-4 ) ) # verify area __UpperCamelCase =torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , A_ ) ) # verify boxes __UpperCamelCase =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , A_ ) __UpperCamelCase =torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , A_ , atol=1E-3 ) ) # verify image_id __UpperCamelCase =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , A_ ) ) # verify is_crowd __UpperCamelCase =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , A_ ) ) # verify class_labels __UpperCamelCase =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , A_ ) ) # verify orig_size __UpperCamelCase =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , A_ ) ) # verify size __UpperCamelCase =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , A_ ) ) @slow def _a ( self ) -> List[Any]: # prepare image, target and masks_path __UpperCamelCase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __UpperCamelCase =json.loads(f.read() ) __UpperCamelCase ={'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __UpperCamelCase =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __UpperCamelCase =DeformableDetrImageProcessor(format='coco_panoptic' ) __UpperCamelCase =image_processing(images=A_ , annotations=A_ , masks_path=A_ , return_tensors='pt' ) # verify pixel values __UpperCamelCase =torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , A_ ) __UpperCamelCase =torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , A_ , atol=1E-4 ) ) # verify area __UpperCamelCase =torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , A_ ) ) # verify boxes __UpperCamelCase =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , A_ ) __UpperCamelCase =torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , A_ , atol=1E-3 ) ) # verify image_id __UpperCamelCase =torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , A_ ) ) # verify is_crowd __UpperCamelCase =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , A_ ) ) # verify class_labels __UpperCamelCase =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , A_ ) ) # verify masks __UpperCamelCase =822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , A_ ) # verify orig_size __UpperCamelCase =torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , A_ ) ) # verify size __UpperCamelCase =torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , A_ ) )
62
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = TransfoXLTokenizer UpperCAmelCase__ : str = False UpperCAmelCase__ : Tuple = False def _a ( self ) -> Union[str, Any]: super().setUp() __UpperCamelCase =[ '<unk>', '[CLS]', '[SEP]', 'want', 'unwanted', 'wa', 'un', 'running', ',', 'low', 'l', ] __UpperCamelCase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def _a ( self , **A_ ) -> Optional[int]: __UpperCamelCase =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **A_ ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase ='<unk> UNwanted , running' __UpperCamelCase ='<unk> unwanted, running' return input_text, output_text def _a ( self ) -> str: __UpperCamelCase =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=A_ ) __UpperCamelCase =tokenizer.tokenize('<unk> UNwanted , running' ) self.assertListEqual(A_ , ['<unk>', 'unwanted', ',', 'running'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A_ ) , [0, 4, 8, 7] ) def _a ( self ) -> Any: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) def _a ( self ) -> Optional[int]: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo ! how \n Are yoU ? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _a ( self ) -> int: __UpperCamelCase =TransfoXLTokenizer(lower_case=A_ ) __UpperCamelCase ='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?' __UpperCamelCase =[ 'Hello', '(', 'bracket', ')', 'and', 'side', '@-@', 'scrolled', '[', 'and', ']', 'Henry', '\'s', '$', '5', '@,@', '000', 'with', '3', '@.@', '34', 'm', '.', 'What', '\'s', 'up', '!', '?', ] self.assertListEqual(tokenizer.tokenize(A_ ) , A_ ) self.assertEqual(tokenizer.convert_tokens_to_string(A_ ) , A_ ) def _a ( self ) -> Optional[int]: __UpperCamelCase =self.get_tokenizer() __UpperCamelCase =len(A_ ) tokenizer.add_tokens(['new1', 'new2'] ) tokenizer.move_added_token('new1' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(A_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('new1' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , 'new1' )
62
1
import argparse import os import re _A = 'src/transformers/models/auto' # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict _A = re.compile(R'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict') # re pattern that matches identifiers in mappings _A = re.compile(R'\s*\(\s*"(\S[^"]+)"') def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : bool = False ): with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as f: __UpperCamelCase =f.read() __UpperCamelCase =content.split('\n' ) __UpperCamelCase =[] __UpperCamelCase =0 while line_idx < len(SCREAMING_SNAKE_CASE__ ): if _re_intro_mapping.search(lines[line_idx] ) is not None: __UpperCamelCase =len(re.search(r'^(\s*)\S' , lines[line_idx] ).groups()[0] ) + 8 # Start of a new mapping! while not lines[line_idx].startswith(' ' * indent + '(' ): new_lines.append(lines[line_idx] ) line_idx += 1 __UpperCamelCase =[] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": __UpperCamelCase =line_idx while not lines[line_idx].startswith(' ' * indent + ')' ): line_idx += 1 blocks.append('\n'.join(lines[start_idx : line_idx + 1] ) ) else: blocks.append(lines[line_idx] ) line_idx += 1 # Sort blocks by their identifiers __UpperCamelCase =sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : _re_identifier.search(SCREAMING_SNAKE_CASE__ ).groups()[0] ) new_lines += blocks else: new_lines.append(lines[line_idx] ) line_idx += 1 if overwrite: with open(SCREAMING_SNAKE_CASE__ , 'w' , encoding='utf-8' ) as f: f.write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) elif "\n".join(SCREAMING_SNAKE_CASE__ ) != content: return True def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : bool = False ): __UpperCamelCase =[os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for f in os.listdir(SCREAMING_SNAKE_CASE__ ) if f.endswith('.py' )] __UpperCamelCase =[sort_auto_mapping(SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) for fname in fnames] if not overwrite and any(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[f for f, d in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if d] raise ValueError( F'The following files have auto mappings that need sorting: {", ".join(SCREAMING_SNAKE_CASE__ )}. Run `make style` to fix' ' this.' ) if __name__ == "__main__": _A = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') _A = parser.parse_args() sort_all_auto_mappings(not args.check_only)
62
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _A = { 'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'], 'tokenization_convbert': ['ConvBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ConvBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConvBertForMaskedLM', 'ConvBertForMultipleChoice', 'ConvBertForQuestionAnswering', 'ConvBertForSequenceClassification', 'ConvBertForTokenClassification', 'ConvBertLayer', 'ConvBertModel', 'ConvBertPreTrainedModel', 'load_tf_weights_in_convbert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFConvBertForMaskedLM', 'TFConvBertForMultipleChoice', 'TFConvBertForQuestionAnswering', 'TFConvBertForSequenceClassification', 'TFConvBertForTokenClassification', 'TFConvBertLayer', 'TFConvBertModel', 'TFConvBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
62
1
import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_=13 , A_=32 , A_=3 , A_=4 , A_=[10, 20, 30, 40] , A_=[2, 2, 3, 2] , A_=True , A_=True , A_=37 , A_="gelu" , A_=10 , A_=0.02 , A_=["stage2", "stage3", "stage4"] , A_=[2, 3, 4] , A_=None , ) -> Union[str, Any]: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =image_size __UpperCamelCase =num_channels __UpperCamelCase =num_stages __UpperCamelCase =hidden_sizes __UpperCamelCase =depths __UpperCamelCase =is_training __UpperCamelCase =use_labels __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =num_labels __UpperCamelCase =initializer_range __UpperCamelCase =out_features __UpperCamelCase =out_indices __UpperCamelCase =scope def _a ( self ) -> int: __UpperCamelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.num_labels ) __UpperCamelCase =self.get_config() return config, pixel_values, labels def _a ( self ) -> Optional[int]: return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=A_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def _a ( self , A_ , A_ , A_ ) -> List[Any]: __UpperCamelCase =ConvNextModel(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _a ( self , A_ , A_ , A_ ) -> Optional[Any]: __UpperCamelCase =ConvNextForImageClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _a ( self , A_ , A_ , A_ ) -> Tuple: __UpperCamelCase =ConvNextBackbone(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __UpperCamelCase =None __UpperCamelCase =ConvNextBackbone(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _a ( self ) -> str: __UpperCamelCase =self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =config_and_inputs __UpperCamelCase ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase__ ( A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) UpperCAmelCase__ : Dict = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) UpperCAmelCase__ : Dict = True UpperCAmelCase__ : Tuple = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : List[Any] = False UpperCAmelCase__ : str = False def _a ( self ) -> Tuple: __UpperCamelCase =ConvNextModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def _a ( self ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ) -> str: return @unittest.skip(reason='ConvNext does not use inputs_embeds' ) def _a ( self ) -> Optional[int]: pass @unittest.skip(reason='ConvNext does not support input and output embeddings' ) def _a ( self ) -> Optional[Any]: pass @unittest.skip(reason='ConvNext does not use feedforward chunking' ) def _a ( self ) -> List[Any]: pass def _a ( self ) -> Union[str, Any]: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase =model_class(A_ ) __UpperCamelCase =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase =[*signature.parameters.keys()] __UpperCamelCase =['pixel_values'] self.assertListEqual(arg_names[:1] , A_ ) def _a ( self ) -> List[str]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*A_ ) def _a ( self ) -> Optional[Any]: def check_hidden_states_output(A_ , A_ , A_ ): __UpperCamelCase =model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): __UpperCamelCase =model(**self._prepare_for_class(A_ , A_ ) ) __UpperCamelCase =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCamelCase =self.model_tester.num_stages self.assertEqual(len(A_ ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase =True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCamelCase =True check_hidden_states_output(A_ , A_ , A_ ) def _a ( self ) -> int: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A_ ) @slow def _a ( self ) -> Optional[Any]: for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase =ConvNextModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def _UpperCAmelCase ( ): __UpperCamelCase =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self ) -> Optional[int]: return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224' ) if is_vision_available() else None @slow def _a ( self ) -> int: __UpperCamelCase =ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224' ).to(A_ ) __UpperCamelCase =self.default_image_processor __UpperCamelCase =prepare_img() __UpperCamelCase =image_processor(images=A_ , return_tensors='pt' ).to(A_ ) # forward pass with torch.no_grad(): __UpperCamelCase =model(**A_ ) # verify the logits __UpperCamelCase =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , A_ ) __UpperCamelCase =torch.tensor([-0.0260, -0.4739, 0.1911] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1E-4 ) ) @require_torch class UpperCAmelCase__ ( unittest.TestCase , A_ ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = (ConvNextBackbone,) if is_torch_available() else () UpperCAmelCase__ : Optional[Any] = ConvNextConfig UpperCAmelCase__ : Any = False def _a ( self ) -> Dict: __UpperCamelCase =ConvNextModelTester(self )
62
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _A = logging.getLogger(__name__) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return np.sum(outputs == labels ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[Any] ): with open(SCREAMING_SNAKE_CASE__ , encoding='utf_8' ) as f: __UpperCamelCase =csv.reader(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[] next(SCREAMING_SNAKE_CASE__ ) # skip the first line for line in tqdm(SCREAMING_SNAKE_CASE__ ): output.append((' '.join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): __UpperCamelCase =[] for dataset in encoded_datasets: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch, 2) , dtype=np.intaa ) __UpperCamelCase =np.full((n_batch, 2, input_len) , fill_value=-1_00 , dtype=np.intaa ) __UpperCamelCase =np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) - 1 __UpperCamelCase =with_conta __UpperCamelCase =with_conta __UpperCamelCase =mc_label __UpperCamelCase =(input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE__ ) for t in all_inputs ) ) return tensor_datasets def _UpperCAmelCase ( ): __UpperCamelCase =argparse.ArgumentParser() parser.add_argument('--model_name' , type=SCREAMING_SNAKE_CASE__ , default='openai-gpt' , help='pretrained model name' ) parser.add_argument('--do_train' , action='store_true' , help='Whether to run training.' ) parser.add_argument('--do_eval' , action='store_true' , help='Whether to run eval on the dev set.' ) parser.add_argument( '--output_dir' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='The output directory where the model predictions and checkpoints will be written.' , ) parser.add_argument('--train_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--eval_dataset' , type=SCREAMING_SNAKE_CASE__ , default='' ) parser.add_argument('--seed' , type=SCREAMING_SNAKE_CASE__ , default=42 ) parser.add_argument('--num_train_epochs' , type=SCREAMING_SNAKE_CASE__ , default=3 ) parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=8 ) parser.add_argument('--eval_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=16 ) parser.add_argument('--adam_epsilon' , default=1E-8 , type=SCREAMING_SNAKE_CASE__ , help='Epsilon for Adam optimizer.' ) parser.add_argument('--max_grad_norm' , type=SCREAMING_SNAKE_CASE__ , default=1 ) parser.add_argument( '--max_steps' , default=-1 , type=SCREAMING_SNAKE_CASE__ , help=( 'If > 0: set total number of training steps to perform. Override num_train_epochs.' ) , ) parser.add_argument( '--gradient_accumulation_steps' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Number of updates steps to accumulate before performing a backward/update pass.' , ) parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=6.25E-5 ) parser.add_argument('--warmup_steps' , default=0 , type=SCREAMING_SNAKE_CASE__ , help='Linear warmup over warmup_steps.' ) parser.add_argument('--lr_schedule' , type=SCREAMING_SNAKE_CASE__ , default='warmup_linear' ) parser.add_argument('--weight_decay' , type=SCREAMING_SNAKE_CASE__ , default=0.01 ) parser.add_argument('--lm_coef' , type=SCREAMING_SNAKE_CASE__ , default=0.9 ) parser.add_argument('--n_valid' , type=SCREAMING_SNAKE_CASE__ , default=3_74 ) parser.add_argument('--server_ip' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=SCREAMING_SNAKE_CASE__ , default='' , help='Can be used for distant debugging.' ) __UpperCamelCase =parser.parse_args() print(SCREAMING_SNAKE_CASE__ ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=SCREAMING_SNAKE_CASE__ ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __UpperCamelCase =torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __UpperCamelCase =torch.cuda.device_count() logger.info('device: {}, n_gpu {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if not args.do_train and not args.do_eval: raise ValueError('At least one of `do_train` or `do_eval` must be True.' ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __UpperCamelCase =['_start_', '_delimiter_', '_classify_'] __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE__ ) ) model.to(SCREAMING_SNAKE_CASE__ ) # Load and encode the datasets def tokenize_and_encode(SCREAMING_SNAKE_CASE__ : str ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return obj return [tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) for o in obj] logger.info('Encoding dataset...' ) __UpperCamelCase =load_rocstories_dataset(args.train_dataset ) __UpperCamelCase =load_rocstories_dataset(args.eval_dataset ) __UpperCamelCase =(train_dataset, eval_dataset) __UpperCamelCase =tokenize_and_encode(SCREAMING_SNAKE_CASE__ ) # Compute the max input length for the Transformer __UpperCamelCase =model.config.n_positions // 2 - 2 __UpperCamelCase =max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __UpperCamelCase =min(SCREAMING_SNAKE_CASE__ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __UpperCamelCase =pre_process_datasets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =tensor_datasets[0], tensor_datasets[1] __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =RandomSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.train_batch_size ) __UpperCamelCase =TensorDataset(*SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =SequentialSampler(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =DataLoader(SCREAMING_SNAKE_CASE__ , sampler=SCREAMING_SNAKE_CASE__ , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __UpperCamelCase =args.max_steps __UpperCamelCase =args.max_steps // (len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps) + 1 else: __UpperCamelCase =len(SCREAMING_SNAKE_CASE__ ) // args.gradient_accumulation_steps * args.num_train_epochs __UpperCamelCase =list(model.named_parameters() ) __UpperCamelCase =['bias', 'LayerNorm.bias', 'LayerNorm.weight'] __UpperCamelCase =[ { 'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], 'weight_decay': args.weight_decay, }, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], 'weight_decay': 0.0}, ] __UpperCamelCase =AdamW(SCREAMING_SNAKE_CASE__ , lr=args.learning_rate , eps=args.adam_epsilon ) __UpperCamelCase =get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE__ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE__ ) if args.do_train: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc='Epoch' ): __UpperCamelCase =0 __UpperCamelCase =0 __UpperCamelCase =tqdm(SCREAMING_SNAKE_CASE__ , desc='Training' ) for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch __UpperCamelCase =model(SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __UpperCamelCase =( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __UpperCamelCase ='Training loss: {:.2e} lr: {:.2e}'.format(SCREAMING_SNAKE_CASE__ , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __UpperCamelCase =model.module if hasattr(SCREAMING_SNAKE_CASE__ , 'module' ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(args.output_dir , SCREAMING_SNAKE_CASE__ ) torch.save(model_to_save.state_dict() , SCREAMING_SNAKE_CASE__ ) model_to_save.config.to_json_file(SCREAMING_SNAKE_CASE__ ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __UpperCamelCase =OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __UpperCamelCase =OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE__ ) if args.do_eval: model.eval() __UpperCamelCase , __UpperCamelCase =0, 0 __UpperCamelCase , __UpperCamelCase =0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE__ , desc='Evaluating' ): __UpperCamelCase =tuple(t.to(SCREAMING_SNAKE_CASE__ ) for t in batch ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =batch with torch.no_grad(): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase =model( SCREAMING_SNAKE_CASE__ , mc_token_ids=SCREAMING_SNAKE_CASE__ , lm_labels=SCREAMING_SNAKE_CASE__ , mc_labels=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =mc_logits.detach().cpu().numpy() __UpperCamelCase =mc_labels.to('cpu' ).numpy() __UpperCamelCase =accuracy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __UpperCamelCase =eval_loss / nb_eval_steps __UpperCamelCase =eval_accuracy / nb_eval_examples __UpperCamelCase =tr_loss / nb_tr_steps if args.do_train else None __UpperCamelCase ={'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss} __UpperCamelCase =os.path.join(args.output_dir , 'eval_results.txt' ) with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: logger.info('***** Eval results *****' ) for key in sorted(result.keys() ): logger.info(' %s = %s' , SCREAMING_SNAKE_CASE__ , str(result[key] ) ) writer.write('%s = %s\n' % (key, str(result[key] )) ) if __name__ == "__main__": main()
62
1