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 argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse("1.0.0a"): raise Exception("requires fairseq >= 1.0.0a") logging.set_verbosity_info() lowercase__ :int = logging.get_logger(__name__) lowercase__ :Union[str, Any] = "Hello world! cécé herlolip" def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = FairseqRobertaModel.from_pretrained(lowerCAmelCase__ ) roberta.eval() # disable dropout lowercase = roberta.model.encoder.sentence_encoder lowercase = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: lowercase = roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our RoBERTa config:''' , lowerCAmelCase__ ) lowercase = XLMRobertaXLForSequenceClassification(lowerCAmelCase__ ) if classification_head else XLMRobertaXLForMaskedLM(lowerCAmelCase__ ) model.eval() # Now let's copy all the weights. # Embeddings lowercase = roberta_sent_encoder.embed_tokens.weight lowercase = roberta_sent_encoder.embed_positions.weight lowercase = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. lowercase = roberta_sent_encoder.layer_norm.weight lowercase = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowercase = model.roberta.encoder.layer[i] lowercase = roberta_sent_encoder.layers[i] lowercase = layer.attention lowercase = roberta_layer.self_attn_layer_norm.weight lowercase = roberta_layer.self_attn_layer_norm.bias # self attention lowercase = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) lowercase = roberta_layer.self_attn.q_proj.weight lowercase = roberta_layer.self_attn.q_proj.bias lowercase = roberta_layer.self_attn.k_proj.weight lowercase = roberta_layer.self_attn.k_proj.bias lowercase = roberta_layer.self_attn.v_proj.weight lowercase = roberta_layer.self_attn.v_proj.bias # self-attention output lowercase = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape lowercase = roberta_layer.self_attn.out_proj.weight lowercase = roberta_layer.self_attn.out_proj.bias # this one is final layer norm lowercase = roberta_layer.final_layer_norm.weight lowercase = roberta_layer.final_layer_norm.bias # intermediate lowercase = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape lowercase = roberta_layer.fca.weight lowercase = roberta_layer.fca.bias # output lowercase = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape lowercase = roberta_layer.fca.weight lowercase = roberta_layer.fca.bias # end of layer if classification_head: lowercase = roberta.model.classification_heads['''mnli'''].dense.weight lowercase = roberta.model.classification_heads['''mnli'''].dense.bias lowercase = roberta.model.classification_heads['''mnli'''].out_proj.weight lowercase = roberta.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head lowercase = roberta.model.encoder.lm_head.dense.weight lowercase = roberta.model.encoder.lm_head.dense.bias lowercase = roberta.model.encoder.lm_head.layer_norm.weight lowercase = roberta.model.encoder.lm_head.layer_norm.bias lowercase = roberta.model.encoder.lm_head.weight lowercase = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. lowercase = roberta.encode(lowerCAmelCase__ ).unsqueeze(0 ) # batch of size 1 lowercase = model(lowerCAmelCase__ )[0] if classification_head: lowercase = roberta.model.classification_heads['''mnli'''](roberta.extract_features(lowerCAmelCase__ ) ) else: lowercase = roberta.model(lowerCAmelCase__ )[0] print(our_output.shape , their_output.shape ) lowercase = torch.max(torch.abs(our_output - their_output ) ).item() print(f'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 lowercase = torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) pathlib.Path(lowerCAmelCase__ ).mkdir(parents=lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": lowercase__ :Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--roberta_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--classification_head", action="store_true", help="Whether to convert a final classification head." ) lowercase__ :Optional[int] = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
101
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
92
0
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ , a_ , a_=0.0 , a_ = None , a_ = "geglu" , a_ = None , a_ = False , a_ = False , a_ = False , a_ = False , a_ = True , a_ = "layer_norm" , a_ = False , ): '''simple docstring''' super().__init__() __snake_case : List[Any] = only_cross_attention __snake_case : Union[str, Any] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero''' __snake_case : Any = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm''' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" f""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: __snake_case : Dict = AdaLayerNorm(a_ , a_ ) elif self.use_ada_layer_norm_zero: __snake_case : int = AdaLayerNormZero(a_ , a_ ) else: __snake_case : Optional[Any] = nn.LayerNorm(a_ , elementwise_affine=a_ ) __snake_case : Any = Attention( query_dim=a_ , heads=a_ , dim_head=a_ , dropout=a_ , bias=a_ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=a_ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. __snake_case : Dict = ( AdaLayerNorm(a_ , a_ ) if self.use_ada_layer_norm else nn.LayerNorm(a_ , elementwise_affine=a_ ) ) __snake_case : List[Any] = Attention( query_dim=a_ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=a_ , dim_head=a_ , dropout=a_ , bias=a_ , upcast_attention=a_ , ) # is self-attn if encoder_hidden_states is none else: __snake_case : int = None __snake_case : Union[str, Any] = None # 3. Feed-forward __snake_case : Optional[int] = nn.LayerNorm(a_ , elementwise_affine=a_ ) __snake_case : Optional[Any] = FeedForward(a_ , dropout=a_ , activation_fn=a_ , final_dropout=a_ ) # let chunk size default to None __snake_case : Tuple = None __snake_case : int = 0 def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : int = chunk_size __snake_case : Optional[Any] = dim def SCREAMING_SNAKE_CASE (self , a_ , a_ = None , a_ = None , a_ = None , a_ = None , a_ = None , a_ = None , ): '''simple docstring''' if self.use_ada_layer_norm: __snake_case : Tuple = self.norma(a_ , a_ ) elif self.use_ada_layer_norm_zero: __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = self.norma( a_ , a_ , a_ , hidden_dtype=hidden_states.dtype ) else: __snake_case : Optional[Any] = self.norma(a_ ) __snake_case : Optional[Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} __snake_case : List[Any] = self.attna( a_ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=a_ , **a_ , ) if self.use_ada_layer_norm_zero: __snake_case : Optional[Any] = gate_msa.unsqueeze(1 ) * attn_output __snake_case : List[str] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: __snake_case : List[Any] = ( self.norma(a_ , a_ ) if self.use_ada_layer_norm else self.norma(a_ ) ) __snake_case : str = self.attna( a_ , encoder_hidden_states=a_ , attention_mask=a_ , **a_ , ) __snake_case : Union[str, Any] = attn_output + hidden_states # 3. Feed-forward __snake_case : Any = self.norma(a_ ) if self.use_ada_layer_norm_zero: __snake_case : Optional[Any] = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) __snake_case : List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size __snake_case : Dict = torch.cat( [self.ff(a_ ) for hid_slice in norm_hidden_states.chunk(a_ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: __snake_case : Tuple = self.ff(a_ ) if self.use_ada_layer_norm_zero: __snake_case : Any = gate_mlp.unsqueeze(1 ) * ff_output __snake_case : int = ff_output + hidden_states return hidden_states class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ = None , a_ = 4 , a_ = 0.0 , a_ = "geglu" , a_ = False , ): '''simple docstring''' super().__init__() __snake_case : Union[str, Any] = int(dim * mult ) __snake_case : List[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": __snake_case : Optional[int] = GELU(a_ , a_ ) if activation_fn == "gelu-approximate": __snake_case : Union[str, Any] = GELU(a_ , a_ , approximate='''tanh''' ) elif activation_fn == "geglu": __snake_case : Optional[int] = GEGLU(a_ , a_ ) elif activation_fn == "geglu-approximate": __snake_case : List[Any] = ApproximateGELU(a_ , a_ ) __snake_case : List[str] = nn.ModuleList([] ) # project in self.net.append(a_ ) # project dropout self.net.append(nn.Dropout(a_ ) ) # project out self.net.append(nn.Linear(a_ , a_ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(a_ ) ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' for module in self.net: __snake_case : List[Any] = module(a_ ) return hidden_states class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ , a_ = "none" ): '''simple docstring''' super().__init__() __snake_case : Optional[int] = nn.Linear(a_ , a_ ) __snake_case : Optional[Any] = approximate def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(a_ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : Any = self.proj(a_ ) __snake_case : List[str] = self.gelu(a_ ) return hidden_states class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ ): '''simple docstring''' super().__init__() __snake_case : Union[str, Any] = nn.Linear(a_ , dim_out * 2 ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' if gate.device.type != "mps": return F.gelu(a_ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case , __snake_case : Tuple = self.proj(a_ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(a_ ) class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ ): '''simple docstring''' super().__init__() __snake_case : Dict = nn.Linear(a_ , a_ ) def SCREAMING_SNAKE_CASE (self , a_ ): '''simple docstring''' __snake_case : Tuple = self.proj(a_ ) return x * torch.sigmoid(1.702 * x ) class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ ): '''simple docstring''' super().__init__() __snake_case : Union[str, Any] = nn.Embedding(a_ , a_ ) __snake_case : Any = nn.SiLU() __snake_case : str = nn.Linear(a_ , embedding_dim * 2 ) __snake_case : Dict = nn.LayerNorm(a_ , elementwise_affine=a_ ) def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' __snake_case : Union[str, Any] = self.linear(self.silu(self.emb(a_ ) ) ) __snake_case , __snake_case : int = torch.chunk(a_ , 2 ) __snake_case : Optional[int] = self.norm(a_ ) * (1 + scale) + shift return x class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ ): '''simple docstring''' super().__init__() __snake_case : Optional[int] = CombinedTimestepLabelEmbeddings(a_ , a_ ) __snake_case : Optional[int] = nn.SiLU() __snake_case : List[str] = nn.Linear(a_ , 6 * embedding_dim , bias=a_ ) __snake_case : str = nn.LayerNorm(a_ , elementwise_affine=a_ , eps=1E-6 ) def SCREAMING_SNAKE_CASE (self , a_ , a_ , a_ , a_=None ): '''simple docstring''' __snake_case : Any = self.linear(self.silu(self.emb(a_ , a_ , hidden_dtype=a_ ) ) ) __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : str = emb.chunk(6 , dim=1 ) __snake_case : Any = self.norm(a_ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class _UpperCAmelCase ( nn.Module ): '''simple docstring''' def __init__(self , a_ , a_ , a_ , a_ = None , a_ = 1E-5 ): '''simple docstring''' super().__init__() __snake_case : Optional[Any] = num_groups __snake_case : Any = eps if act_fn is None: __snake_case : Optional[Any] = None else: __snake_case : Tuple = get_activation(a_ ) __snake_case : List[str] = nn.Linear(a_ , out_dim * 2 ) def SCREAMING_SNAKE_CASE (self , a_ , a_ ): '''simple docstring''' if self.act: __snake_case : Dict = self.act(a_ ) __snake_case : List[str] = self.linear(a_ ) __snake_case : Tuple = emb[:, :, None, None] __snake_case , __snake_case : Optional[int] = emb.chunk(2 , dim=1 ) __snake_case : Union[str, Any] = F.group_norm(a_ , self.num_groups , eps=self.eps ) __snake_case : int = x * (1 + scale) + shift return x
102
from queue import PriorityQueue from typing import Any import numpy as np def _a ( 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 __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = 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(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = 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_ , ) __lowerCAmelCase = 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: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """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()
92
0
from bisect import bisect from itertools import accumulate def UpperCamelCase( __UpperCamelCase : Optional[int] ,__UpperCamelCase : Optional[Any] ,__UpperCamelCase : Dict ,__UpperCamelCase : str ): lowerCAmelCase_ : Union[str, Any] = sorted(zip(__UpperCamelCase ,__UpperCamelCase ) ,key=lambda __UpperCamelCase : x[0] / x[1] ,reverse=__UpperCamelCase ) lowerCAmelCase_ , lowerCAmelCase_ : Any = [i[0] for i in r], [i[1] for i in r] lowerCAmelCase_ : Union[str, Any] = list(accumulate(__UpperCamelCase ) ) lowerCAmelCase_ : List[Any] = bisect(__UpperCamelCase ,__UpperCamelCase ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
103
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a__ ( snake_case__ ): _a : Optional[int] = """decision_transformer""" _a : Optional[int] = ["""past_key_values"""] _a : Dict = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _A=1_7 , _A=4 , _A=1_2_8 , _A=4_0_9_6 , _A=True , _A=1 , _A=1_0_2_4 , _A=3 , _A=1 , _A=None , _A="relu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1E-5 , _A=0.02 , _A=True , _A=True , _A=5_0_2_5_6 , _A=5_0_2_5_6 , _A=False , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = state_dim __lowerCAmelCase = act_dim __lowerCAmelCase = hidden_size __lowerCAmelCase = max_ep_len __lowerCAmelCase = action_tanh __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = bos_token_id __lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
92
0
'''simple docstring''' import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all LED models at https://huggingface.co/models?filter=LED lowerCAmelCase__ = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } lowerCAmelCase__ = { '''allenai/led-base-16384''': 1_6384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def _A ( ): """simple docstring""" __lowercase = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __lowercase = bs[:] __lowercase = 0 for b in range(2**8 ): if b not in bs: bs.append(A__ ) cs.append(2**8 + n ) n += 1 __lowercase = [chr(A__ ) for n in cs] return dict(zip(A__ , A__ ) ) def _A ( A__ ): """simple docstring""" __lowercase = set() __lowercase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowercase = char return pairs class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE : Optional[int] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self : Dict ,lowercase__ : Tuple ,lowercase__ : Dict ,lowercase__ : Union[str, Any]="replace" ,lowercase__ : Any="<s>" ,lowercase__ : Dict="</s>" ,lowercase__ : Union[str, Any]="</s>" ,lowercase__ : Dict="<s>" ,lowercase__ : Dict="<unk>" ,lowercase__ : Union[str, Any]="<pad>" ,lowercase__ : Tuple="<mask>" ,lowercase__ : List[str]=False ,**lowercase__ : List[Any] ,): __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else bos_token __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else eos_token __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else sep_token __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else cls_token __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else unk_token __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __lowercase = AddedToken(lowercase__ ,lstrip=lowercase__ ,rstrip=lowercase__ ) if isinstance(lowercase__ ,lowercase__ ) else mask_token super().__init__( errors=lowercase__ ,bos_token=lowercase__ ,eos_token=lowercase__ ,unk_token=lowercase__ ,sep_token=lowercase__ ,cls_token=lowercase__ ,pad_token=lowercase__ ,mask_token=lowercase__ ,add_prefix_space=lowercase__ ,**lowercase__ ,) with open(lowercase__ ,encoding='''utf-8''' ) as vocab_handle: __lowercase = json.load(lowercase__ ) __lowercase = {v: k for k, v in self.encoder.items()} __lowercase = errors # how to handle errors in decoding __lowercase = bytes_to_unicode() __lowercase = {v: k for k, v in self.byte_encoder.items()} with open(lowercase__ ,encoding='''utf-8''' ) as merges_handle: __lowercase = merges_handle.read().split('''\n''' )[1:-1] __lowercase = [tuple(merge.split() ) for merge in bpe_merges] __lowercase = dict(zip(lowercase__ ,range(len(lowercase__ ) ) ) ) __lowercase = {} __lowercase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __lowercase = 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.bart.tokenization_bart.BartTokenizer.vocab_size def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): return len(self.encoder ) def SCREAMING_SNAKE_CASE ( self : List[str] ): return dict(self.encoder ,**self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : Optional[Any] ): if token in self.cache: return self.cache[token] __lowercase = tuple(lowercase__ ) __lowercase = get_pairs(lowercase__ ) if not pairs: return token while True: __lowercase = min(lowercase__ ,key=lambda lowercase__ : self.bpe_ranks.get(lowercase__ ,float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __lowercase , __lowercase = bigram __lowercase = [] __lowercase = 0 while i < len(lowercase__ ): try: __lowercase = word.index(lowercase__ ,lowercase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowercase = j if word[i] == first and i < len(lowercase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowercase = tuple(lowercase__ ) __lowercase = new_word if len(lowercase__ ) == 1: break else: __lowercase = get_pairs(lowercase__ ) __lowercase = ''' '''.join(lowercase__ ) __lowercase = word return word def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : List[Any] ): __lowercase = [] for token in re.findall(self.pat ,lowercase__ ): __lowercase = ''''''.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(lowercase__ ).split(''' ''' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE ( self : str ,lowercase__ : Tuple ): return self.encoder.get(lowercase__ ,self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : Any ): return self.decoder.get(lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : Optional[Any] ): __lowercase = ''''''.join(lowercase__ ) __lowercase = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' ,errors=self.errors ) return text def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : str ,lowercase__ : Optional[str] = None ): if not os.path.isdir(lowercase__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __lowercase = os.path.join( lowercase__ ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __lowercase = os.path.join( lowercase__ ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(lowercase__ ,'''w''' ,encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=lowercase__ ,ensure_ascii=lowercase__ ) + '''\n''' ) __lowercase = 0 with open(lowercase__ ,'''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 lowercase__ : 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!''' ) __lowercase = token_index writer.write(''' '''.join(lowercase__ ) + '''\n''' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : List[int] ,lowercase__ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowercase = [self.cls_token_id] __lowercase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : List[int] ,lowercase__ : Optional[List[int]] = None ,lowercase__ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase__ ,token_ids_a=lowercase__ ,already_has_special_tokens=lowercase__ ) if token_ids_a is None: return [1] + ([0] * len(lowercase__ )) + [1] return [1] + ([0] * len(lowercase__ )) + [1, 1] + ([0] * len(lowercase__ )) + [1] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,lowercase__ : List[int] ,lowercase__ : Optional[List[int]] = None ): __lowercase = [self.sep_token_id] __lowercase = [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 SCREAMING_SNAKE_CASE ( self : int ,lowercase__ : Optional[int] ,lowercase__ : Optional[Any]=False ,**lowercase__ : Optional[int] ): __lowercase = kwargs.pop('''add_prefix_space''' ,self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(lowercase__ ) > 0 and not text[0].isspace()): __lowercase = ''' ''' + text return (text, kwargs) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Union[Dict[str, EncodedInput], BatchEncoding] ,lowercase__ : Optional[int] = None ,lowercase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[bool] = None ,): __lowercase = super()._pad( encoded_inputs=lowercase__ ,max_length=lowercase__ ,padding_strategy=lowercase__ ,pad_to_multiple_of=lowercase__ ,return_attention_mask=lowercase__ ,) # Load from model defaults if return_attention_mask is None: __lowercase = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: __lowercase = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. __lowercase = len(encoded_inputs['''global_attention_mask'''] ) != len(lowercase__ ) if needs_to_be_padded: __lowercase = len(lowercase__ ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` __lowercase = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": __lowercase = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
104
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
0
"""simple docstring""" import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand a : Optional[int] = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) a : Tuple = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) a : Union[str, Any] = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) a : str = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) a : str = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]), ('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) a : Optional[int] = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) a : str = ( ('''JH AH TH KH QH''', 23), ('''JH 9H TH KH QH''', 22), ('''JC KH JS JD JH''', 21), ('''KH KC 3S 3H 3D''', 20), ('''8C 9C 5C 3C TC''', 19), ('''JS QS 9H TS KH''', 18), ('''7C 7S KH 2H 7H''', 17), ('''3C KH 5D 5S KH''', 16), ('''QH 8H KD JH 8S''', 15), ('''2D 6D 9D TH 7D''', 14), ) def _SCREAMING_SNAKE_CASE ( ) ->Tuple: '''simple docstring''' a, a : List[Any] = randrange(len(_lowercase ) ), randrange(len(_lowercase ) ) a : Dict = ["Loss", "Tie", "Win"][(play >= oppo) + (play > oppo)] a, a : Optional[int] = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _SCREAMING_SNAKE_CASE ( _lowercase : int = 100 ) ->Tuple: '''simple docstring''' return (generate_random_hand() for _ in range(_lowercase )) @pytest.mark.parametrize("hand, expected" , _lowercase ) def _SCREAMING_SNAKE_CASE ( _lowercase : Tuple , _lowercase : Tuple ) ->List[Any]: '''simple docstring''' assert PokerHand(_lowercase )._is_flush() == expected @pytest.mark.parametrize("hand, expected" , _lowercase ) def _SCREAMING_SNAKE_CASE ( _lowercase : List[str] , _lowercase : Any ) ->Union[str, Any]: '''simple docstring''' assert PokerHand(_lowercase )._is_straight() == expected @pytest.mark.parametrize("hand, expected, card_values" , _lowercase ) def _SCREAMING_SNAKE_CASE ( _lowercase : str , _lowercase : Optional[int] , _lowercase : Tuple ) ->int: '''simple docstring''' a : str = PokerHand(_lowercase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize("hand, expected" , _lowercase ) def _SCREAMING_SNAKE_CASE ( _lowercase : Optional[Any] , _lowercase : int ) ->str: '''simple docstring''' assert PokerHand(_lowercase )._is_same_kind() == expected @pytest.mark.parametrize("hand, expected" , _lowercase ) def _SCREAMING_SNAKE_CASE ( _lowercase : List[Any] , _lowercase : Optional[int] ) ->Optional[Any]: '''simple docstring''' assert PokerHand(_lowercase )._hand_type == expected @pytest.mark.parametrize("hand, other, expected" , _lowercase ) def _SCREAMING_SNAKE_CASE ( _lowercase : int , _lowercase : str , _lowercase : Optional[int] ) ->Union[str, Any]: '''simple docstring''' assert PokerHand(_lowercase ).compare_with(PokerHand(_lowercase ) ) == expected @pytest.mark.parametrize("hand, other, expected" , generate_random_hands() ) def _SCREAMING_SNAKE_CASE ( _lowercase : str , _lowercase : List[Any] , _lowercase : Optional[Any] ) ->Union[str, Any]: '''simple docstring''' assert PokerHand(_lowercase ).compare_with(PokerHand(_lowercase ) ) == expected def _SCREAMING_SNAKE_CASE ( ) ->Optional[int]: '''simple docstring''' a : Union[str, Any] = [PokerHand(_lowercase ) for hand in SORTED_HANDS] a : Union[str, Any] = poker_hands.copy() shuffle(_lowercase ) a : Tuple = chain(sorted(_lowercase ) ) for index, hand in enumerate(_lowercase ): assert hand == poker_hands[index] def _SCREAMING_SNAKE_CASE ( ) ->Optional[int]: '''simple docstring''' a : int = [PokerHand("2D AC 3H 4H 5S" ), PokerHand("2S 3H 4H 5S 6C" )] pokerhands.sort(reverse=_lowercase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _SCREAMING_SNAKE_CASE ( ) ->List[str]: '''simple docstring''' a : List[Any] = PokerHand("2C 4S AS 3D 5C" ) a : Optional[Any] = True a : Optional[Any] = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _SCREAMING_SNAKE_CASE ( ) ->Union[str, Any]: '''simple docstring''' a : Tuple = 0 a : Union[str, Any] = os.path.abspath(os.path.dirname(_lowercase ) ) a : Optional[Any] = os.path.join(_lowercase , "poker_hands.txt" ) with open(_lowercase ) as file_hand: for line in file_hand: a : Tuple = line[:14].strip() a : List[Any] = line[15:].strip() a, a : Optional[int] = PokerHand(_lowercase ), PokerHand(_lowercase ) a : str = player.compare_with(_lowercase ) if output == "Win": answer += 1 assert answer == 376
105
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
"""simple docstring""" 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 SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Dict ,lowercase_ : Tuple ,lowercase_ : List[str]=1_3 ,lowercase_ : int=7 ,lowercase_ : Optional[Any]=True ,lowercase_ : Any=True ,lowercase_ : int=True ,lowercase_ : Any=True ,lowercase_ : str=9_9 ,lowercase_ : Union[str, Any]=3_2 ,lowercase_ : str=2 ,lowercase_ : Union[str, Any]=4 ,lowercase_ : Optional[int]=3_7 ,lowercase_ : Any="gelu" ,lowercase_ : str=0.1 ,lowercase_ : Dict=0.1 ,lowercase_ : Optional[int]=5_1_2 ,lowercase_ : Optional[Any]=1_6 ,lowercase_ : Optional[Any]=2 ,lowercase_ : int=0.02 ,lowercase_ : Union[str, Any]=3 ,lowercase_ : Optional[Any]=4 ,lowercase_ : Dict=None ,): lowerCAmelCase__ : Tuple = parent lowerCAmelCase__ : Dict = 1_3 lowerCAmelCase__ : List[str] = 7 lowerCAmelCase__ : Union[str, Any] = True lowerCAmelCase__ : Any = True lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : Optional[int] = True lowerCAmelCase__ : List[Any] = 9_9 lowerCAmelCase__ : Any = 3_2 lowerCAmelCase__ : Optional[int] = 2 lowerCAmelCase__ : Optional[Any] = 4 lowerCAmelCase__ : Any = 3_7 lowerCAmelCase__ : Tuple = '''gelu''' lowerCAmelCase__ : Any = 0.1 lowerCAmelCase__ : Union[str, Any] = 0.1 lowerCAmelCase__ : List[Any] = 5_1_2 lowerCAmelCase__ : str = 1_6 lowerCAmelCase__ : Union[str, Any] = 2 lowerCAmelCase__ : List[Any] = 0.02 lowerCAmelCase__ : Optional[Any] = 3 lowerCAmelCase__ : Union[str, Any] = 4 lowerCAmelCase__ : Optional[int] = None def __lowerCAmelCase ( self : Optional[int] ): lowerCAmelCase__ : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowerCAmelCase__ : List[Any] = None if self.use_input_mask: lowerCAmelCase__ : Any = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ : List[Any] = None if self.use_token_type_ids: lowerCAmelCase__ : List[str] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) lowerCAmelCase__ : Tuple = None lowerCAmelCase__ : Optional[int] = None lowerCAmelCase__ : int = None if self.use_labels: lowerCAmelCase__ : Union[str, Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowerCAmelCase__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) lowerCAmelCase__ : Tuple = ids_tensor([self.batch_size] ,self.num_choices ) lowerCAmelCase__ : Tuple = RoFormerConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,return_dict=lowercase_ ,) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : List[str] ,lowercase_ : List[str] ,lowercase_ : Tuple ,lowercase_ : Tuple ,lowercase_ : Optional[int] ,lowercase_ : str ,lowercase_ : str ,lowercase_ : Dict ): lowerCAmelCase__ : Optional[int] = TFRoFormerModel(config=lowercase_ ) lowerCAmelCase__ : Optional[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} lowerCAmelCase__ : str = [input_ids, input_mask] lowerCAmelCase__ : str = model(lowercase_ ) lowerCAmelCase__ : Optional[int] = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : List[str] ,lowercase_ : Union[str, Any] ,lowercase_ : Any ,lowercase_ : Union[str, Any] ,lowercase_ : int ,lowercase_ : Optional[int] ,lowercase_ : Optional[Any] ,lowercase_ : Optional[int] ): lowerCAmelCase__ : Dict = True lowerCAmelCase__ : Tuple = TFRoFormerForCausalLM(config=lowercase_ ) lowerCAmelCase__ : List[str] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : Dict = model(lowercase_ )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) ,[self.batch_size, self.seq_length, self.vocab_size] ) def __lowerCAmelCase ( self : int ,lowercase_ : Any ,lowercase_ : int ,lowercase_ : int ,lowercase_ : str ,lowercase_ : str ,lowercase_ : Optional[int] ,lowercase_ : Any ): lowerCAmelCase__ : Optional[Any] = TFRoFormerForMaskedLM(config=lowercase_ ) lowerCAmelCase__ : Dict = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : Union[str, Any] = model(lowercase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : int ,lowercase_ : List[Any] ,lowercase_ : List[Any] ,lowercase_ : Any ,lowercase_ : str ,lowercase_ : int ,lowercase_ : List[Any] ,lowercase_ : List[str] ): lowerCAmelCase__ : List[str] = self.num_labels lowerCAmelCase__ : List[str] = TFRoFormerForSequenceClassification(config=lowercase_ ) lowerCAmelCase__ : int = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : str = model(lowercase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : int ,lowercase_ : List[str] ,lowercase_ : Dict ,lowercase_ : Any ,lowercase_ : str ,lowercase_ : str ,lowercase_ : List[Any] ,lowercase_ : Optional[int] ): lowerCAmelCase__ : List[Any] = self.num_choices lowerCAmelCase__ : Tuple = TFRoFormerForMultipleChoice(config=lowercase_ ) lowerCAmelCase__ : List[str] = tf.tile(tf.expand_dims(lowercase_ ,1 ) ,(1, self.num_choices, 1) ) lowerCAmelCase__ : Tuple = tf.tile(tf.expand_dims(lowercase_ ,1 ) ,(1, self.num_choices, 1) ) lowerCAmelCase__ : Tuple = tf.tile(tf.expand_dims(lowercase_ ,1 ) ,(1, self.num_choices, 1) ) lowerCAmelCase__ : Optional[Any] = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } lowerCAmelCase__ : Union[str, Any] = model(lowercase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : int ,lowercase_ : Optional[Any] ,lowercase_ : List[str] ,lowercase_ : List[str] ,lowercase_ : List[str] ,lowercase_ : Optional[int] ,lowercase_ : Any ,lowercase_ : Dict ): lowerCAmelCase__ : Any = self.num_labels lowerCAmelCase__ : List[Any] = TFRoFormerForTokenClassification(config=lowercase_ ) lowerCAmelCase__ : Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : Optional[int] = model(lowercase_ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : str ,lowercase_ : List[str] ,lowercase_ : Any ,lowercase_ : Any ,lowercase_ : Dict ,lowercase_ : str ,lowercase_ : Any ,lowercase_ : Any ): lowerCAmelCase__ : List[Any] = TFRoFormerForQuestionAnswering(config=lowercase_ ) lowerCAmelCase__ : Optional[int] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } lowerCAmelCase__ : str = model(lowercase_ ) 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 __lowerCAmelCase ( self : Dict ): lowerCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) : Optional[int] = config_and_inputs lowerCAmelCase__ : List[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class SCREAMING_SNAKE_CASE ( a_ , a_ , unittest.TestCase ): """simple docstring""" lowercase__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) lowercase__ = ( { "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 {} ) lowercase__ = False lowercase__ = False def __lowerCAmelCase ( self : Union[str, Any] ,lowercase_ : Dict ,lowercase_ : int ,lowercase_ : Optional[int] ,lowercase_ : Optional[Any] ,lowercase_ : str ): if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : Any = TFRoFormerModelTester(self ) lowerCAmelCase__ : Any = ConfigTester(self ,config_class=lowercase_ ,hidden_size=3_7 ) def __lowerCAmelCase ( self : Optional[Any] ): self.config_tester.run_common_tests() def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase_ ) def __lowerCAmelCase ( self : Any ): lowerCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*lowercase_ ) def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase_ ) def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase_ ) def __lowerCAmelCase ( self : int ): lowerCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase_ ) def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase_ ) @slow def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Dict = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(lowercase_ ) @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Tuple ): lowerCAmelCase__ : Dict = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) lowerCAmelCase__ : Dict = tf.constant([[0, 1, 2, 3, 4, 5]] ) lowerCAmelCase__ : Optional[int] = model(lowercase_ )[0] # TODO Replace vocab size lowerCAmelCase__ : int = 5_0_0_0_0 lowerCAmelCase__ : int = [1, 6, vocab_size] self.assertEqual(output.shape ,lowercase_ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. lowerCAmelCase__ : Optional[int] = 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] ,lowercase_ ,atol=1E-4 ) @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" lowercase__ = 1e-4 def __lowerCAmelCase ( self : List[Any] ): lowerCAmelCase__ : List[Any] = tf.constant([[4, 1_0]] ) lowerCAmelCase__ : Optional[int] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 ,embedding_dim=6 ) lowerCAmelCase__ : List[Any] = emba(input_ids.shape ) lowerCAmelCase__ : int = 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(lowercase_ ,lowercase_ ,atol=self.tolerance ) def __lowerCAmelCase ( self : List[str] ): lowerCAmelCase__ : Tuple = 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], ] ) lowerCAmelCase__ : Tuple = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 ,embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) lowerCAmelCase__ : int = emba.weight[:3, :5] tf.debugging.assert_near(lowercase_ ,lowercase_ ,atol=self.tolerance ) @require_tf class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" lowercase__ = 1e-4 def __lowerCAmelCase ( self : str ): # 2,12,16,64 lowerCAmelCase__ : Optional[Any] = tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 ,dtype=tf.floataa ) ,shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 lowerCAmelCase__ : Optional[Any] = -tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 ,dtype=tf.floataa ) ,shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 lowerCAmelCase__ : Optional[int] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 ,embedding_dim=6_4 ) lowerCAmelCase__ : str = embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] lowerCAmelCase__ ,lowerCAmelCase__ : Any = TFRoFormerSelfAttention.apply_rotary_position_embeddings( lowercase_ ,lowercase_ ,lowercase_ ) lowerCAmelCase__ : str = 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], ] ) lowerCAmelCase__ : Union[str, Any] = 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] ,lowercase_ ,atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] ,lowercase_ ,atol=self.tolerance )
106
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 UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 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, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 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" , )
92
0
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split __lowerCAmelCase : Any = datasets.load_iris() __lowerCAmelCase : List[Any] = np.array(data['data']) __lowerCAmelCase : List[str] = np.array(data['target']) __lowerCAmelCase : Dict = data['target_names'] __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : List[str] = train_test_split(X, y) def __magic_name__ ( A : Optional[Any], A : Optional[Any] ): '''simple docstring''' return np.linalg.norm(np.array(A ) - np.array(A ) ) def __magic_name__ ( A : Tuple, A : List[Any], A : int, A : str, A : int=5 ): '''simple docstring''' a = zip(A, A ) # List of distances of all points from the point to be classified a = [] for data_point in data: a = euclidean_distance(data_point[0], A ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. a = [i[1] for i in sorted(A )[:k]] # Most commonly occurring class among them # is the class into which the point is classified a = Counter(A ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
107
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
0
"""simple docstring""" from math import ceil def a__ ( SCREAMING_SNAKE_CASE : List[str] , SCREAMING_SNAKE_CASE : Tuple ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = list(range(0 , SCREAMING_SNAKE_CASE ) ) lowerCAmelCase : Union[str, Any] = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check lowerCAmelCase : Optional[Any] = [] for i in device_map_blocks: if device_map_blocks.count(SCREAMING_SNAKE_CASE ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(SCREAMING_SNAKE_CASE ) # Missing blocks lowerCAmelCase : Any = [i for i in blocks if i not in device_map_blocks] lowerCAmelCase : Any = [i for i in device_map_blocks if i not in blocks] if len(SCREAMING_SNAKE_CASE ) != 0: raise ValueError( "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device." " These attention blocks were specified more than once: " + str(SCREAMING_SNAKE_CASE ) ) if len(SCREAMING_SNAKE_CASE ) != 0: raise ValueError( "There are attention blocks for this model that are not specified in the device_map. Add these attention " "blocks to a device on the device_map: " + str(SCREAMING_SNAKE_CASE ) ) if len(SCREAMING_SNAKE_CASE ) != 0: raise ValueError( "The device_map contains more attention blocks than this model has. Remove these from the device_map:" + str(SCREAMING_SNAKE_CASE ) ) def a__ ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Any ): '''simple docstring''' lowerCAmelCase : List[Any] = list(range(SCREAMING_SNAKE_CASE ) ) lowerCAmelCase : Union[str, Any] = int(ceil(n_layers / len(SCREAMING_SNAKE_CASE ) ) ) lowerCAmelCase : int = [layers[i : i + n_blocks] for i in range(0 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )] return dict(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) )
108
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 UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = 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) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 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. __lowerCAmelCase = [ "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 , )
92
0
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": A: Tuple = argparse.ArgumentParser() parser.add_argument( "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert." ) parser.add_argument( "--original_config_file", type=str, required=True, help="The YAML config file corresponding to the original architecture.", ) parser.add_argument( "--num_in_channels", default=None, type=int, help="The number of input channels. If `None` number of input channels will be automatically inferred.", ) parser.add_argument( "--image_size", default=5_1_2, type=int, help=( "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2" " Base. Use 768 for Stable Diffusion v2." ), ) parser.add_argument( "--extract_ema", action="store_true", help=( "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights" " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield" " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning." ), ) parser.add_argument( "--upcast_attention", action="store_true", help=( "Whether the attention computation should always be upcasted. This is necessary when running stable" " diffusion 2.1." ), ) parser.add_argument( "--from_safetensors", action="store_true", help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.", ) parser.add_argument( "--to_safetensors", action="store_true", help="Whether to store pipeline in safetensors format or not.", ) parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)") def _snake_case ( UpperCamelCase : int ): if string == "True": return True elif string == "False": return False else: raise ValueError(F"could not parse string as bool {string}" ) parser.add_argument( "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool ) parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int) A: Union[str, Any] = parser.parse_args() A: Tuple = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
109
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ): return x return (x, x) @require_tf class a__ : def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase = VisionTextDualEncoderConfig.from_vision_text_configs(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = after_output[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = np.abs((a - b) ).max() self.assertLessEqual(_A , _A , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_save_load(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_pretrained_model_and_inputs() __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = after_outputs[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFViTModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFViTModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFDeiTModel(_A , name="vision_model" ) __lowerCAmelCase = TFRobertaModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFDeiTModelTester(self ) __lowerCAmelCase = TFRobertaModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = clip_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=_A ) __lowerCAmelCase = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __lowerCAmelCase = processor( text=["una foto di un gatto", "una foto di un cane"] , images=_A , padding=_A , return_tensors="np" ) __lowerCAmelCase = model(**_A ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __lowerCAmelCase = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , _A , atol=1E-3 ) )
92
0
from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class _a ( UpperCamelCase__ ): def __init__( self: Optional[Any] , UpperCamelCase_: pyspark.sql.DataFrame , UpperCamelCase_: Optional[NamedSplit] = None , UpperCamelCase_: Optional[Features] = None , UpperCamelCase_: bool = True , UpperCamelCase_: str = None , UpperCamelCase_: bool = False , UpperCamelCase_: str = None , UpperCamelCase_: bool = True , UpperCamelCase_: str = "arrow" , **UpperCamelCase_: Tuple , ) -> Optional[int]: """simple docstring""" super().__init__( split=UpperCamelCase_ , features=UpperCamelCase_ , cache_dir=UpperCamelCase_ , keep_in_memory=UpperCamelCase_ , streaming=UpperCamelCase_ , **UpperCamelCase_ , ) lowercase__ = load_from_cache_file lowercase__ = file_format lowercase__ = Spark( df=UpperCamelCase_ , features=UpperCamelCase_ , cache_dir=UpperCamelCase_ , working_dir=UpperCamelCase_ , **UpperCamelCase_ , ) def lowerCamelCase_ ( self: str ) -> Optional[int]: """simple docstring""" if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) lowercase__ = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=UpperCamelCase_ , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
110
import json import os import torch from diffusers import UNetaDModel os.makedirs("""hub/hopper-medium-v2/unet/hor32""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/unet/hor128""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/value_function""", exist_ok=True) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): if hor == 1_28: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 64, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") __lowerCAmelCase = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) __lowerCAmelCase = model.state_dict() __lowerCAmelCase = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 6_55_36, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 1_28, 2_56), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 6_55_36, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } __lowerCAmelCase = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) __lowerCAmelCase = model __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
92
0
"""simple docstring""" import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib _UpperCamelCase : Optional[Any] = threading.Lock() _UpperCamelCase : Optional[int] = None _UpperCamelCase : Optional[Any] = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } _UpperCamelCase : Optional[int] = logging.WARNING _UpperCamelCase : str = True def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = os.getenv('TRANSFORMERS_VERBOSITY' , SCREAMING_SNAKE_CASE_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' f'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return __name__.split('.' )[0] def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return lowercase = logging.StreamHandler() # Set sys.stderr as stream. lowercase = sys.stderr.flush # Apply our default configuration to the library root logger. lowercase = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) lowercase = False def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return lowercase = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) lowercase = None def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return log_levels def _SCREAMING_SNAKE_CASE ( __snake_case : Optional[str] = None ): '''simple docstring''' if name is None: lowercase = _get_library_name() _configure_library_root_logger() return logging.getLogger(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def _SCREAMING_SNAKE_CASE ( __snake_case : int ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' return set_verbosity(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def _SCREAMING_SNAKE_CASE ( __snake_case : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( __snake_case : logging.Handler ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _configure_library_root_logger() lowercase = False def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' _configure_library_root_logger() lowercase = True def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = _get_library_root_logger().handlers for handler in handlers: lowercase = logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s' ) handler.setFormatter(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] , *__snake_case : Optional[int] , **__snake_case : int ): '''simple docstring''' lowercase = os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS' , SCREAMING_SNAKE_CASE_ ) if no_advisory_warnings: return self.warning(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : int = warning_advice @functools.lru_cache(SCREAMING_SNAKE_CASE_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple , *__snake_case : int , **__snake_case : Optional[int] ): '''simple docstring''' self.warning(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : List[Any] = warning_once class a : def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): # pylint: disable=unused-argument lowercase = args[0] if args else None def __iter__( self ): return iter(self._iterator ) def __getattr__( self , _lowerCamelCase ): def empty_fn(*_lowerCamelCase , **_lowerCamelCase ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ): return self def __exit__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): return class a : def __call__( self , *_lowerCamelCase , **_lowerCamelCase ): if _tqdm_active: return tqdm_lib.tqdm(*_A , **_A ) else: return EmptyTqdm(*_A , **_A ) def UpperCamelCase_ ( self , *_lowerCamelCase , **_lowerCamelCase ): lowercase = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_A , **_A ) def UpperCamelCase_ ( self ): if _tqdm_active: return tqdm_lib.tqdm.get_lock() _UpperCamelCase : str = _tqdm_cls() def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' global _tqdm_active lowercase = True hf_hub_utils.enable_progress_bars() def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' global _tqdm_active lowercase = False hf_hub_utils.disable_progress_bars()
220
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = metric_id class a__ : _a : Optional[int] = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): if "tmp_path" in args: __lowerCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="https://huggingface.co/docs/evaluate" ): func(*SCREAMING_SNAKE_CASE_ )
92
0
from ..utils import DummyObject, requires_backends class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> int: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Dict: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> int: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> str: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Tuple: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Dict: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Dict: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Dict: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> str: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> str: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Optional[int]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> List[str]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Tuple: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Tuple: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> List[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Optional[Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> List[str]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['''flax'''] ) class __A( metaclass=snake_case__ ): snake_case_ = ["""flax"""] def __init__( self , *_snake_case , **_snake_case ) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Tuple: '''simple docstring''' requires_backends(cls , ['''flax'''] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls , *_snake_case , **_snake_case ) -> Any: '''simple docstring''' requires_backends(cls , ['''flax'''] )
6
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
0
class _UpperCAmelCase : """simple docstring""" def __init__( self : Tuple, lowerCamelCase : Optional[int], lowerCamelCase : Any, lowerCamelCase : str ): '''simple docstring''' lowercase__ = name lowercase__ = value lowercase__ = weight def __repr__( self : Union[str, Any] ): '''simple docstring''' return F"""{self.__class__.__name__}({self.name}, {self.value}, {self.weight})""" def lowercase__ ( self : Tuple ): '''simple docstring''' return self.value def lowercase__ ( self : str ): '''simple docstring''' return self.name def lowercase__ ( self : Optional[Any] ): '''simple docstring''' return self.weight def lowercase__ ( self : Optional[int] ): '''simple docstring''' return self.value / self.weight def a ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' lowercase__ = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def a ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' lowercase__ = sorted(SCREAMING_SNAKE_CASE_ , key=SCREAMING_SNAKE_CASE_ , reverse=SCREAMING_SNAKE_CASE_ ) lowercase__ = [] lowercase__ , lowercase__ = 0.0, 0.0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def a ( ): '''simple docstring''' pass if __name__ == "__main__": import doctest doctest.testmod()
207
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCamelCase__ = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCAmelCase: Any = TypeVar('T') class a__( Generic[T] ): def __init__( self : Dict , __snake_case : int ): a : List[str] = data a : int = None def __str__( self : Dict ): return F"""{self.data}""" class a__( Generic[T] ): def __init__( self : Tuple ): a : List[str] = None def __iter__( self : Union[str, Any] ): a : str = self.top while node: yield node.data a : List[str] = node.next def __str__( self : str ): return "->".join([str(_A ) for item in self] ) def __len__( self : Any ): return len(tuple(iter(self ) ) ) def lowercase_ ( self : Optional[int] ): return self.top is None def lowercase_ ( self : Optional[Any] , __snake_case : List[str] ): a : List[str] = Node(_A ) if not self.is_empty(): a : str = self.top a : str = node def lowercase_ ( self : Union[str, Any] ): if self.is_empty(): raise IndexError('pop from empty stack' ) assert isinstance(self.top , _A ) a : List[str] = self.top a : str = self.top.next return pop_node.data def lowercase_ ( self : Union[str, Any] ): if self.is_empty(): raise IndexError('peek from empty stack' ) assert self.top is not None return self.top.data def lowercase_ ( self : Optional[int] ): a : Tuple = None if __name__ == "__main__": from doctest import testmod testmod()
297
import argparse import os import re import packaging.version UpperCamelCase__ = """examples/""" UpperCamelCase__ = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCamelCase__ = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCamelCase__ = """README.md""" def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = re_pattern.sub(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , pattern="examples" ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(SCREAMING_SNAKE_CASE_ ) def _a ( ): with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(SCREAMING_SNAKE_CASE_ ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any]=False ): __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ , patch=SCREAMING_SNAKE_CASE_ ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _a ( ): __lowerCAmelCase = get_version() __lowerCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCamelCase__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
92
0
from __future__ import annotations UpperCAmelCase : Optional[int] = [] def __lowerCamelCase ( lowerCamelCase__ : list[list[int]] , lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if board[row][i] == 1: return False for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if board[i][column] == 1: return False for i, j in zip(range(SCREAMING_SNAKE_CASE_ , -1 , -1 ) , range(SCREAMING_SNAKE_CASE_ , -1 , -1 ) ): if board[i][j] == 1: return False for i, j in zip(range(SCREAMING_SNAKE_CASE_ , -1 , -1 ) , range(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ) ): if board[i][j] == 1: return False return True def __lowerCamelCase ( lowerCamelCase__ : list[list[int]] , lowerCamelCase__ : int ): '''simple docstring''' if row >= len(SCREAMING_SNAKE_CASE_ ): solution.append(SCREAMING_SNAKE_CASE_ ) printboard(SCREAMING_SNAKE_CASE_ ) print() return True for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if is_safe(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase = 1 solve(SCREAMING_SNAKE_CASE_ , row + 1 ) lowerCamelCase = 0 return False def __lowerCamelCase ( lowerCamelCase__ : list[list[int]] ): '''simple docstring''' for i in range(len(SCREAMING_SNAKE_CASE_ ) ): for j in range(len(SCREAMING_SNAKE_CASE_ ) ): if board[i][j] == 1: print("""Q""" , end=""" """ ) else: print(""".""" , end=""" """ ) print() # n=int(input("The no. of queens")) UpperCAmelCase : Optional[int] = 8 UpperCAmelCase : Optional[Any] = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
252
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 a__ ( snake_case__ , unittest.TestCase ): _a : Dict = KandinskyImgaImgPipeline _a : List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] _a : str = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] _a : List[Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _a : int = False @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim * 4 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 1_0_0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) __lowerCAmelCase = MultilingualCLIP(_A ) __lowerCAmelCase = text_encoder.eval() return text_encoder @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = { "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, } __lowerCAmelCase = UNetaDConditionModel(**_A ) return model @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return { "block_out_channels": [3_2, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_unet __lowerCAmelCase = self.dummy_movq __lowerCAmelCase = { "num_train_timesteps": 1_0_0_0, "beta_schedule": "linear", "beta_start": 0.0_00_85, "beta_end": 0.0_12, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } __lowerCAmelCase = DDIMScheduler(**_A ) __lowerCAmelCase = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_A ) # create init_image __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCAmelCase = Image.fromarray(np.uinta(_A ) ).convert("RGB" ).resize((2_5_6, 2_5_6) ) if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "horse", "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 6_4, "width": 6_4, "num_inference_steps": 1_0, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "cpu" __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = self.pipeline_class(**_A ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __lowerCAmelCase = pipe(**self.get_dummy_inputs(_A ) ) __lowerCAmelCase = output.images __lowerCAmelCase = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCAmelCase = np.array( [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33] ) 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 a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_img2img_frog.npy" ) __lowerCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __lowerCAmelCase = "A red cartoon frog, 4k" __lowerCAmelCase = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __lowerCAmelCase = KandinskyImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase , __lowerCAmelCase = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __lowerCAmelCase = pipeline( _A , image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A )
92
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { "BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json", # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class UpperCAmelCase_ ( snake_case__ ): """simple docstring""" lowercase = """altclip_text_model""" def __init__( self : List[str] , snake_case_ : int=250_002 , snake_case_ : Tuple=1_024 , snake_case_ : str=24 , snake_case_ : Optional[int]=16 , snake_case_ : str=4_096 , snake_case_ : Optional[int]="gelu" , snake_case_ : Dict=0.1 , snake_case_ : str=0.1 , snake_case_ : List[Any]=514 , snake_case_ : int=1 , snake_case_ : str=0.02 , snake_case_ : List[str]=0.02 , snake_case_ : List[str]=1E-0_5 , snake_case_ : Any=1 , snake_case_ : Optional[int]=0 , snake_case_ : str=2 , snake_case_ : Tuple="absolute" , snake_case_ : List[Any]=True , snake_case_ : List[str]=768 , **snake_case_ : Union[str, Any] , ): super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A ) snake_case__ : Optional[int] = vocab_size snake_case__ : Optional[int] = hidden_size snake_case__ : str = num_hidden_layers snake_case__ : List[str] = num_attention_heads snake_case__ : List[str] = hidden_act snake_case__ : Union[str, Any] = intermediate_size snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : str = max_position_embeddings snake_case__ : Tuple = type_vocab_size snake_case__ : Union[str, Any] = initializer_range snake_case__ : Dict = initializer_factor snake_case__ : Any = layer_norm_eps snake_case__ : int = position_embedding_type snake_case__ : List[Any] = use_cache snake_case__ : List[Any] = project_dim class UpperCAmelCase_ ( snake_case__ ): """simple docstring""" lowercase = """altclip_vision_model""" def __init__( self : Any , snake_case_ : Optional[int]=768 , snake_case_ : List[Any]=3_072 , snake_case_ : Tuple=512 , snake_case_ : Optional[Any]=12 , snake_case_ : List[Any]=12 , snake_case_ : Union[str, Any]=3 , snake_case_ : Any=224 , snake_case_ : Union[str, Any]=32 , snake_case_ : Union[str, Any]="quick_gelu" , snake_case_ : List[Any]=1E-5 , snake_case_ : Tuple=0.0 , snake_case_ : Optional[Any]=0.02 , snake_case_ : Any=1.0 , **snake_case_ : List[str] , ): super().__init__(**_A ) snake_case__ : Optional[int] = hidden_size snake_case__ : Tuple = intermediate_size snake_case__ : Optional[int] = projection_dim snake_case__ : Dict = num_hidden_layers snake_case__ : Any = num_attention_heads snake_case__ : Tuple = num_channels snake_case__ : Optional[int] = patch_size snake_case__ : int = image_size snake_case__ : List[Any] = initializer_range snake_case__ : Any = initializer_factor snake_case__ : Optional[Any] = attention_dropout snake_case__ : List[Any] = layer_norm_eps snake_case__ : Tuple = hidden_act @classmethod def lowerCamelCase ( cls : Any , snake_case_ : Union[str, Any] , **snake_case_ : Any ): cls._set_token_in_kwargs(_A ) snake_case__ , snake_case__ : int = cls.get_config_dict(_A , **_A ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get("""model_type""" ) == "altclip": snake_case__ : Tuple = 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_ ( snake_case__ ): """simple docstring""" lowercase = """altclip""" lowercase = True def __init__( self : List[Any] , snake_case_ : Union[str, Any]=None , snake_case_ : str=None , snake_case_ : Union[str, Any]=768 , snake_case_ : List[str]=2.6592 , **snake_case_ : List[Any] ): snake_case__ : Optional[int] = kwargs.pop("""text_config_dict""" , _A ) snake_case__ : Optional[Any] = kwargs.pop("""vision_config_dict""" , _A ) super().__init__(**_A ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: snake_case__ : Any = {} # This is the complete result when using `text_config_dict`. snake_case__ : Optional[Any] = AltCLIPTextConfig(**_A ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: snake_case__ : Dict = ( f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. " f"The value `text_config_dict[\"{key}\"]` will be used instead." ) # If inferred from default argument values (just to be super careful) else: snake_case__ : Optional[Any] = ( f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The " f"value `text_config[\"{key}\"]` will be overriden." ) logger.warning(_A ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: snake_case__ : Optional[Any] = {} # This is the complete result when using `vision_config_dict`. snake_case__ : str = AltCLIPVisionConfig(**_A ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: snake_case__ : Union[str, Any] = { str(_A ): value for key, value in _vision_config_dict["""id2label"""].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: snake_case__ : List[Any] = ( f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different " f"values. The value `vision_config_dict[\"{key}\"]` will be used instead." ) # If inferred from default argument values (just to be super careful) else: snake_case__ : List[str] = ( f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. " f"The value `vision_config[\"{key}\"]` will be overriden." ) logger.warning(_A ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: snake_case__ : int = {} logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""" ) if vision_config is None: snake_case__ : Optional[Any] = {} logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""" ) snake_case__ : Optional[Any] = AltCLIPTextConfig(**_A ) snake_case__ : Dict = AltCLIPVisionConfig(**_A ) snake_case__ : List[str] = projection_dim snake_case__ : Optional[Any] = logit_scale_init_value snake_case__ : int = 1.0 @classmethod def lowerCamelCase ( cls : Optional[Any] , snake_case_ : List[Any] , snake_case_ : Tuple , **snake_case_ : Dict ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_A ) def lowerCamelCase ( self : Dict ): snake_case__ : int = copy.deepcopy(self.__dict__ ) snake_case__ : List[str] = self.text_config.to_dict() snake_case__ : int = self.vision_config.to_dict() snake_case__ : List[Any] = self.__class__.model_type return output
35
class a__ ( snake_case__ ): pass class a__ ( snake_case__ ): pass class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [ [], [], [], ] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(_A ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): """simple docstring""" return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if len(self.queue ) == 1_0_0: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(_A ) return data def __str__( self ): """simple docstring""" return str(self.queue ) def _a ( ): __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
92
0
'''simple docstring''' 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__ ( snake_case__ , unittest.TestCase): UpperCAmelCase__ : Dict = KandinskyImgaImgPipeline UpperCAmelCase__ : List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] UpperCAmelCase__ : str = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] UpperCAmelCase__ : List[Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] UpperCAmelCase__ : int = False @property def lowercase_ ( self :Dict ) -> Dict: '''simple docstring''' return 32 @property def lowercase_ ( self :Any ) -> Optional[Any]: '''simple docstring''' return 32 @property def lowercase_ ( self :Optional[Any] ) -> List[str]: '''simple docstring''' return self.time_input_dim @property def lowercase_ ( self :str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def lowercase_ ( self :Optional[int] ) -> Any: '''simple docstring''' return 100 @property def lowercase_ ( self :Dict ) -> Optional[Any]: '''simple docstring''' __A = XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base' ) return tokenizer @property def lowercase_ ( self :Dict ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __A = 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=1_005 , ) __A = MultilingualCLIP(_A ) __A = text_encoder.eval() return text_encoder @property def lowercase_ ( self :str ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __A = { '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, } __A = UNetaDConditionModel(**_A ) return model @property def lowercase_ ( self :str ) -> Dict: '''simple docstring''' 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 lowercase_ ( self :Tuple ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) __A = VQModel(**self.dummy_movq_kwargs ) return model def lowercase_ ( self :Union[str, Any] ) -> Optional[int]: '''simple docstring''' __A = self.dummy_text_encoder __A = self.dummy_tokenizer __A = self.dummy_unet __A = self.dummy_movq __A = { 'num_train_timesteps': 1_000, 'beta_schedule': 'linear', 'beta_start': 0.00_085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } __A = DDIMScheduler(**_A ) __A = { 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowercase_ ( self :List[Any] , _A :Any , _A :Tuple=0 ) -> Dict: '''simple docstring''' __A = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_A ) ).to(_A ) __A = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_A ) # create init_image __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(_A ) ).to(_A ) __A = image.cpu().permute(0 , 2 , 3 , 1 )[0] __A = Image.fromarray(np.uinta(_A ) ).convert('RGB' ).resize((256, 256) ) if str(_A ).startswith('mps' ): __A = torch.manual_seed(_A ) else: __A = torch.Generator(device=_A ).manual_seed(_A ) __A = { '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 lowercase_ ( self :int ) -> Dict: '''simple docstring''' __A = 'cpu' __A = self.get_dummy_components() __A = self.pipeline_class(**_A ) __A = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __A = pipe(**self.get_dummy_inputs(_A ) ) __A = output.images __A = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __A = image[0, -3:, -3:, -1] __A = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __A = np.array( [0.61_474_943, 0.6_073_539, 0.43_308_544, 0.5_928_269, 0.47_493_595, 0.46_755_973, 0.4_613_838, 0.45_368_797, 0.50_119_233] ) 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): def lowercase_ ( self :Any ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self :Optional[Any] ) -> Tuple: '''simple docstring''' __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/kandinsky_img2img_frog.npy' ) __A = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) __A = 'A red cartoon frog, 4k' __A = KandinskyPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1-prior' , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __A = KandinskyImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-1' , torch_dtype=torch.floataa ) __A = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A , __A = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __A = 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' , ) __A = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_A , _A )
161
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a__ : def __init__( self , _A , _A=1_3 , _A=3_0 , _A=2 , _A=3 , _A=True , _A=True , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1_0 , _A=0.02 , _A=3 , _A=None , _A=2 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = scope __lowerCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 2 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTForMaskedImageModeling(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForMaskedImageModeling(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) _a : int = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) _a : Optional[Any] = False _a : Tuple = False _a : Tuple = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=False ): """simple docstring""" __lowerCAmelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.model_tester.is_training: return __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __lowerCAmelCase = False __lowerCAmelCase = True for model_class in self.all_model_classes: if model_class in get_values(_A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __lowerCAmelCase = model_class(_A ) model.gradient_checkpointing_enable() model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_A ), *get_values(_A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type['title']}""" ): __lowerCAmelCase = problem_type["title"] __lowerCAmelCase = problem_type["num_labels"] __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) if problem_type["num_labels"] > 1: __lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) __lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_A ) as warning_list: __lowerCAmelCase = model(**_A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DeiTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _a ( ): __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( _A ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ).to(_A ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**_A ) # verify the logits __lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _A ) __lowerCAmelCase = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ) __lowerCAmelCase = inputs.pixel_values.to(_A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowerCAmelCase = model(_A )
92
0
"""simple docstring""" 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 a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = filter(lambda _SCREAMING_SNAKE_CASE : p.requires_grad , model.parameters() ) UpperCamelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params lowerCAmelCase__ = logging.getLogger(__name__) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" 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}" elif metric == "loss": UpperCamelCase = "{val_avg_loss:.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=1 , every_n_epochs=1 , ) return checkpoint_callback def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" return EarlyStopping( monitor=F"val_{metric}" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class _lowerCamelCase ( pl.Callback ): def snake_case_ (self , __a , __a ) -> int: 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 snake_case_ (self , __a , __a , __a , __a=True ) -> List[str]: 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 snake_case_ (self , __a , __a ) -> List[Any]: 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 snake_case_ (self , __a , __a ) -> int: save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def snake_case_ (self , __a , __a ) -> Optional[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")
153
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
92
0
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def __lowerCAmelCase ( lowercase : Optional[int] , lowercase : Union[str, Any] , lowercase : Dict ) -> List[Any]: """simple docstring""" snake_case : Optional[Any] = MobileBertConfig.from_json_file(SCREAMING_SNAKE_CASE_ ) print(F'Building PyTorch model from configuration: {config}' ) snake_case : str = MobileBertForPreTraining(SCREAMING_SNAKE_CASE_ ) # Load weights from tf checkpoint snake_case : Any = load_tf_weights_in_mobilebert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __snake_case = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
203
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
92
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a : Tuple = logging.get_logger(__name__) a : List[str] = {'vocab_file': 'sentencepiece.bpe.model'} a : Union[str, Any] = { 'vocab_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model' ), }, } a : List[Any] = { 'moussaKam/mbarthez': 1024, 'moussaKam/barthez': 1024, 'moussaKam/barthez-orangesum-title': 1024, } a : Dict = '▁' class a ( snake_case__ ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["""input_ids""", """attention_mask"""] def __init__( self : Optional[int] , lowercase_ : List[str] , lowercase_ : List[Any]="<s>" , lowercase_ : Optional[Any]="</s>" , lowercase_ : List[Any]="</s>" , lowercase_ : List[Any]="<s>" , lowercase_ : int="<unk>" , lowercase_ : str="<pad>" , lowercase_ : List[Any]="<mask>" , lowercase_ : List[str] = None , **lowercase_ : List[Any] , ): snake_case_ = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else mask_token snake_case_ = {} 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 , ) snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_A ) ) snake_case_ = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} snake_case_ = len(self.sp_model ) - 1 snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def A_ ( self : str , lowercase_ : List[Any] , lowercase_ : int = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : Optional[int] , lowercase_ : List[str] , lowercase_ : int = None , lowercase_ : int = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) if token_ids_a is None: return [1] + ([0] * len(_A )) + [1] return [1] + ([0] * len(_A )) + [1, 1] + ([0] * len(_A )) + [1] def A_ ( self : int , lowercase_ : Tuple , lowercase_ : str = None ): snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A_ ( self : List[Any] ): return len(self.sp_model ) def A_ ( self : Optional[int] ): snake_case_ = {self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : Tuple , lowercase_ : Optional[Any] ): return self.sp_model.encode(_A , out_type=_A ) def A_ ( self : int , lowercase_ : Tuple ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case_ = self.sp_model.PieceToId(_A ) return spm_id if spm_id else self.unk_token_id def A_ ( self : Dict , lowercase_ : Tuple ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(_A ) def A_ ( self : int , lowercase_ : Dict ): snake_case_ = [] snake_case_ = '''''' snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_A ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(_A ) snake_case_ = False out_string += self.sp_model.decode(_A ) return out_string.strip() def __getstate__( self : Union[str, Any] ): snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Optional[int] , lowercase_ : Union[str, Any] ): snake_case_ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A_ ( self : Optional[int] , lowercase_ : Union[str, Any] , lowercase_ : Optional[int] = None ): if not os.path.isdir(_A ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ = os.path.join( _A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _A ) elif not os.path.isfile(self.vocab_file ): with open(_A , '''wb''' ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(_A ) return (out_vocab_file,)
56
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType UpperCamelCase__ = get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {ckpt_dir}""" ) __lowerCAmelCase = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Model saved to {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " "initializing FSDP object" ) return __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) if F"""{MODEL_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading model from {ckpt_dir}""" ) __lowerCAmelCase = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) __lowerCAmelCase = state_dict["model"] logger.info(F"""Model loaded from {ckpt_dir}""" ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {output_optimizer_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state saved in {output_optimizer_file}""" ) else: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {ckpt_dir}""" ) dist_cp.save_state_dict( state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Optimizer state saved in {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading Optimizer state from {input_optimizer_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state loaded from {input_optimizer_file}""" ) else: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) if F"""{OPTIMIZER_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading Optimizer from {ckpt_dir}""" ) __lowerCAmelCase = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) __lowerCAmelCase = optim_state["optimizer"] logger.info(F"""Optimizer loaded from {ckpt_dir}""" ) __lowerCAmelCase = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
92
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a_ : Dict = logging.get_logger(__name__) a_ : Optional[Any] = { """alibaba-damo/mgp-str-base""": """https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json""", } class __UpperCamelCase ( snake_case__ ): lowercase : Union[str, Any] ="""mgp-str""" def __init__( self, lowerCAmelCase=[32, 128], lowerCAmelCase=4, lowerCAmelCase=3, lowerCAmelCase=27, lowerCAmelCase=38, lowerCAmelCase=50_257, lowerCAmelCase=30_522, lowerCAmelCase=768, lowerCAmelCase=12, lowerCAmelCase=12, lowerCAmelCase=4.0, lowerCAmelCase=True, lowerCAmelCase=False, lowerCAmelCase=1e-5, lowerCAmelCase=0.0, lowerCAmelCase=0.0, lowerCAmelCase=0.0, lowerCAmelCase=False, lowerCAmelCase=0.0_2, **lowerCAmelCase, ): """simple docstring""" super().__init__(**_A ) lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =max_token_length lowerCamelCase_ =num_character_labels lowerCamelCase_ =num_bpe_labels lowerCamelCase_ =num_wordpiece_labels lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =mlp_ratio lowerCamelCase_ =distilled lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =drop_rate lowerCamelCase_ =qkv_bias lowerCamelCase_ =attn_drop_rate lowerCamelCase_ =drop_path_rate lowerCamelCase_ =output_aa_attentions lowerCamelCase_ =initializer_range
75
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( snake_case__ ): def __init__( self , *_A , _A=None , _A=None , **_A ): """simple docstring""" super().__init__(*_A , **_A ) __lowerCAmelCase = eval_examples __lowerCAmelCase = post_process_function def __SCREAMING_SNAKE_CASE( self , _A = None , _A=None , _A = None , _A = "eval" , **_A , ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = ( gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length ) __lowerCAmelCase = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams ) __lowerCAmelCase = gen_kwargs __lowerCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset __lowerCAmelCase = self.get_eval_dataloader(_A ) __lowerCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default __lowerCAmelCase = self.post_process_function(_A , _A , _A ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) else: __lowerCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_A ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __lowerCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , _A ) return metrics def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=None , _A = "test" , **_A ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output __lowerCAmelCase = self.post_process_function(_A , _A , _A , "predict" ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_A )
92
0
"""simple docstring""" from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm _UpperCamelCase : Dict = logging.get_logger(__name__) @dataclass class a ( snake_case__ ): UpperCAmelCase_ : str =[ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_lowerCamelCase ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: lowercase = deprecated_arg[3:] setattr(self , _A , not kwargs.pop(_A ) ) logger.warning( F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or' F' {positive_arg}={kwargs[positive_arg]}' ) lowercase = kwargs.pop('torchscript' , self.torchscript ) lowercase = kwargs.pop('torch_xla_tpu_print_metrics' , self.torch_xla_tpu_print_metrics ) lowercase = kwargs.pop('fp16_opt_level' , self.fpaa_opt_level ) super().__init__(**_A ) UpperCAmelCase_ : bool =field(default=snake_case__, metadata={"help": "Trace the models using torchscript"} ) UpperCAmelCase_ : bool =field(default=snake_case__, metadata={"help": "Print Xla/PyTorch tpu metrics"} ) UpperCAmelCase_ : str =field( default="O1", metadata={ "help": ( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. " "See details at https://nvidia.github.io/apex/amp.html" ) }, ) @cached_property def UpperCamelCase_ ( self ): requires_backends(self , ['torch'] ) logger.info('PyTorch: setting up devices' ) if not self.cuda: lowercase = torch.device('cpu' ) lowercase = 0 elif is_torch_tpu_available(): lowercase = xm.xla_device() lowercase = 0 else: lowercase = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) lowercase = torch.cuda.device_count() return device, n_gpu @property def UpperCamelCase_ ( self ): return is_torch_tpu_available() and self.tpu @property def UpperCamelCase_ ( self ): requires_backends(self , ['torch'] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def UpperCamelCase_ ( self ): requires_backends(self , ['torch'] ) return self._setup_devices[0] @property def UpperCamelCase_ ( self ): requires_backends(self , ['torch'] ) return self._setup_devices[1] @property def UpperCamelCase_ ( self ): return self.n_gpu > 0
220
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 _a ( SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = filter(lambda SCREAMING_SNAKE_CASE_ : p.requires_grad , model.parameters() ) __lowerCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase__ = logging.getLogger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): if metric == "rouge2": __lowerCAmelCase = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __lowerCAmelCase = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __lowerCAmelCase = "{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." ) __lowerCAmelCase = 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 _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return EarlyStopping( monitor=F"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class a__ ( pl.Callback ): def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = {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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCAmelCase = 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 __lowerCAmelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCAmelCase = od / "test_results.txt" __lowerCAmelCase = 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. __lowerCAmelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCAmelCase = 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 __lowerCAmelCase = metrics[key] if isinstance(_A , torch.Tensor ): __lowerCAmelCase = val.item() __lowerCAmelCase = f"""{key}: {val:.6f}\n""" writer.write(_A ) if not save_generations: return if "preds" in metrics: __lowerCAmelCase = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: __lowerCAmelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCAmelCase = pl_module.model.num_parameters() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
92
0
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class __A( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' __a = tempfile.mkdtemp() # fmt: off __a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __a = 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] ) ) __a = { '''do_resize''': True, '''size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __a = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_A , _A ) def SCREAMING_SNAKE_CASE_ ( self , **_snake_case ) -> Dict: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **_A ) def SCREAMING_SNAKE_CASE_ ( self , **_snake_case ) -> Optional[int]: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __a = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = self.get_tokenizer() __a = self.get_image_processor() __a = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) processor.save_pretrained(self.tmpdirname ) __a = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __a = self.get_image_processor(do_normalize=_A , padding_value=1.0 ) __a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) __a = self.prepare_image_inputs() __a = image_processor(_A , return_tensors='''np''' ) __a = processor(images=_A , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) __a = '''lower newer''' __a = processor(text=_A ) __a = tokenizer(_A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) __a = '''lower newer''' __a = self.prepare_image_inputs() __a = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_A ): processor() def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) __a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __a = processor.batch_decode(_A ) __a = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = self.get_image_processor() __a = self.get_tokenizer() __a = VisionTextDualEncoderProcessor(tokenizer=_A , image_processor=_A ) __a = '''lower newer''' __a = self.prepare_image_inputs() __a = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
6
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
92
0
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
207
from queue import PriorityQueue from typing import Any import numpy as np def _a ( 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 __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = 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(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = 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_ , ) __lowerCAmelCase = 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: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """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()
92
0
'''simple docstring''' import argparse from collections import defaultdict import yaml lowerCAmelCase: List[str] = 'docs/source/en/_toctree.yml' def lowerCamelCase__ ( _A ): a : int = defaultdict(SCREAMING_SNAKE_CASE_ ) for doc in model_doc: counts[doc["local"]] += 1 a : Any = [key for key, value in counts.items() if value > 1] a : Any = [] for duplicate_key in duplicates: a : List[Any] = list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key} ) if len(SCREAMING_SNAKE_CASE_ ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ' 'others.' ) # Only add this once new_doc.append({'local': duplicate_key, 'title': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1] ) # Sort return sorted(SCREAMING_SNAKE_CASE_ , key=lambda _A : s["title"].lower() ) def lowerCamelCase__ ( _A=False ): with open(SCREAMING_SNAKE_CASE_ , encoding='utf-8' ) as f: a : List[str] = yaml.safe_load(f.read() ) # Get to the API doc a : Dict = 0 while content[api_idx]["title"] != "API": api_idx += 1 a : List[str] = content[api_idx]['sections'] # Then to the model doc a : str = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 a : List[str] = api_doc[model_idx]['sections'] a : List[str] = [(idx, section) for idx, section in enumerate(SCREAMING_SNAKE_CASE_ ) if 'sections' in section] a : Union[str, Any] = False for idx, modality_doc in modalities_docs: a : List[str] = modality_doc['sections'] a : Any = clean_model_doc_toc(SCREAMING_SNAKE_CASE_ ) if old_modality_doc != new_modality_doc: a : str = True if overwrite: a : str = new_modality_doc if diff: if overwrite: a : Any = model_doc a : Tuple = api_doc with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(SCREAMING_SNAKE_CASE_ , allow_unicode=SCREAMING_SNAKE_CASE_ ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) if __name__ == "__main__": lowerCAmelCase: int = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowerCAmelCase: List[Any] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
297
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a__ ( snake_case__ ): _a : Optional[int] = """decision_transformer""" _a : Optional[int] = ["""past_key_values"""] _a : Dict = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _A=1_7 , _A=4 , _A=1_2_8 , _A=4_0_9_6 , _A=True , _A=1 , _A=1_0_2_4 , _A=3 , _A=1 , _A=None , _A="relu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1E-5 , _A=0.02 , _A=True , _A=True , _A=5_0_2_5_6 , _A=5_0_2_5_6 , _A=False , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = state_dim __lowerCAmelCase = act_dim __lowerCAmelCase = hidden_size __lowerCAmelCase = max_ep_len __lowerCAmelCase = action_tanh __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = bos_token_id __lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
92
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class __lowercase ( unittest.TestCase ): """simple docstring""" def __A ( self , A ) -> Dict: '''simple docstring''' for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): lowerCamelCase = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(_A ) def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ) -> Dict: '''simple docstring''' lowerCamelCase = """sgugger/tiny-distilbert-classification""" lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , only_pretrain_model=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , torchscript=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def __A ( self ) -> Dict: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , fpaa=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = AutoConfig.from_pretrained(_A ) # set architectures equal to `None` lowerCamelCase = None lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A , configs=[config] ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ) -> Tuple: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def __A ( self ) -> int: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , fpaa=_A , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ) -> Tuple: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = AutoConfig.from_pretrained(_A ) lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A , configs=[config] ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase = """sshleifer/tinier_bart""" lowerCamelCase = AutoConfig.from_pretrained(_A ) lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A , configs=[config] ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def __A ( self ) -> List[Any]: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" lowerCamelCase = AutoConfig.from_pretrained(_A ) lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A , configs=[config] ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase = """sshleifer/tinier_bart""" lowerCamelCase = AutoConfig.from_pretrained(_A ) lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A , configs=[config] ) lowerCamelCase = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def __A ( self ) -> str: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , save_to_csv=_A , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(_A , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(_A , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(_A , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(_A , """train_time.csv""" ) , env_info_csv_file=os.path.join(_A , """env.csv""" ) , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) benchmark.run() self.assertTrue(Path(os.path.join(_A , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_A , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_A , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_A , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(_A , """env.csv""" ) ).exists() ) def __A ( self ) -> str: '''simple docstring''' lowerCamelCase = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(A ): self.assertTrue(hasattr(_A , """sequential""" ) ) self.assertTrue(hasattr(_A , """cumulative""" ) ) self.assertTrue(hasattr(_A , """current""" ) ) self.assertTrue(hasattr(_A , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: lowerCamelCase = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=_A , inference=_A , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(_A , """log.txt""" ) , log_print=_A , trace_memory_line_by_line=_A , multi_process=_A , ) lowerCamelCase = PyTorchBenchmark(_A ) lowerCamelCase = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(_A , """log.txt""" ) ).exists() )
252
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
0
'''simple docstring''' 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 ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) def __snake_case( _lowerCAmelCase , _lowerCAmelCase=False ) -> List[str]: snake_case__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False ) -> List[str]: for i in range(config.num_hidden_layers ): if base_model: snake_case__ : List[str] = """""" else: snake_case__ : Tuple = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : List[Any] = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) snake_case__ : Optional[Any] = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[Any] = in_proj_bias[: config.hidden_size] snake_case__ : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : Optional[int] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : Any = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Any = in_proj_bias[-config.hidden_size :] def __snake_case( _lowerCAmelCase ) -> List[str]: snake_case__ : Optional[Any] = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: snake_case__ : List[str] = dct.pop(SCREAMING_SNAKE_CASE_ ) snake_case__ : List[Any] = val def __snake_case( ) -> Union[str, Any]: snake_case__ : str = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Optional[int] = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=True ) -> List[Any]: snake_case__ : str = ViTConfig() # patch_size if model_name[-1] == "8": snake_case__ : Dict = 8 # set labels if required if not base_model: snake_case__ : Dict = 1_000 snake_case__ : Any = """huggingface/label-files""" snake_case__ : Dict = """imagenet-1k-id2label.json""" snake_case__ : Optional[Any] = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : int = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} snake_case__ : List[str] = idalabel snake_case__ : int = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: snake_case__ : List[Any] = 384 snake_case__ : Any = 1_536 snake_case__ : Tuple = 12 snake_case__ : Optional[int] = 6 # load original model from torch hub snake_case__ : Optional[int] = torch.hub.load("""facebookresearch/dino:main""" , SCREAMING_SNAKE_CASE_ ) original_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : List[str] = original_model.state_dict() if base_model: remove_classification_head_(SCREAMING_SNAKE_CASE_ ) snake_case__ : Any = create_rename_keys(SCREAMING_SNAKE_CASE_ , base_model=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_ , SCREAMING_SNAKE_CASE_ ) # load HuggingFace model if base_model: snake_case__ : Optional[int] = ViTModel(SCREAMING_SNAKE_CASE_ , add_pooling_layer=SCREAMING_SNAKE_CASE_ ).eval() else: snake_case__ : int = ViTForImageClassification(SCREAMING_SNAKE_CASE_ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check outputs on an image, prepared by ViTImageProcessor snake_case__ : List[str] = ViTImageProcessor() snake_case__ : List[str] = image_processor(images=prepare_img() , return_tensors="""pt""" ) snake_case__ : Any = encoding["""pixel_values"""] snake_case__ : int = model(SCREAMING_SNAKE_CASE_ ) if base_model: snake_case__ : Any = original_model(SCREAMING_SNAKE_CASE_ ) assert torch.allclose(SCREAMING_SNAKE_CASE_ , outputs.last_hidden_state[:, 0, :] , atol=1e-1 ) else: snake_case__ : int = original_model(SCREAMING_SNAKE_CASE_ ) assert logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE_ , outputs.logits , atol=1e-3 ) 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 __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="dino_vitb16", type=str, help="Name of the model trained with DINO you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--base_model", action="store_true", help="Whether to only convert the base model (no projection head weights).", ) parser.set_defaults(base_model=True) __a = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
35
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class UpperCamelCase__ ( snake_case__ , snake_case__ , unittest.TestCase): UpperCAmelCase__ : str = IFPipeline UpperCAmelCase__ : List[Any] = TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""} UpperCAmelCase__ : Any = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase__ : Dict = PipelineTesterMixin.required_optional_params - {"""latents"""} def lowercase_ ( self :Tuple ) -> List[Any]: '''simple docstring''' return self._get_dummy_components() def lowercase_ ( self :str , _A :int , _A :Optional[int]=0 ) -> Optional[Any]: '''simple docstring''' if str(_A ).startswith('mps' ): __A = torch.manual_seed(_A ) else: __A = torch.Generator(device=_A ).manual_seed(_A ) __A = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def lowercase_ ( self :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' ) def lowercase_ ( self :int ) -> Optional[int]: '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def lowercase_ ( self :Optional[Any] ) -> str: '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def lowercase_ ( self :Any ) -> Union[str, Any]: '''simple docstring''' self._test_save_load_local() def lowercase_ ( self :Dict ) -> List[str]: '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def lowercase_ ( self :Tuple ) -> Dict: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class UpperCamelCase__ ( unittest.TestCase): def lowercase_ ( self :Tuple ) -> str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self :Dict ) -> Optional[int]: '''simple docstring''' __A = IFPipeline.from_pretrained('DeepFloyd/IF-I-XL-v1.0' , variant='fp16' , torch_dtype=torch.floataa ) __A = IFSuperResolutionPipeline.from_pretrained( 'DeepFloyd/IF-II-L-v1.0' , variant='fp16' , torch_dtype=torch.floataa , text_encoder=_A , tokenizer=_A ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('cuda' ) __A , __A = pipe_a.encode_prompt('anime turtle' , device='cuda' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() __A = None __A = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_A , _A , _A , _A ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img __A = IFImgaImgPipeline(**pipe_a.components ) __A = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_A , _A , _A , _A ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting __A = IFInpaintingPipeline(**pipe_a.components ) __A = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_A , _A , _A , _A ) def lowercase_ ( self :Optional[Any] , _A :Dict , _A :int , _A :Optional[Any] , _A :Dict ) -> Dict: '''simple docstring''' _start_torch_memory_measurement() __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , num_inference_steps=2 , generator=_A , output_type='np' , ) __A = output.images[0] assert image.shape == (64, 64, 3) __A = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy' ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __A = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , generator=_A , num_inference_steps=2 , output_type='np' , ) __A = output.images[0] assert image.shape == (256, 256, 3) __A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy' ) assert_mean_pixel_difference(_A , _A ) def lowercase_ ( self :Union[str, Any] , _A :Tuple , _A :Tuple , _A :str , _A :Optional[int] ) -> List[str]: '''simple docstring''' _start_torch_memory_measurement() __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , num_inference_steps=2 , generator=_A , output_type='np' , ) __A = output.images[0] assert image.shape == (64, 64, 3) __A = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy' ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_A ) __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __A = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , original_image=_A , generator=_A , num_inference_steps=2 , output_type='np' , ) __A = output.images[0] assert image.shape == (256, 256, 3) __A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy' ) assert_mean_pixel_difference(_A , _A ) def lowercase_ ( self :Tuple , _A :Dict , _A :Optional[Any] , _A :Optional[int] , _A :Dict ) -> str: '''simple docstring''' _start_torch_memory_measurement() __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(_A ) __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , mask_image=_A , num_inference_steps=2 , generator=_A , output_type='np' , ) __A = output.images[0] assert image.shape == (64, 64, 3) __A = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy' ) assert_mean_pixel_difference(_A , _A ) # pipeline 2 _start_torch_memory_measurement() __A = torch.Generator(device='cpu' ).manual_seed(0 ) __A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_A ) __A = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_A ) __A = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(_A ) __A = pipe_a( prompt_embeds=_A , negative_prompt_embeds=_A , image=_A , mask_image=_A , original_image=_A , generator=_A , num_inference_steps=2 , output_type='np' , ) __A = output.images[0] assert image.shape == (256, 256, 3) __A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 __A = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy' ) assert_mean_pixel_difference(_A , _A ) def snake_case ( )-> Union[str, Any]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
161
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 UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 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, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 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" , )
92
0
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE ): # noqa: E741 """simple docstring""" UpperCamelCase = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase = 0 UpperCamelCase = [0] * n UpperCamelCase = [False] * n UpperCamelCase = [False] * n def dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if parent == root: out_edge_count += 1 UpperCamelCase = True UpperCamelCase = at for to in l[at]: if to == parent: pass elif not visited[to]: UpperCamelCase = dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: UpperCamelCase = True # AP found via cycle if at == low[to]: UpperCamelCase = True else: UpperCamelCase = min(low[at] , SCREAMING_SNAKE_CASE_ ) return out_edge_count for i in range(SCREAMING_SNAKE_CASE_ ): if not visited[i]: UpperCamelCase = 0 UpperCamelCase = dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , -1 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase = out_edge_count > 1 for x in range(len(SCREAMING_SNAKE_CASE_ ) ): if is_art[x] is True: print(SCREAMING_SNAKE_CASE_ ) # Adjacency list of graph lowerCAmelCase__ = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
153
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
0
"""simple docstring""" def __lowerCAmelCase ( lowercase : list ) -> List[str]: """simple docstring""" if len(SCREAMING_SNAKE_CASE_ ) <= 1: return [tuple(SCREAMING_SNAKE_CASE_ )] snake_case : str = [] def generate(lowercase : int , lowercase : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , SCREAMING_SNAKE_CASE_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even snake_case ,snake_case : List[Any] = arr[k - 1], arr[i] else: # k is odd snake_case ,snake_case : Dict = arr[k - 1], arr[0] generate(k - 1 , SCREAMING_SNAKE_CASE_ ) generate(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) return res if __name__ == "__main__": __snake_case = input("""Enter numbers separated by a comma:\n""").strip() __snake_case = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
203
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 UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = 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) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 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. __lowerCAmelCase = [ "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 , )
92
0
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow a : Tuple = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ 'text-classification', 'language-modeling', 'summarization', 'token-classification', 'question-answering', ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) a : str = logging.getLogger() def __magic_name__ ( ) -> Any: '''simple docstring''' snake_case_ = argparse.ArgumentParser() parser.add_argument('''-f''' ) snake_case_ = parser.parse_args() return args.f def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase="eval" ) -> Tuple: '''simple docstring''' snake_case_ = os.path.join(SCREAMING_SNAKE_CASE_, F"{split}_results.json" ) if os.path.exists(SCREAMING_SNAKE_CASE_ ): with open(SCREAMING_SNAKE_CASE_, '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE_ ) raise ValueError(F"can't find {path}" ) a : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class a ( snake_case__ ): def A_ ( self : str ): snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --eval_steps=2\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n ".split() with patch.object(_A , '''argv''' , _A ): run_flax_glue.main() snake_case_ = get_results(_A ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def A_ ( self : Optional[Any] ): snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_clm_flax.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --block_size 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n ".split() with patch.object(_A , '''argv''' , _A ): run_clm_flax.main() snake_case_ = get_results(_A ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def A_ ( self : Union[str, Any] ): snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_summarization.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --test_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=8\n --do_train\n --do_eval\n --do_predict\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --predict_with_generate\n ".split() with patch.object(_A , '''argv''' , _A ): run_summarization_flax.main() snake_case_ = get_results(_A , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def A_ ( self : Union[str, Any] ): snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_mlm.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --logging_steps 2 --eval_steps 2\n --do_train\n --do_eval\n --num_train_epochs=1\n ".split() with patch.object(_A , '''argv''' , _A ): run_mlm_flax.main() snake_case_ = get_results(_A ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def A_ ( self : Optional[Any] ): snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_t5_mlm_flax.py\n --model_name_or_path t5-small\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n ".split() with patch.object(_A , '''argv''' , _A ): run_ta_mlm_flax.main() snake_case_ = get_results(_A ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def A_ ( self : Optional[Any] ): snake_case_ = 7 if get_gpu_count() > 1 else 2 snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_flax_ner.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --do_train\n --do_eval\n --warmup_steps=2\n --learning_rate=2e-4\n --logging_steps 2 --eval_steps 2\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n ".split() with patch.object(_A , '''argv''' , _A ): run_flax_ner.main() snake_case_ = get_results(_A ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def A_ ( self : Optional[Any] ): snake_case_ = self.get_auto_remove_tmp_dir() snake_case_ = F"\n run_qa.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=2\n --do_train\n --do_eval\n --logging_steps 2 --eval_steps 2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n ".split() with patch.object(_A , '''argv''' , _A ): run_qa.main() snake_case_ = get_results(_A ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
56
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ): return x return (x, x) @require_tf class a__ : def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase = VisionTextDualEncoderConfig.from_vision_text_configs(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = after_output[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = np.abs((a - b) ).max() self.assertLessEqual(_A , _A , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_save_load(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_pretrained_model_and_inputs() __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = after_outputs[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFViTModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFViTModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFDeiTModel(_A , name="vision_model" ) __lowerCAmelCase = TFRobertaModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFDeiTModelTester(self ) __lowerCAmelCase = TFRobertaModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = clip_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=_A ) __lowerCAmelCase = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __lowerCAmelCase = processor( text=["una foto di un gatto", "una foto di un cane"] , images=_A , padding=_A , return_tensors="np" ) __lowerCAmelCase = model(**_A ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __lowerCAmelCase = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , _A , atol=1E-3 ) )
92
0
'''simple docstring''' import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int a_ : Any = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class __UpperCamelCase ( datasets.BuilderConfig ): lowercase : Optional[datasets.Features] =None def a_ ( __snake_case : "pyspark.sql.DataFrame" , __snake_case : List[int] , ) -> Dict: """simple docstring""" import pyspark def generate_fn(): lowerCamelCase_ =df.select('''*''' , pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) ) for partition_id in partition_order: lowerCamelCase_ =df_with_partition_id.select('''*''' ).where(F'''part_id = {partition_id}''' ).drop('''part_id''' ) lowerCamelCase_ =partition_df.collect() lowerCamelCase_ =0 for row in rows: yield F'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class __UpperCamelCase ( _BaseExamplesIterable ): def __init__( self, lowerCAmelCase, lowerCAmelCase=None, ): """simple docstring""" lowerCamelCase_ =df lowerCamelCase_ =partition_order or range(self.df.rdd.getNumPartitions() ) lowerCamelCase_ =_generate_iterable_examples(self.df, self.partition_order ) def __iter__( self ): """simple docstring""" yield from self.generate_examples_fn() def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(_A ) return SparkExamplesIterable(self.df, partition_order=_A ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =self.split_shard_indices_by_worker(_A, _A ) return SparkExamplesIterable(self.df, partition_order=_A ) @property def lowercase__ ( self ): """simple docstring""" return len(self.partition_order ) class __UpperCamelCase ( datasets.DatasetBuilder ): lowercase : Optional[Any] =SparkConfig def __init__( self, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" import pyspark lowerCamelCase_ =pyspark.sql.SparkSession.builder.getOrCreate() lowerCamelCase_ =df lowerCamelCase_ =working_dir super().__init__( cache_dir=_A, config_name=str(self.df.semanticHash() ), **_A, ) def lowercase__ ( self ): """simple docstring""" def create_cache_and_write_probe(lowerCAmelCase ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir, exist_ok=_A ) lowerCamelCase_ =os.path.join(self._cache_dir, '''fs_test''' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(_A, '''a''' ) return [probe_file] if self._spark.conf.get('''spark.master''', '''''' ).startswith('''local''' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: lowerCamelCase_ =( self._spark.sparkContext.parallelize(range(1 ), 1 ).mapPartitions(_A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir''' ) def lowercase__ ( self ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" import pyspark def get_arrow_batch_size(lowerCAmelCase ): for batch in it: yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]} ) lowerCamelCase_ =self.df.count() lowerCamelCase_ =df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. lowerCamelCase_ =( self.df.limit(_A ) .repartition(1 ) .mapInArrow(_A, '''batch_bytes: long''' ) .agg(pyspark.sql.functions.sum('''batch_bytes''' ).alias('''sample_bytes''' ) ) .collect()[0] .sample_bytes / sample_num_rows ) lowerCamelCase_ =approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. lowerCamelCase_ =min(_A, int(approx_total_size / max_shard_size ) ) lowerCamelCase_ =self.df.repartition(_A ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, ): """simple docstring""" import pyspark lowerCamelCase_ =ParquetWriter if file_format == '''parquet''' else ArrowWriter lowerCamelCase_ =os.path.join(self._working_dir, os.path.basename(_A ) ) if self._working_dir else fpath lowerCamelCase_ =file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. lowerCamelCase_ =self.config.features lowerCamelCase_ =self._writer_batch_size lowerCamelCase_ =self._fs.storage_options def write_arrow(lowerCAmelCase ): # Within the same SparkContext, no two task attempts will share the same attempt ID. lowerCamelCase_ =pyspark.TaskContext().taskAttemptId() lowerCamelCase_ =next(_A, _A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]], names=['''task_id''', '''num_examples''', '''num_bytes'''], ) lowerCamelCase_ =0 lowerCamelCase_ =writer_class( features=_A, path=working_fpath.replace('''SSSSS''', f'''{shard_id:05d}''' ).replace('''TTTTT''', f'''{task_id:05d}''' ), writer_batch_size=_A, storage_options=_A, embed_local_files=_A, ) lowerCamelCase_ =pa.Table.from_batches([first_batch] ) writer.write_table(_A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: lowerCamelCase_, lowerCamelCase_ =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]], names=['''task_id''', '''num_examples''', '''num_bytes'''], ) shard_id += 1 lowerCamelCase_ =writer_class( features=writer._features, path=working_fpath.replace('''SSSSS''', f'''{shard_id:05d}''' ).replace('''TTTTT''', f'''{task_id:05d}''' ), writer_batch_size=_A, storage_options=_A, embed_local_files=_A, ) lowerCamelCase_ =pa.Table.from_batches([batch] ) writer.write_table(_A ) if writer._num_bytes > 0: lowerCamelCase_, lowerCamelCase_ =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]], names=['''task_id''', '''num_examples''', '''num_bytes'''], ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(_A ) ): lowerCamelCase_ =os.path.join(os.path.dirname(_A ), os.path.basename(_A ) ) shutil.move(_A, _A ) lowerCamelCase_ =( self.df.mapInArrow(_A, '''task_id: long, num_examples: long, num_bytes: long''' ) .groupBy('''task_id''' ) .agg( pyspark.sql.functions.sum('''num_examples''' ).alias('''total_num_examples''' ), pyspark.sql.functions.sum('''num_bytes''' ).alias('''total_num_bytes''' ), pyspark.sql.functions.count('''num_bytes''' ).alias('''num_shards''' ), pyspark.sql.functions.collect_list('''num_examples''' ).alias('''shard_lengths''' ), ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = "arrow", lowerCAmelCase = None, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" self._validate_cache_dir() lowerCamelCase_ =convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(_A ) lowerCamelCase_ =not is_remote_filesystem(self._fs ) lowerCamelCase_ =os.path.join if is_local else posixpath.join lowerCamelCase_ ='''-TTTTT-SSSSS-of-NNNNN''' lowerCamelCase_ =f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' lowerCamelCase_ =path_join(self._output_dir, _A ) lowerCamelCase_ =0 lowerCamelCase_ =0 lowerCamelCase_ =0 lowerCamelCase_ =[] lowerCamelCase_ =[] for task_id, content in self._prepare_split_single(_A, _A, _A ): ( ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ( lowerCamelCase_ ), ) =content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(_A ) lowerCamelCase_ =total_num_examples lowerCamelCase_ =total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: lowerCamelCase_ =all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. lowerCamelCase_ =self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, ): rename( _A, fpath.replace('''SSSSS''', f'''{shard_id:05d}''' ).replace('''TTTTT''', f'''{task_id:05d}''' ), fpath.replace('''TTTTT-SSSSS''', f'''{global_shard_id:05d}''' ).replace('''NNNNN''', f'''{total_shards:05d}''' ), ) lowerCamelCase_ =[] lowerCamelCase_ =0 for i in range(len(_A ) ): lowerCamelCase_, lowerCamelCase_ =task_id_and_num_shards[i] for shard_id in range(_A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(_A, len(_A ) ).map(lambda lowerCAmelCase : _rename_shard(*_A ) ).collect() else: # don't use any pattern lowerCamelCase_ =0 lowerCamelCase_ =task_id_and_num_shards[0][0] self._rename( fpath.replace('''SSSSS''', f'''{shard_id:05d}''' ).replace('''TTTTT''', f'''{task_id:05d}''' ), fpath.replace(_A, '''''' ), ) def lowercase__ ( self, lowerCAmelCase, ): """simple docstring""" return SparkExamplesIterable(self.df )
75
import json import os import torch from diffusers import UNetaDModel os.makedirs("""hub/hopper-medium-v2/unet/hor32""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/unet/hor128""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/value_function""", exist_ok=True) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): if hor == 1_28: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 64, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") __lowerCAmelCase = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) __lowerCAmelCase = model.state_dict() __lowerCAmelCase = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 6_55_36, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 1_28, 2_56), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 6_55_36, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } __lowerCAmelCase = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) __lowerCAmelCase = model __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
92
0
"""simple docstring""" from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder _UpperCamelCase : List[str] = datasets.utils.logging.get_logger(__name__) class a ( folder_based_builder.FolderBasedBuilderConfig ): UpperCAmelCase_ : bool =None UpperCAmelCase_ : bool =None class a ( folder_based_builder.FolderBasedBuilder ): UpperCAmelCase_ : int =datasets.Audio() UpperCAmelCase_ : Optional[Any] ="""audio""" UpperCAmelCase_ : str =AudioFolderConfig UpperCAmelCase_ : List[str] # definition at the bottom of the script UpperCAmelCase_ : Union[str, Any] =AudioClassification(audio_column="audio", label_column="label" ) _UpperCamelCase : str = [ '.aiff', '.au', '.avr', '.caf', '.flac', '.htk', '.svx', '.mat4', '.mat5', '.mpc2k', '.ogg', '.paf', '.pvf', '.raw', '.rf64', '.sd2', '.sds', '.ircam', '.voc', '.w64', '.wav', '.nist', '.wavex', '.wve', '.xi', '.mp3', '.opus', ] _UpperCamelCase : List[Any] = AUDIO_EXTENSIONS
220
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = metric_id class a__ : _a : Optional[int] = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): if "tmp_path" in args: __lowerCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="https://huggingface.co/docs/evaluate" ): func(*SCREAMING_SNAKE_CASE_ )
92
0
def __lowerCAmelCase ( a__ , a__ ) -> List[Any]: __a = len(SCREAMING_SNAKE_CASE_ ) print('''The following activities are selected:''' ) # The first activity is always selected __a = 0 print(SCREAMING_SNAKE_CASE_ , end=''',''' ) # Consider rest of the activities for j in range(SCREAMING_SNAKE_CASE_ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(SCREAMING_SNAKE_CASE_ , end=''',''' ) __a = j if __name__ == "__main__": import doctest doctest.testmod() A : List[str] = [1, 3, 0, 5, 8, 5] A : Optional[Any] = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
6
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
0
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__ : Tuple = 1.054_571_817e-34 # unit of ℏ : J * s A__ : int = 3e8 # unit of c : m * s^-1 def a ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' 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: lowercase__ = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: lowercase__ = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: lowercase__ = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * 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()
207
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCamelCase__ = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' from __future__ import annotations def lowerCamelCase__ ( _A ): a : List[str] = 0.00 a : List[Any] = 0 for resistor in resistors: if resistor <= 0: a : int = f"""Resistor at index {index} has a negative or zero value!""" raise ValueError(SCREAMING_SNAKE_CASE_ ) first_sum += 1 / float(SCREAMING_SNAKE_CASE_ ) index += 1 return 1 / first_sum def lowerCamelCase__ ( _A ): a : Optional[Any] = 0.00 a : Any = 0 for resistor in resistors: sum_r += resistor if resistor < 0: a : Dict = f"""Resistor at index {index} has a negative value!""" raise ValueError(SCREAMING_SNAKE_CASE_ ) index += 1 return sum_r if __name__ == "__main__": import doctest doctest.testmod()
297
import argparse import os import re import packaging.version UpperCamelCase__ = """examples/""" UpperCamelCase__ = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCamelCase__ = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCamelCase__ = """README.md""" def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = re_pattern.sub(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , pattern="examples" ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(SCREAMING_SNAKE_CASE_ ) def _a ( ): with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(SCREAMING_SNAKE_CASE_ ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any]=False ): __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ , patch=SCREAMING_SNAKE_CASE_ ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _a ( ): __lowerCAmelCase = get_version() __lowerCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCamelCase__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
92
0
from ..utils import DummyObject, requires_backends class __lowercase ( metaclass=snake_case__ ): """simple docstring""" UpperCamelCase : List[str] = ["""keras_nlp"""] def __init__( self , *A , **A ) -> Tuple: '''simple docstring''' requires_backends(self , ["""keras_nlp"""] )
252
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 a__ ( snake_case__ , unittest.TestCase ): _a : Dict = KandinskyImgaImgPipeline _a : List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] _a : str = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] _a : List[Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _a : int = False @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim * 4 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 1_0_0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) __lowerCAmelCase = MultilingualCLIP(_A ) __lowerCAmelCase = text_encoder.eval() return text_encoder @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = { "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, } __lowerCAmelCase = UNetaDConditionModel(**_A ) return model @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return { "block_out_channels": [3_2, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_unet __lowerCAmelCase = self.dummy_movq __lowerCAmelCase = { "num_train_timesteps": 1_0_0_0, "beta_schedule": "linear", "beta_start": 0.0_00_85, "beta_end": 0.0_12, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } __lowerCAmelCase = DDIMScheduler(**_A ) __lowerCAmelCase = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_A ) # create init_image __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCAmelCase = Image.fromarray(np.uinta(_A ) ).convert("RGB" ).resize((2_5_6, 2_5_6) ) if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "horse", "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 6_4, "width": 6_4, "num_inference_steps": 1_0, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "cpu" __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = self.pipeline_class(**_A ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __lowerCAmelCase = pipe(**self.get_dummy_inputs(_A ) ) __lowerCAmelCase = output.images __lowerCAmelCase = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCAmelCase = np.array( [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33] ) 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 a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_img2img_frog.npy" ) __lowerCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __lowerCAmelCase = "A red cartoon frog, 4k" __lowerCAmelCase = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __lowerCAmelCase = KandinskyImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase , __lowerCAmelCase = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __lowerCAmelCase = pipeline( _A , image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A )
92
0
'''simple docstring''' class UpperCAmelCase_ : """simple docstring""" def __init__( self : List[str] , snake_case_ : Dict ): snake_case__ : Tuple = len(_A ) snake_case__ : List[str] = [0] * len_array if len_array > 0: snake_case__ : int = array[0] for i in range(1 , _A ): snake_case__ : Union[str, Any] = self.prefix_sum[i - 1] + array[i] def lowerCamelCase ( self : Any , snake_case_ : List[str] , snake_case_ : Optional[int] ): if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def lowerCamelCase ( self : Dict , snake_case_ : Optional[Any] ): snake_case__ : Any = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(_A ) return False if __name__ == "__main__": import doctest doctest.testmod()
35
class a__ ( snake_case__ ): pass class a__ ( snake_case__ ): pass class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [ [], [], [], ] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(_A ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): """simple docstring""" return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if len(self.queue ) == 1_0_0: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(_A ) return data def __str__( self ): """simple docstring""" return str(self.queue ) def _a ( ): __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
92
0
'''simple docstring''' import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class UpperCamelCase__ ( snake_case__): def __init__( self :str , _A :Optional[int] , _A :List[str] , _A :Optional[Any] , _A :int , ) -> Tuple: '''simple docstring''' super().__init__() __A = value_function __A = unet __A = scheduler __A = env __A = env.get_dataset() __A = {} for key in self.data.keys(): try: __A = self.data[key].mean() except: # noqa: E722 pass __A = {} for key in self.data.keys(): try: __A = self.data[key].std() except: # noqa: E722 pass __A = env.observation_space.shape[0] __A = env.action_space.shape[0] def lowercase_ ( self :List[Any] , _A :int , _A :Optional[int] ) -> Dict: '''simple docstring''' return (x_in - self.means[key]) / self.stds[key] def lowercase_ ( self :Union[str, Any] , _A :Dict , _A :Union[str, Any] ) -> Any: '''simple docstring''' return x_in * self.stds[key] + self.means[key] def lowercase_ ( self :str , _A :Dict ) -> Tuple: '''simple docstring''' if type(_A ) is dict: return {k: self.to_torch(_A ) for k, v in x_in.items()} elif torch.is_tensor(_A ): return x_in.to(self.unet.device ) return torch.tensor(_A , device=self.unet.device ) def lowercase_ ( self :Any , _A :int , _A :List[Any] , _A :List[Any] ) -> Dict: '''simple docstring''' for key, val in cond.items(): __A = val.clone() return x_in def lowercase_ ( self :str , _A :Dict , _A :Tuple , _A :List[Any] , _A :Union[str, Any] ) -> List[str]: '''simple docstring''' __A = x.shape[0] __A = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model __A = torch.full((batch_size,) , _A , device=self.unet.device , dtype=torch.long ) for _ in range(_A ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models __A = self.value_function(x.permute(0 , 2 , 1 ) , _A ).sample __A = torch.autograd.grad([y.sum()] , [x] )[0] __A = self.scheduler._get_variance(_A ) __A = torch.exp(0.5 * posterior_variance ) __A = model_std * grad __A = 0 __A = x.detach() __A = x + scale * grad __A = self.reset_xa(_A , _A , self.action_dim ) __A = self.unet(x.permute(0 , 2 , 1 ) , _A ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg __A = self.scheduler.step(_A , _A , _A , predict_epsilon=_A )['prev_sample'] # apply conditions to the trajectory (set the initial state) __A = self.reset_xa(_A , _A , self.action_dim ) __A = self.to_torch(_A ) return x, y def __call__( self :List[str] , _A :Union[str, Any] , _A :str=64 , _A :Optional[int]=32 , _A :Union[str, Any]=2 , _A :List[str]=0.1 ) -> List[str]: '''simple docstring''' __A = self.normalize(_A , 'observations' ) __A = obs[None].repeat(_A , axis=0 ) __A = {0: self.to_torch(_A )} __A = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) __A = randn_tensor(_A , device=self.unet.device ) __A = self.reset_xa(_A , _A , self.action_dim ) __A = self.to_torch(_A ) # run the diffusion process __A , __A = self.run_diffusion(_A , _A , _A , _A ) # sort output trajectories by value __A = y.argsort(0 , descending=_A ).squeeze() __A = x[sorted_idx] __A = sorted_values[:, :, : self.action_dim] __A = actions.detach().cpu().numpy() __A = self.de_normalize(_A , key='actions' ) # select the action with the highest value if y is not None: __A = 0 else: # if we didn't run value guiding, select a random action __A = np.random.randint(0 , _A ) __A = denorm_actions[selected_index, 0] return denorm_actions
161
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a__ : def __init__( self , _A , _A=1_3 , _A=3_0 , _A=2 , _A=3 , _A=True , _A=True , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1_0 , _A=0.02 , _A=3 , _A=None , _A=2 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = scope __lowerCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 2 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTForMaskedImageModeling(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForMaskedImageModeling(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) _a : int = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) _a : Optional[Any] = False _a : Tuple = False _a : Tuple = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=False ): """simple docstring""" __lowerCAmelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.model_tester.is_training: return __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __lowerCAmelCase = False __lowerCAmelCase = True for model_class in self.all_model_classes: if model_class in get_values(_A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __lowerCAmelCase = model_class(_A ) model.gradient_checkpointing_enable() model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_A ), *get_values(_A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type['title']}""" ): __lowerCAmelCase = problem_type["title"] __lowerCAmelCase = problem_type["num_labels"] __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) if problem_type["num_labels"] > 1: __lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) __lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_A ) as warning_list: __lowerCAmelCase = model(**_A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DeiTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _a ( ): __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( _A ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ).to(_A ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**_A ) # verify the logits __lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _A ) __lowerCAmelCase = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ) __lowerCAmelCase = inputs.pixel_values.to(_A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowerCAmelCase = model(_A )
92
0
"""simple docstring""" import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') lowerCAmelCase__ = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: lowerCAmelCase__ = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowerCAmelCase__ = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f'''pip install -r transformers/examples/{example_dir}/requirements.txt''']) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f'''python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}''']) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
153
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
92
0
"""simple docstring""" from __future__ import annotations from collections.abc import Callable def __lowerCAmelCase ( lowercase : Callable[[int | float], int | float] , lowercase : int | float , lowercase : int | float , lowercase : int = 100 , ) -> int: """simple docstring""" snake_case : Optional[int] = x_start snake_case : Optional[int] = fnc(SCREAMING_SNAKE_CASE_ ) snake_case : Dict = 0.0 for _ in range(SCREAMING_SNAKE_CASE_ ): # Approximates small segments of curve as linear and solve # for trapezoidal area snake_case : List[str] = (x_end - x_start) / steps + xa snake_case : Union[str, Any] = fnc(SCREAMING_SNAKE_CASE_ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step snake_case : int = xa snake_case : str = fxa return area if __name__ == "__main__": def __lowerCAmelCase ( lowercase : Tuple ) -> Optional[int]: """simple docstring""" return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __snake_case = 10 while i <= 100000: print(F'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
203
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
92
0
'''simple docstring''' from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract a : Dict = logging.get_logger(__name__) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> List[Any]: '''simple docstring''' return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> List[str]: '''simple docstring''' snake_case_ = to_pil_image(SCREAMING_SNAKE_CASE_ ) snake_case_ ,snake_case_ = pil_image.size snake_case_ = pytesseract.image_to_data(SCREAMING_SNAKE_CASE_, lang=SCREAMING_SNAKE_CASE_, output_type='''dict''', config=SCREAMING_SNAKE_CASE_ ) snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates snake_case_ = [idx for idx, word in enumerate(SCREAMING_SNAKE_CASE_ ) if not word.strip()] snake_case_ = [word for idx, word in enumerate(SCREAMING_SNAKE_CASE_ ) if idx not in irrelevant_indices] snake_case_ = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE_ ) if idx not in irrelevant_indices] snake_case_ = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE_ ) if idx not in irrelevant_indices] snake_case_ = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE_ ) if idx not in irrelevant_indices] snake_case_ = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE_ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format snake_case_ = [] for x, y, w, h in zip(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): snake_case_ = [x, y, x + w, y + h] actual_boxes.append(SCREAMING_SNAKE_CASE_ ) # finally, normalize the bounding boxes snake_case_ = [] for box in actual_boxes: normalized_boxes.append(normalize_box(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) ) assert len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a ( snake_case__ ): snake_case_ = ["""pixel_values"""] def __init__( self : List[str] , lowercase_ : Dict = True , lowercase_ : Tuple = None , lowercase_ : Union[str, Any] = PILImageResampling.BILINEAR , lowercase_ : List[str] = True , lowercase_ : Dict = 1 / 255 , lowercase_ : str = True , lowercase_ : List[Any] = None , lowercase_ : List[str] = None , lowercase_ : List[Any] = True , lowercase_ : Optional[Any] = None , lowercase_ : Optional[Any] = "" , **lowercase_ : Optional[int] , ): super().__init__(**_A ) snake_case_ = size if size is not None else {'''height''': 224, '''width''': 224} snake_case_ = get_size_dict(_A ) snake_case_ = do_resize snake_case_ = size snake_case_ = resample snake_case_ = do_rescale snake_case_ = rescale_value snake_case_ = do_normalize snake_case_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN snake_case_ = image_std if image_std is not None else IMAGENET_STANDARD_STD snake_case_ = apply_ocr snake_case_ = ocr_lang snake_case_ = tesseract_config def A_ ( self : Tuple , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : Dict = PILImageResampling.BILINEAR , lowercase_ : List[str] = None , **lowercase_ : str , ): snake_case_ = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) snake_case_ = (size['''height'''], size['''width''']) return resize(_A , size=_A , resample=_A , data_format=_A , **_A ) def A_ ( self : str , lowercase_ : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : int = None , **lowercase_ : Tuple , ): return rescale(_A , scale=_A , data_format=_A , **_A ) def A_ ( self : Union[str, Any] , lowercase_ : Dict , lowercase_ : Optional[Any] , lowercase_ : Any , lowercase_ : Optional[Any] = None , **lowercase_ : Any , ): return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def A_ ( self : List[str] , lowercase_ : int , lowercase_ : Tuple = None , lowercase_ : List[Any] = None , lowercase_ : str=None , lowercase_ : Tuple = None , lowercase_ : Tuple = None , lowercase_ : Optional[int] = None , lowercase_ : List[str] = None , lowercase_ : int = None , lowercase_ : List[str] = None , lowercase_ : List[Any] = None , lowercase_ : List[Any] = None , lowercase_ : Union[str, Any] = None , lowercase_ : List[str] = ChannelDimension.FIRST , **lowercase_ : List[str] , ): snake_case_ = do_resize if do_resize is not None else self.do_resize snake_case_ = size if size is not None else self.size snake_case_ = get_size_dict(_A ) snake_case_ = resample if resample is not None else self.resample snake_case_ = do_rescale if do_rescale is not None else self.do_rescale snake_case_ = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ = do_normalize if do_normalize is not None else self.do_normalize snake_case_ = image_mean if image_mean is not None else self.image_mean snake_case_ = image_std if image_std is not None else self.image_std snake_case_ = apply_ocr if apply_ocr is not None else self.apply_ocr snake_case_ = ocr_lang if ocr_lang is not None else self.ocr_lang snake_case_ = tesseract_config if tesseract_config is not None else self.tesseract_config snake_case_ = make_list_of_images(_A ) if not valid_images(_A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.''' ) # All transformations expect numpy arrays. snake_case_ = [to_numpy_array(_A ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , '''pytesseract''' ) snake_case_ = [] snake_case_ = [] for image in images: snake_case_ ,snake_case_ = apply_tesseract(_A , _A , _A ) words_batch.append(_A ) boxes_batch.append(_A ) if do_resize: snake_case_ = [self.resize(image=_A , size=_A , resample=_A ) for image in images] if do_rescale: snake_case_ = [self.rescale(image=_A , scale=_A ) for image in images] if do_normalize: snake_case_ = [self.normalize(image=_A , mean=_A , std=_A ) for image in images] snake_case_ = [to_channel_dimension_format(_A , _A ) for image in images] snake_case_ = BatchFeature(data={'''pixel_values''': images} , tensor_type=_A ) if apply_ocr: snake_case_ = words_batch snake_case_ = boxes_batch return data
56
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType UpperCamelCase__ = get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {ckpt_dir}""" ) __lowerCAmelCase = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Model saved to {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " "initializing FSDP object" ) return __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) if F"""{MODEL_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading model from {ckpt_dir}""" ) __lowerCAmelCase = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) __lowerCAmelCase = state_dict["model"] logger.info(F"""Model loaded from {ckpt_dir}""" ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {output_optimizer_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state saved in {output_optimizer_file}""" ) else: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {ckpt_dir}""" ) dist_cp.save_state_dict( state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Optimizer state saved in {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading Optimizer state from {input_optimizer_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state loaded from {input_optimizer_file}""" ) else: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) if F"""{OPTIMIZER_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading Optimizer from {ckpt_dir}""" ) __lowerCAmelCase = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) __lowerCAmelCase = optim_state["optimizer"] logger.info(F"""Optimizer loaded from {ckpt_dir}""" ) __lowerCAmelCase = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
92
0
'''simple docstring''' from __future__ import annotations a_ : List[Any] = 10 def a_ ( __snake_case : list[int] ) -> List[str]: """simple docstring""" lowerCamelCase_ =1 lowerCamelCase_ =max(SCREAMING_SNAKE_CASE_ ) while placement <= max_digit: # declare and initialize empty buckets lowerCamelCase_ =[[] for _ in range(SCREAMING_SNAKE_CASE_ )] # split list_of_ints between the buckets for i in list_of_ints: lowerCamelCase_ =int((i / placement) % RADIX ) buckets[tmp].append(SCREAMING_SNAKE_CASE_ ) # put each buckets' contents into list_of_ints lowerCamelCase_ =0 for b in range(SCREAMING_SNAKE_CASE_ ): for i in buckets[b]: lowerCamelCase_ =i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
75
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( snake_case__ ): def __init__( self , *_A , _A=None , _A=None , **_A ): """simple docstring""" super().__init__(*_A , **_A ) __lowerCAmelCase = eval_examples __lowerCAmelCase = post_process_function def __SCREAMING_SNAKE_CASE( self , _A = None , _A=None , _A = None , _A = "eval" , **_A , ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = ( gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length ) __lowerCAmelCase = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams ) __lowerCAmelCase = gen_kwargs __lowerCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset __lowerCAmelCase = self.get_eval_dataloader(_A ) __lowerCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default __lowerCAmelCase = self.post_process_function(_A , _A , _A ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) else: __lowerCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_A ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __lowerCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , _A ) return metrics def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=None , _A = "test" , **_A ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output __lowerCAmelCase = self.post_process_function(_A , _A , _A , "predict" ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_A )
92
0
"""simple docstring""" class a ( snake_case__ ): pass class a ( snake_case__ ): pass class a : def __init__( self ): lowercase = [ [], [], [], ] def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase ): try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(_A ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def UpperCamelCase_ ( self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self ): return "\n".join(F'Priority {i}: {q}' for i, q in enumerate(self.queues ) ) class a : def __init__( self ): lowercase = [] def UpperCamelCase_ ( self , _lowerCamelCase ): if len(self.queue ) == 1_0_0: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(_A ) def UpperCamelCase_ ( self ): if not self.queue: raise UnderFlowError('The queue is empty' ) else: lowercase = min(self.queue ) self.queue.remove(_A ) return data def __str__( self ): return str(self.queue ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowercase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
220
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 _a ( SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = filter(lambda SCREAMING_SNAKE_CASE_ : p.requires_grad , model.parameters() ) __lowerCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase__ = logging.getLogger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): if metric == "rouge2": __lowerCAmelCase = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __lowerCAmelCase = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __lowerCAmelCase = "{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." ) __lowerCAmelCase = 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 _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return EarlyStopping( monitor=F"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class a__ ( pl.Callback ): def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = {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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCAmelCase = 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 __lowerCAmelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCAmelCase = od / "test_results.txt" __lowerCAmelCase = 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. __lowerCAmelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCAmelCase = 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 __lowerCAmelCase = metrics[key] if isinstance(_A , torch.Tensor ): __lowerCAmelCase = val.item() __lowerCAmelCase = f"""{key}: {val:.6f}\n""" writer.write(_A ) if not save_generations: return if "preds" in metrics: __lowerCAmelCase = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: __lowerCAmelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCAmelCase = pl_module.model.num_parameters() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
92
0
from __future__ import annotations from scipy.special import comb # type: ignore class __A: def __init__( self , _snake_case ) -> Dict: '''simple docstring''' __a = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __a = len(_A ) - 1 def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> List[Any]: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." __a = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , _A ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(_A ) , 5 ) == 1 return output_values def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> str: '''simple docstring''' assert 0 <= t <= 1, "Time t must be between 0 and 1." __a = self.basis_function(_A ) __a = 0.0 __a = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def SCREAMING_SNAKE_CASE_ ( self , _snake_case = 0.01 ) -> int: '''simple docstring''' from matplotlib import pyplot as plt # type: ignore __a = [] # x coordinates of points to plot __a = [] # y coordinates of points to plot __a = 0.0 while t <= 1: __a = self.bezier_curve_function(_A ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size __a = [i[0] for i in self.list_of_points] __a = [i[1] for i in self.list_of_points] plt.plot( _A , _A , color='''blue''' , label='''Curve of Degree ''' + str(self.degree ) , ) plt.scatter(_A , _A , color='''red''' , label='''Control Points''' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
6
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
92
0
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class _UpperCAmelCase ( snake_case__ ): """simple docstring""" lowercase__ = """""" lowercase__ = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) lowercase__ = None # compression type in fsspec. ex: "gzip" lowercase__ = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : Tuple, lowerCamelCase : Optional[Any] = "", lowerCamelCase : List[str] = None, lowerCamelCase : int = None, **lowerCamelCase : str ): '''simple docstring''' super().__init__(self, **_A ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode lowercase__ = fsspec.open( _A, mode='''rb''', protocol=_A, compression=self.compression, client_kwargs={ '''requote_redirect_url''': False, # see https://github.com/huggingface/datasets/pull/5459 '''trust_env''': True, # Enable reading proxy env variables. **(target_options or {}).pop('''client_kwargs''', {} ), # To avoid issues if it was already passed. }, **(target_options or {}), ) lowercase__ = os.path.basename(self.file.path.split('''::''' )[0] ) lowercase__ = ( self.compressed_name[: self.compressed_name.rindex('''.''' )] if '''.''' in self.compressed_name else self.compressed_name ) lowercase__ = None @classmethod def lowercase__ ( cls : List[str], lowerCamelCase : int ): '''simple docstring''' return super()._strip_protocol(_A ).lstrip('''/''' ) def lowercase__ ( self : Any ): '''simple docstring''' if self.dir_cache is None: lowercase__ = {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name} lowercase__ = {f['''name''']: f} def lowercase__ ( self : Union[str, Any], lowerCamelCase : Union[str, Any] ): '''simple docstring''' return self.file.open().read() def lowercase__ ( self : Any, lowerCamelCase : Optional[int], lowerCamelCase : List[str] = "rb", lowerCamelCase : List[str]=None, lowerCamelCase : List[Any]=True, lowerCamelCase : str=None, **lowerCamelCase : List[Any], ): '''simple docstring''' lowercase__ = self._strip_protocol(_A ) if mode != "rb": raise ValueError(F"""Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'""" ) return self.file.open() class _UpperCAmelCase ( snake_case__ ): """simple docstring""" lowercase__ = """bz2""" lowercase__ = """bz2""" lowercase__ = """.bz2""" class _UpperCAmelCase ( snake_case__ ): """simple docstring""" lowercase__ = """gzip""" lowercase__ = """gzip""" lowercase__ = """.gz""" class _UpperCAmelCase ( snake_case__ ): """simple docstring""" lowercase__ = """lz4""" lowercase__ = """lz4""" lowercase__ = """.lz4""" class _UpperCAmelCase ( snake_case__ ): """simple docstring""" lowercase__ = """xz""" lowercase__ = """xz""" lowercase__ = """.xz""" class _UpperCAmelCase ( snake_case__ ): """simple docstring""" lowercase__ = """zstd""" lowercase__ = """zstd""" lowercase__ = """.zst""" def __init__( self : Tuple, lowerCamelCase : Tuple, lowerCamelCase : Optional[int] = "rb", lowerCamelCase : List[Any] = None, lowerCamelCase : Optional[int] = None, lowerCamelCase : Tuple = DEFAULT_BLOCK_SIZE, **lowerCamelCase : int, ): '''simple docstring''' super().__init__( fo=_A, mode=_A, target_protocol=_A, target_options=_A, block_size=_A, **_A, ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 lowercase__ = self.file.__enter__ class _UpperCAmelCase : """simple docstring""" def __init__( self : Any, lowerCamelCase : List[Any] ): '''simple docstring''' lowercase__ = file_ def __enter__( self : Union[str, Any] ): '''simple docstring''' self._file.__enter__() return self def __exit__( self : Optional[int], *lowerCamelCase : Optional[Any], **lowerCamelCase : int ): '''simple docstring''' self._file.__exit__(*_A, **_A ) def __iter__( self : List[str] ): '''simple docstring''' return iter(self._file ) def lowercase__ ( self : Tuple ): '''simple docstring''' return next(self._file ) def __getattr__( self : Any, lowerCamelCase : int ): '''simple docstring''' return getattr(self._file, _A ) def fixed_enter(*lowerCamelCase : Union[str, Any], **lowerCamelCase : Optional[Any] ): return WrappedFile(_enter(*_A, **_A ) ) lowercase__ = fixed_enter
207
from queue import PriorityQueue from typing import Any import numpy as np def _a ( 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 __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = 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(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = 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_ , ) __lowerCAmelCase = 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: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """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()
92
0
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowerCAmelCase: Tuple = get_logger() lowerCAmelCase: List[Any] = None class a__( TensorFormatter[Mapping, """jax.Array""", Mapping] ): def __init__( self : Union[str, Any] , __snake_case : Any=None , __snake_case : Dict=None , **__snake_case : int ): super().__init__(features=_A ) import jax from jaxlib.xla_client import Device if isinstance(_A , _A ): raise ValueError( F"""Expected {device} to be a `str` not {type(_A )}, as `jaxlib.xla_extension.Device` """ 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) a : Optional[int] = device if isinstance(_A , _A ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: a : Optional[Any] = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"""Device with string identifier {self.device} not listed among the available """ F"""devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default """ F"""device: {str(jax.devices()[0] )}.""" ) a : Tuple = str(jax.devices()[0] ) a : Optional[int] = jnp_array_kwargs @staticmethod def lowercase_ ( ): import jax return {str(_A ): device for device in jax.devices()} def lowercase_ ( self : Dict , __snake_case : Tuple ): import jax import jax.numpy as jnp if isinstance(_A , _A ) and column: if all( isinstance(_A , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(_A , axis=0 ) return column def lowercase_ ( self : Union[str, Any] , __snake_case : Union[str, Any] ): import jax import jax.numpy as jnp if isinstance(_A , (str, bytes, type(_A )) ): return value elif isinstance(_A , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() a : List[str] = {} if isinstance(_A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: a : Union[str, Any] = {'dtype': jnp.intaa} else: a : Dict = {'dtype': jnp.intaa} elif isinstance(_A , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): a : Any = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_A , PIL.Image.Image ): a : str = np.asarray(_A ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: a : Tuple = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(_A , **{**default_dtype, **self.jnp_array_kwargs} ) def lowercase_ ( self : int , __snake_case : Optional[Any] ): import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(_A , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(_A , '__array__' ) and not isinstance(_A , jax.Array ): a : Optional[Any] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_A , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_A ) for substruct in data_struct] ) elif isinstance(_A , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_A ) for substruct in data_struct] ) return self._tensorize(_A ) def lowercase_ ( self : Dict , __snake_case : List[Any] ): return map_nested(self._recursive_tensorize , _A , map_list=_A ) def lowercase_ ( self : Optional[Any] , __snake_case : List[Any] ): a : Tuple = self.numpy_arrow_extractor().extract_row(_A ) a : int = self.python_features_decoder.decode_row(_A ) return self.recursive_tensorize(_A ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Optional[int] = self.numpy_arrow_extractor().extract_column(_A ) a : Dict = self.python_features_decoder.decode_column(_A , pa_table.column_names[0] ) a : Optional[Any] = self.recursive_tensorize(_A ) a : Optional[int] = self._consolidate(_A ) return column def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): a : str = self.numpy_arrow_extractor().extract_batch(_A ) a : Optional[Any] = self.python_features_decoder.decode_batch(_A ) a : Optional[Any] = self.recursive_tensorize(_A ) for column_name in batch: a : int = self._consolidate(batch[column_name] ) return batch
297
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a__ ( snake_case__ ): _a : Optional[int] = """decision_transformer""" _a : Optional[int] = ["""past_key_values"""] _a : Dict = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _A=1_7 , _A=4 , _A=1_2_8 , _A=4_0_9_6 , _A=True , _A=1 , _A=1_0_2_4 , _A=3 , _A=1 , _A=None , _A="relu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1E-5 , _A=0.02 , _A=True , _A=True , _A=5_0_2_5_6 , _A=5_0_2_5_6 , _A=False , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = state_dim __lowerCAmelCase = act_dim __lowerCAmelCase = hidden_size __lowerCAmelCase = max_ep_len __lowerCAmelCase = action_tanh __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = bos_token_id __lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
92
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase : Dict = {"configuration_vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig", "ViTOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = ["ViTFeatureExtractor"] UpperCAmelCase : int = ["ViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[int] = [ "VIT_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTForImageClassification", "ViTForMaskedImageModeling", "ViTModel", "ViTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ "TFViTForImageClassification", "TFViTModel", "TFViTPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : List[str] = [ "FlaxViTForImageClassification", "FlaxViTModel", "FlaxViTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys UpperCAmelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
252
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
0
'''simple docstring''' from __future__ import annotations def __snake_case( _lowerCAmelCase ) -> Any: if not nums: return 0 snake_case__ : List[Any] = nums[0] snake_case__ : Optional[Any] = 0 for num in nums[1:]: snake_case__ , snake_case__ : Optional[Any] = ( max_excluding + num, max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ), ) return max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod()
35
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class UpperCamelCase__ ( snake_case__): UpperCAmelCase__ : List[Any] = ["""image_processor""", """tokenizer"""] UpperCAmelCase__ : int = """OwlViTImageProcessor""" UpperCAmelCase__ : Optional[Any] = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self :Tuple , _A :List[str]=None , _A :Optional[Any]=None , **_A :List[Any] ) -> int: '''simple docstring''' __A = 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 , ) __A = kwargs.pop('feature_extractor' ) __A = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_A , _A ) def __call__( self :Any , _A :int=None , _A :Any=None , _A :Dict=None , _A :int="max_length" , _A :List[str]="np" , **_A :Any ) -> Optional[Any]: '''simple docstring''' if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(_A , _A ) or (isinstance(_A , _A ) and not isinstance(text[0] , _A )): __A = [self.tokenizer(_A , padding=_A , return_tensors=_A , **_A )] elif isinstance(_A , _A ) and isinstance(text[0] , _A ): __A = [] # Maximum number of queries across batch __A = max([len(_A ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(_A ) != max_num_queries: __A = t + [' '] * (max_num_queries - len(_A )) __A = self.tokenizer(_A , padding=_A , return_tensors=_A , **_A ) encodings.append(_A ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": __A = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __A = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp __A = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) __A = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch __A = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) __A = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf __A = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) __A = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) __A = BatchEncoding() __A = input_ids __A = attention_mask if query_images is not None: __A = BatchEncoding() __A = self.image_processor( _A , return_tensors=_A , **_A ).pixel_values __A = query_pixel_values if images is not None: __A = self.image_processor(_A , return_tensors=_A , **_A ) if text is not None and images is not None: __A = image_features.pixel_values return encoding elif query_images is not None and images is not None: __A = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**_A ) , tensor_type=_A ) def lowercase_ ( self :str , *_A :str , **_A :Tuple ) -> Tuple: '''simple docstring''' return self.image_processor.post_process(*_A , **_A ) def lowercase_ ( self :List[str] , *_A :int , **_A :Dict ) -> Any: '''simple docstring''' return self.image_processor.post_process_object_detection(*_A , **_A ) def lowercase_ ( self :int , *_A :Tuple , **_A :int ) -> Any: '''simple docstring''' return self.image_processor.post_process_image_guided_detection(*_A , **_A ) def lowercase_ ( self :Any , *_A :Dict , **_A :List[str] ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.batch_decode(*_A , **_A ) def lowercase_ ( self :int , *_A :Dict , **_A :Union[str, Any] ) -> Optional[int]: '''simple docstring''' return self.tokenizer.decode(*_A , **_A ) @property def lowercase_ ( self :List[str] ) -> Optional[Any]: '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _A , ) return self.image_processor_class @property def lowercase_ ( self :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _A , ) return self.image_processor
161
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 UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 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, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 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" , )
92
0
"""simple docstring""" import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope="session" ) def a__ ( ): """simple docstring""" UpperCamelCase = 10 UpperCamelCase = datasets.Features( { "tokens": datasets.Sequence(datasets.Value("string" ) ), "labels": datasets.Sequence(datasets.ClassLabel(names=["negative", "positive"] ) ), "answers": datasets.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), "id": datasets.Value("int64" ), } ) UpperCamelCase = datasets.Dataset.from_dict( { "tokens": [["foo"] * 5] * n, "labels": [[1] * 5] * n, "answers": [{"answer_start": [97], "text": ["1976"]}] * 10, "id": list(range(SCREAMING_SNAKE_CASE_ ) ), } , features=SCREAMING_SNAKE_CASE_ , ) return dataset @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "file.arrow" ) dataset.map(cache_file_name=SCREAMING_SNAKE_CASE_ ) return filename # FILE_CONTENT + files lowerCAmelCase__ = '''\ Text data. Second line of data.''' @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt" UpperCamelCase = FILE_CONTENT with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return filename @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" import bza UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.bz2" UpperCamelCase = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with bza.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" import gzip UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "file.txt.gz" ) UpperCamelCase = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with gzip.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" if datasets.config.LZ4_AVAILABLE: import lza.frame UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.lz4" UpperCamelCase = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with lza.frame.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" if datasets.config.PY7ZR_AVAILABLE: import pyazr UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.7z" with pyazr.SevenZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as archive: archive.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" import tarfile UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.tar" with tarfile.TarFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.add(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" import lzma UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.xz" UpperCamelCase = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with lzma.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" import zipfile UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.txt.zst" 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(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "file.xml" UpperCamelCase = textwrap.dedent( "\\n <?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <tmx version=\"1.4\">\n <header segtype=\"sentence\" srclang=\"ca\" />\n <body>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 1</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 1</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 2</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 2</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 3</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 3</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 4</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 4</seg></tuv>\n </tu>\n <tu>\n <tuv xml:lang=\"ca\"><seg>Contingut 5</seg></tuv>\n <tuv xml:lang=\"en\"><seg>Content 5</seg></tuv>\n </tu>\n </body>\n </tmx>" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return filename lowerCAmelCase__ = [ {'''col_1''': '''0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''3''', '''col_2''': 3, '''col_3''': 3.0}, ] lowerCAmelCase__ = [ {'''col_1''': '''4''', '''col_2''': 4, '''col_3''': 4.0}, {'''col_1''': '''5''', '''col_2''': 5, '''col_3''': 5.0}, ] lowerCAmelCase__ = { '''col_1''': ['''0''', '''1''', '''2''', '''3'''], '''col_2''': [0, 1, 2, 3], '''col_3''': [0.0, 1.0, 2.0, 3.0], } lowerCAmelCase__ = [ {'''col_3''': 0.0, '''col_1''': '''0''', '''col_2''': 0}, {'''col_3''': 1.0, '''col_1''': '''1''', '''col_2''': 1}, ] lowerCAmelCase__ = [ {'''col_1''': '''s0''', '''col_2''': 0, '''col_3''': 0.0}, {'''col_1''': '''s1''', '''col_2''': 1, '''col_3''': 1.0}, {'''col_1''': '''s2''', '''col_2''': 2, '''col_3''': 2.0}, {'''col_1''': '''s3''', '''col_2''': 3, '''col_3''': 3.0}, ] @pytest.fixture(scope="session" ) def a__ ( ): """simple docstring""" return DATA_DICT_OF_LISTS @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = datasets.Dataset.from_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.arrow" ) dataset.map(cache_file_name=SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.sqlite" ) with contextlib.closing(sqlitea.connect(SCREAMING_SNAKE_CASE_ ) ) as con: UpperCamelCase = con.cursor() cur.execute("CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)" ) for item in DATA: cur.execute("INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)" , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.csv" ) with open(SCREAMING_SNAKE_CASE_ , "w" , newline="" ) as f: UpperCamelCase = csv.DictWriter(SCREAMING_SNAKE_CASE_ , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset2.csv" ) with open(SCREAMING_SNAKE_CASE_ , "w" , newline="" ) as f: UpperCamelCase = csv.DictWriter(SCREAMING_SNAKE_CASE_ , fieldnames=["col_1", "col_2", "col_3"] ) writer.writeheader() for item in DATA: writer.writerow(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" import bza UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.csv.bz2" with open(SCREAMING_SNAKE_CASE_ , "rb" ) as f: UpperCamelCase = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.csv.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(csv_path.replace(".csv" , ".CSV" ) ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(csva_path.replace(".csv" , ".CSV" ) ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.csv.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("main_dir" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("main_dir" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.parquet" ) UpperCamelCase = pa.schema( { "col_1": pa.string(), "col_2": pa.intaa(), "col_3": pa.floataa(), } ) with open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: UpperCamelCase = pq.ParquetWriter(SCREAMING_SNAKE_CASE_ , schema=SCREAMING_SNAKE_CASE_ ) UpperCamelCase = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(SCREAMING_SNAKE_CASE_ ) )] for k in DATA[0]} , schema=SCREAMING_SNAKE_CASE_ ) writer.write_table(SCREAMING_SNAKE_CASE_ ) writer.close() return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) UpperCamelCase = {"data": DATA} with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.json" ) UpperCamelCase = {"data": DATA_DICT_OF_LISTS} with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in DATA: f.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset2.jsonl" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in DATA: f.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset_312.jsonl" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in DATA_312: f.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset-str.jsonl" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in DATA_STR: f.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" import gzip UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.txt.gz" ) with open(SCREAMING_SNAKE_CASE_ , "rb" ) as orig_file: with gzip.open(SCREAMING_SNAKE_CASE_ , "wb" ) as zipped_file: zipped_file.writelines(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" import gzip UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.jsonl.gz" ) with open(SCREAMING_SNAKE_CASE_ , "rb" ) as orig_file: with gzip.open(SCREAMING_SNAKE_CASE_ , "wb" ) as zipped_file: zipped_file.writelines(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("nested" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.jsonl.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("main_dir" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("main_dir" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.jsonl.tar" with tarfile.TarFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.add(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) f.add(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset_nested.jsonl.tar" with tarfile.TarFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.add(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("nested" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = ["0", "1", "2", "3"] UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset.txt" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = ["0", "1", "2", "3"] UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset2.txt" ) with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = ["0", "1", "2", "3"] UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.abc" with open(SCREAMING_SNAKE_CASE_ , "w" ) as f: for item in data: f.write(item + "\n" ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.text.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset_with_dir.text.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("main_dir" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.join("main_dir" , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.ext.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename("unsupported.ext" ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename("unsupported_2.ext" ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = "\n".join(["First", "Second\u2029with Unicode new line", "Third"] ) UpperCamelCase = str(tmp_path_factory.mktemp("data" ) / "dataset_with_unicode_new_lines.txt" ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture(scope="session" ) def a__ ( ): """simple docstring""" return os.path.join("tests" , "features" , "data" , "test_image_rgb.jpg" ) @pytest.fixture(scope="session" ) def a__ ( ): """simple docstring""" return os.path.join("tests" , "features" , "data" , "test_audio_44100.wav" ) @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data" ) / "dataset.img.zip" with zipfile.ZipFile(SCREAMING_SNAKE_CASE_ , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ) ) f.write(SCREAMING_SNAKE_CASE_ , arcname=os.path.basename(SCREAMING_SNAKE_CASE_ ).replace(".jpg" , "2.jpg" ) ) return path @pytest.fixture(scope="session" ) def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = tmp_path_factory.mktemp("data_dir" ) (data_dir / "subdir").mkdir() with open(data_dir / "subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / "subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden file with open(data_dir / "subdir" / ".test.txt" , "w" ) as f: f.write("bar\n" * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / ".subdir" / "train.txt" , "w" ) as f: f.write("foo\n" * 10 ) with open(data_dir / ".subdir" / "test.txt" , "w" ) as f: f.write("bar\n" * 10 ) return data_dir
153
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
0
"""simple docstring""" def __lowerCAmelCase ( lowercase : int , lowercase : int ) -> str: """simple docstring""" while b: snake_case ,snake_case : int = b, a % b return a def __lowerCAmelCase ( lowercase : int , lowercase : int ) -> str: """simple docstring""" return a if b == 0 else euclidean_gcd_recursive(SCREAMING_SNAKE_CASE_ , a % b ) def __lowerCAmelCase ( ) -> List[Any]: """simple docstring""" print(F'euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}' ) print(F'euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}' ) print(F'euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}' ) print(F'euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}' ) print(F'euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}' ) print(F'euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}' ) print(F'euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}' ) print(F'euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}' ) print(F'euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}' ) print(F'euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}' ) if __name__ == "__main__": main()
203
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 UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = 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) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 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. __lowerCAmelCase = [ "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 , )
92
0
'''simple docstring''' def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' return int((input_a, input_a).count(1 ) != 0 ) def __magic_name__ ( ) -> int: '''simple docstring''' assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
56
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ): return x return (x, x) @require_tf class a__ : def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase = VisionTextDualEncoderConfig.from_vision_text_configs(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = after_output[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = np.abs((a - b) ).max() self.assertLessEqual(_A , _A , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_save_load(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_pretrained_model_and_inputs() __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = after_outputs[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFViTModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFViTModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFDeiTModel(_A , name="vision_model" ) __lowerCAmelCase = TFRobertaModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFDeiTModelTester(self ) __lowerCAmelCase = TFRobertaModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = clip_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=_A ) __lowerCAmelCase = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __lowerCAmelCase = processor( text=["una foto di un gatto", "una foto di un cane"] , images=_A , padding=_A , return_tensors="np" ) __lowerCAmelCase = model(**_A ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __lowerCAmelCase = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , _A , atol=1E-3 ) )
92
0
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES a_ : Union[str, Any] = logging.get_logger(__name__) a_ : Union[str, Any] = OrderedDict( [ # Base model mapping ("""albert""", """FlaxAlbertModel"""), ("""bart""", """FlaxBartModel"""), ("""beit""", """FlaxBeitModel"""), ("""bert""", """FlaxBertModel"""), ("""big_bird""", """FlaxBigBirdModel"""), ("""blenderbot""", """FlaxBlenderbotModel"""), ("""blenderbot-small""", """FlaxBlenderbotSmallModel"""), ("""clip""", """FlaxCLIPModel"""), ("""distilbert""", """FlaxDistilBertModel"""), ("""electra""", """FlaxElectraModel"""), ("""gpt-sw3""", """FlaxGPT2Model"""), ("""gpt2""", """FlaxGPT2Model"""), ("""gpt_neo""", """FlaxGPTNeoModel"""), ("""gptj""", """FlaxGPTJModel"""), ("""longt5""", """FlaxLongT5Model"""), ("""marian""", """FlaxMarianModel"""), ("""mbart""", """FlaxMBartModel"""), ("""mt5""", """FlaxMT5Model"""), ("""opt""", """FlaxOPTModel"""), ("""pegasus""", """FlaxPegasusModel"""), ("""regnet""", """FlaxRegNetModel"""), ("""resnet""", """FlaxResNetModel"""), ("""roberta""", """FlaxRobertaModel"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""), ("""roformer""", """FlaxRoFormerModel"""), ("""t5""", """FlaxT5Model"""), ("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""), ("""vit""", """FlaxViTModel"""), ("""wav2vec2""", """FlaxWav2Vec2Model"""), ("""whisper""", """FlaxWhisperModel"""), ("""xglm""", """FlaxXGLMModel"""), ("""xlm-roberta""", """FlaxXLMRobertaModel"""), ] ) a_ : Dict = OrderedDict( [ # Model for pre-training mapping ("""albert""", """FlaxAlbertForPreTraining"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForPreTraining"""), ("""big_bird""", """FlaxBigBirdForPreTraining"""), ("""electra""", """FlaxElectraForPreTraining"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) a_ : Optional[Any] = OrderedDict( [ # Model for Masked LM mapping ("""albert""", """FlaxAlbertForMaskedLM"""), ("""bart""", """FlaxBartForConditionalGeneration"""), ("""bert""", """FlaxBertForMaskedLM"""), ("""big_bird""", """FlaxBigBirdForMaskedLM"""), ("""distilbert""", """FlaxDistilBertForMaskedLM"""), ("""electra""", """FlaxElectraForMaskedLM"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""roberta""", """FlaxRobertaForMaskedLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""), ("""roformer""", """FlaxRoFormerForMaskedLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""), ] ) a_ : Optional[int] = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("""bart""", """FlaxBartForConditionalGeneration"""), ("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""), ("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""), ("""encoder-decoder""", """FlaxEncoderDecoderModel"""), ("""longt5""", """FlaxLongT5ForConditionalGeneration"""), ("""marian""", """FlaxMarianMTModel"""), ("""mbart""", """FlaxMBartForConditionalGeneration"""), ("""mt5""", """FlaxMT5ForConditionalGeneration"""), ("""pegasus""", """FlaxPegasusForConditionalGeneration"""), ("""t5""", """FlaxT5ForConditionalGeneration"""), ] ) a_ : Any = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) a_ : str = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) a_ : List[str] = OrderedDict( [ # Model for Causal LM mapping ("""bart""", """FlaxBartForCausalLM"""), ("""bert""", """FlaxBertForCausalLM"""), ("""big_bird""", """FlaxBigBirdForCausalLM"""), ("""electra""", """FlaxElectraForCausalLM"""), ("""gpt-sw3""", """FlaxGPT2LMHeadModel"""), ("""gpt2""", """FlaxGPT2LMHeadModel"""), ("""gpt_neo""", """FlaxGPTNeoForCausalLM"""), ("""gptj""", """FlaxGPTJForCausalLM"""), ("""opt""", """FlaxOPTForCausalLM"""), ("""roberta""", """FlaxRobertaForCausalLM"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""), ("""xglm""", """FlaxXGLMForCausalLM"""), ("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""), ] ) a_ : Tuple = OrderedDict( [ # Model for Sequence Classification mapping ("""albert""", """FlaxAlbertForSequenceClassification"""), ("""bart""", """FlaxBartForSequenceClassification"""), ("""bert""", """FlaxBertForSequenceClassification"""), ("""big_bird""", """FlaxBigBirdForSequenceClassification"""), ("""distilbert""", """FlaxDistilBertForSequenceClassification"""), ("""electra""", """FlaxElectraForSequenceClassification"""), ("""mbart""", """FlaxMBartForSequenceClassification"""), ("""roberta""", """FlaxRobertaForSequenceClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""), ("""roformer""", """FlaxRoFormerForSequenceClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""), ] ) a_ : List[Any] = OrderedDict( [ # Model for Question Answering mapping ("""albert""", """FlaxAlbertForQuestionAnswering"""), ("""bart""", """FlaxBartForQuestionAnswering"""), ("""bert""", """FlaxBertForQuestionAnswering"""), ("""big_bird""", """FlaxBigBirdForQuestionAnswering"""), ("""distilbert""", """FlaxDistilBertForQuestionAnswering"""), ("""electra""", """FlaxElectraForQuestionAnswering"""), ("""mbart""", """FlaxMBartForQuestionAnswering"""), ("""roberta""", """FlaxRobertaForQuestionAnswering"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""), ("""roformer""", """FlaxRoFormerForQuestionAnswering"""), ("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""), ] ) a_ : List[Any] = OrderedDict( [ # Model for Token Classification mapping ("""albert""", """FlaxAlbertForTokenClassification"""), ("""bert""", """FlaxBertForTokenClassification"""), ("""big_bird""", """FlaxBigBirdForTokenClassification"""), ("""distilbert""", """FlaxDistilBertForTokenClassification"""), ("""electra""", """FlaxElectraForTokenClassification"""), ("""roberta""", """FlaxRobertaForTokenClassification"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""), ("""roformer""", """FlaxRoFormerForTokenClassification"""), ("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""), ] ) a_ : List[str] = OrderedDict( [ # Model for Multiple Choice mapping ("""albert""", """FlaxAlbertForMultipleChoice"""), ("""bert""", """FlaxBertForMultipleChoice"""), ("""big_bird""", """FlaxBigBirdForMultipleChoice"""), ("""distilbert""", """FlaxDistilBertForMultipleChoice"""), ("""electra""", """FlaxElectraForMultipleChoice"""), ("""roberta""", """FlaxRobertaForMultipleChoice"""), ("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""), ("""roformer""", """FlaxRoFormerForMultipleChoice"""), ("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""), ] ) a_ : Optional[int] = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) a_ : List[str] = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) a_ : Any = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) a_ : str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) a_ : Tuple = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) a_ : List[str] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) a_ : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) a_ : List[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) a_ : Dict = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) a_ : List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) a_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) a_ : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) a_ : str = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) a_ : Optional[Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) a_ : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) a_ : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) a_ : List[str] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Tuple =FLAX_MODEL_MAPPING a_ : Union[str, Any] = auto_class_update(FlaxAutoModel) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Any =FLAX_MODEL_FOR_PRETRAINING_MAPPING a_ : List[str] = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : List[Any] =FLAX_MODEL_FOR_CAUSAL_LM_MAPPING a_ : Optional[Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Optional[int] =FLAX_MODEL_FOR_MASKED_LM_MAPPING a_ : Optional[int] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Dict =FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a_ : int = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Any =FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING a_ : List[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : int =FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING a_ : int = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Tuple =FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a_ : Dict = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : int =FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING a_ : Optional[Any] = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : List[Any] =FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING a_ : Tuple = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : Tuple =FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING a_ : Union[str, Any] = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : int =FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING a_ : str = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class __UpperCamelCase ( _BaseAutoModelClass ): lowercase : int =FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING a_ : Dict = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
75
import json import os import torch from diffusers import UNetaDModel os.makedirs("""hub/hopper-medium-v2/unet/hor32""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/unet/hor128""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/value_function""", exist_ok=True) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): if hor == 1_28: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 64, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") __lowerCAmelCase = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) __lowerCAmelCase = model.state_dict() __lowerCAmelCase = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 6_55_36, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 1_28, 2_56), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 6_55_36, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } __lowerCAmelCase = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) __lowerCAmelCase = model __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
92
0
"""simple docstring""" from __future__ import annotations _UpperCamelCase : str = 'Muhammad Umer Farooq' _UpperCamelCase : Optional[Any] = 'MIT' _UpperCamelCase : str = '1.0.0' _UpperCamelCase : Union[str, Any] = 'Muhammad Umer Farooq' _UpperCamelCase : Dict = 'contact@muhammadumerfarooq.me' _UpperCamelCase : List[Any] = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class a ( snake_case__ ): def __init__( self , _lowerCamelCase ): super().__init__() lowercase = [] lowercase = domain def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase ): if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: lowercase = parse.urljoin(self.domain , _A ) self.urls.append(_A ) def _SCREAMING_SNAKE_CASE ( __snake_case : str ): '''simple docstring''' return ".".join(get_sub_domain_name(SCREAMING_SNAKE_CASE_ ).split('.' )[-2:] ) def _SCREAMING_SNAKE_CASE ( __snake_case : str ): '''simple docstring''' return parse.urlparse(SCREAMING_SNAKE_CASE_ ).netloc def _SCREAMING_SNAKE_CASE ( __snake_case : str = "https://github.com" ): '''simple docstring''' lowercase = get_domain_name(SCREAMING_SNAKE_CASE_ ) # Initialize the parser lowercase = Parser(SCREAMING_SNAKE_CASE_ ) try: # Open URL lowercase = requests.get(SCREAMING_SNAKE_CASE_ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through lowercase = set() for link in parser.urls: # open URL. # read = requests.get(link) try: lowercase = requests.get(SCREAMING_SNAKE_CASE_ ) # Get the valid email. lowercase = re.findall('[a-zA-Z0-9]+@' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(SCREAMING_SNAKE_CASE_ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": _UpperCamelCase : Dict = emails_from_url('https://github.com') print(F'''{len(emails)} emails found:''') print('\n'.join(sorted(emails)))
220
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = metric_id class a__ : _a : Optional[int] = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): if "tmp_path" in args: __lowerCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="https://huggingface.co/docs/evaluate" ): func(*SCREAMING_SNAKE_CASE_ )
92
0
from __future__ import annotations import numpy as np def __lowerCAmelCase ( a__ ) -> List[str]: return np.maximum(0 , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
6
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
0
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
207
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCamelCase__ = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' import argparse import os import re import packaging.version lowerCAmelCase: Optional[int] = 'examples/' lowerCAmelCase: Optional[Any] = { 'examples': (re.compile(r'^check_min_version\(\"[^\"]+\"\)\s*$', re.MULTILINE), 'check_min_version(\"VERSION\")\n'), 'init': (re.compile(r'^__version__\s+=\s+\"([^\"]+)\"\s*$', re.MULTILINE), '__version__ = \"VERSION\"\n'), 'setup': (re.compile(r'^(\s*)version\s*=\s*\"[^\"]+\",', re.MULTILINE), r'\1version=\"VERSION\",'), 'doc': (re.compile(r'^(\s*)release\s*=\s*\"[^\"]+\"$', re.MULTILINE), 'release = \"VERSION\"\n'), } lowerCAmelCase: Union[str, Any] = { 'init': 'src/transformers/__init__.py', 'setup': 'setup.py', } lowerCAmelCase: Any = 'README.md' def lowerCamelCase__ ( _A , _A , _A ): with open(SCREAMING_SNAKE_CASE_ , 'r' , encoding='utf-8' , newline='\n' ) as f: a : List[str] = f.read() a , a : Optional[Any] = REPLACE_PATTERNS[pattern] a : List[Any] = replace.replace('VERSION' , SCREAMING_SNAKE_CASE_ ) a : Union[str, Any] = re_pattern.sub(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(SCREAMING_SNAKE_CASE_ ) def lowerCamelCase__ ( _A ): for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , pattern='examples' ) def lowerCamelCase__ ( _A , _A=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE_ ) def lowerCamelCase__ ( ): a : Any = '🤗 Transformers currently provides the following architectures' a : Dict = '1. Want to contribute a new model?' with open(SCREAMING_SNAKE_CASE_ , 'r' , encoding='utf-8' , newline='\n' ) as f: a : List[str] = f.readlines() # Find the start of the list. a : Optional[int] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 a : Optional[int] = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): a : Dict = lines[index].replace( 'https://huggingface.co/docs/transformers/main/model_doc' , 'https://huggingface.co/docs/transformers/model_doc' , ) index += 1 with open(SCREAMING_SNAKE_CASE_ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(SCREAMING_SNAKE_CASE_ ) def lowerCamelCase__ ( ): with open(REPLACE_FILES['init'] , 'r' ) as f: a : Union[str, Any] = f.read() a : Dict = REPLACE_PATTERNS['init'][0].search(SCREAMING_SNAKE_CASE_ ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE_ ) def lowerCamelCase__ ( _A=False ): a : Union[str, Any] = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: a : int = default_version.base_version elif patch: a : str = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: a : Optional[int] = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. a : Any = input(f"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: a : Optional[Any] = default_version print(f"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ , patch=SCREAMING_SNAKE_CASE_ ) if not patch: print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() def lowerCamelCase__ ( ): a : Dict = get_version() a : Any = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" a : Optional[int] = current_version.base_version # Check with the user we got that right. a : int = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: a : Union[str, Any] = dev_version print(f"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ ) print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() if __name__ == "__main__": lowerCAmelCase: Optional[int] = argparse.ArgumentParser() parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.') parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.') lowerCAmelCase: List[str] = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('Nothing to do after a patch :-)') else: post_release_work()
297
import argparse import os import re import packaging.version UpperCamelCase__ = """examples/""" UpperCamelCase__ = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCamelCase__ = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCamelCase__ = """README.md""" def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = re_pattern.sub(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , pattern="examples" ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(SCREAMING_SNAKE_CASE_ ) def _a ( ): with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(SCREAMING_SNAKE_CASE_ ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any]=False ): __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ , patch=SCREAMING_SNAKE_CASE_ ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _a ( ): __lowerCAmelCase = get_version() __lowerCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCamelCase__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
92
0
UpperCAmelCase : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase : int = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase : int = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' assert len(str(SCREAMING_SNAKE_CASE_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: lowerCamelCase = year // 100 lowerCamelCase = (5 * (century % 4) + 2) % 7 lowerCamelCase = year % 100 lowerCamelCase = centurian % 12 lowerCamelCase = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 lowerCamelCase = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) lowerCamelCase = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
252
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 a__ ( snake_case__ , unittest.TestCase ): _a : Dict = KandinskyImgaImgPipeline _a : List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] _a : str = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] _a : List[Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _a : int = False @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim * 4 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 1_0_0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) __lowerCAmelCase = MultilingualCLIP(_A ) __lowerCAmelCase = text_encoder.eval() return text_encoder @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = { "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, } __lowerCAmelCase = UNetaDConditionModel(**_A ) return model @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return { "block_out_channels": [3_2, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_unet __lowerCAmelCase = self.dummy_movq __lowerCAmelCase = { "num_train_timesteps": 1_0_0_0, "beta_schedule": "linear", "beta_start": 0.0_00_85, "beta_end": 0.0_12, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } __lowerCAmelCase = DDIMScheduler(**_A ) __lowerCAmelCase = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_A ) # create init_image __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCAmelCase = Image.fromarray(np.uinta(_A ) ).convert("RGB" ).resize((2_5_6, 2_5_6) ) if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "horse", "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 6_4, "width": 6_4, "num_inference_steps": 1_0, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "cpu" __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = self.pipeline_class(**_A ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __lowerCAmelCase = pipe(**self.get_dummy_inputs(_A ) ) __lowerCAmelCase = output.images __lowerCAmelCase = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCAmelCase = np.array( [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33] ) 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 a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_img2img_frog.npy" ) __lowerCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __lowerCAmelCase = "A red cartoon frog, 4k" __lowerCAmelCase = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __lowerCAmelCase = KandinskyImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase , __lowerCAmelCase = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __lowerCAmelCase = pipeline( _A , image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A )
92
0
'''simple docstring''' 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 __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Any: snake_case__ : Dict = np.argmax(SCREAMING_SNAKE_CASE_ , axis=1 ) return np.sum(outputs == labels ) def __snake_case( _lowerCAmelCase ) -> Optional[Any]: with open(SCREAMING_SNAKE_CASE_ , encoding="""utf_8""" ) as f: snake_case__ : List[str] = csv.reader(SCREAMING_SNAKE_CASE_ ) snake_case__ : int = [] 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 __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> int: snake_case__ : str = [] for dataset in encoded_datasets: snake_case__ : int = len(SCREAMING_SNAKE_CASE_ ) snake_case__ : Any = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) snake_case__ : Union[str, Any] = np.zeros((n_batch, 2) , dtype=np.intaa ) snake_case__ : str = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) snake_case__ : List[str] = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(SCREAMING_SNAKE_CASE_ ): snake_case__ : Union[str, Any] = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] snake_case__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] snake_case__ : List[Any] = with_conta snake_case__ : List[Any] = with_conta snake_case__ : List[Any] = len(SCREAMING_SNAKE_CASE_ ) - 1 snake_case__ : Dict = len(SCREAMING_SNAKE_CASE_ ) - 1 snake_case__ : Optional[Any] = with_conta snake_case__ : Union[str, Any] = with_conta snake_case__ : str = mc_label snake_case__ : List[str] = (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 __snake_case( ) -> int: snake_case__ : Tuple = 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=374 ) 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.""" ) snake_case__ : List[str] = 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 ) snake_case__ : int = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) snake_case__ : Tuple = 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 snake_case__ : Tuple = ["""_start_""", """_delimiter_""", """_classify_"""] snake_case__ : Tuple = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(SCREAMING_SNAKE_CASE_ ) snake_case__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) snake_case__ : Optional[Any] = 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(_lowerCAmelCase ): 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...""" ) snake_case__ : Optional[int] = load_rocstories_dataset(args.train_dataset ) snake_case__ : List[str] = load_rocstories_dataset(args.eval_dataset ) snake_case__ : Union[str, Any] = (train_dataset, eval_dataset) snake_case__ : Dict = tokenize_and_encode(SCREAMING_SNAKE_CASE_ ) # Compute the max input length for the Transformer snake_case__ : List[Any] = model.config.n_positions // 2 - 2 snake_case__ : Any = 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 ) snake_case__ : Optional[Any] = min(SCREAMING_SNAKE_CASE_ , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders snake_case__ : Optional[int] = pre_process_datasets(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) snake_case__ , snake_case__ : Optional[Any] = tensor_datasets[0], tensor_datasets[1] snake_case__ : Optional[Any] = TensorDataset(*SCREAMING_SNAKE_CASE_ ) snake_case__ : str = RandomSampler(SCREAMING_SNAKE_CASE_ ) snake_case__ : Union[str, Any] = DataLoader(SCREAMING_SNAKE_CASE_ , sampler=SCREAMING_SNAKE_CASE_ , batch_size=args.train_batch_size ) snake_case__ : Optional[int] = TensorDataset(*SCREAMING_SNAKE_CASE_ ) snake_case__ : List[str] = SequentialSampler(SCREAMING_SNAKE_CASE_ ) snake_case__ : Optional[Any] = 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: snake_case__ : Tuple = args.max_steps snake_case__ : Any = args.max_steps // (len(SCREAMING_SNAKE_CASE_ ) // args.gradient_accumulation_steps) + 1 else: snake_case__ : Dict = len(SCREAMING_SNAKE_CASE_ ) // args.gradient_accumulation_steps * args.num_train_epochs snake_case__ : str = list(model.named_parameters() ) snake_case__ : str = ["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""] snake_case__ : List[str] = [ { """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}, ] snake_case__ : int = AdamW(SCREAMING_SNAKE_CASE_ , lr=args.learning_rate , eps=args.adam_epsilon ) snake_case__ : List[Any] = get_linear_schedule_with_warmup( SCREAMING_SNAKE_CASE_ , num_warmup_steps=args.warmup_steps , num_training_steps=SCREAMING_SNAKE_CASE_ ) if args.do_train: snake_case__ , snake_case__ , snake_case__ : Optional[int] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="""Epoch""" ): snake_case__ : str = 0 snake_case__ : Optional[int] = 0 snake_case__ : Dict = tqdm(SCREAMING_SNAKE_CASE_ , desc="""Training""" ) for step, batch in enumerate(SCREAMING_SNAKE_CASE_ ): snake_case__ : Union[str, Any] = tuple(t.to(SCREAMING_SNAKE_CASE_ ) for t in batch ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = batch snake_case__ : Tuple = model(SCREAMING_SNAKE_CASE_ , mc_token_ids=SCREAMING_SNAKE_CASE_ , lm_labels=SCREAMING_SNAKE_CASE_ , mc_labels=SCREAMING_SNAKE_CASE_ ) snake_case__ : Any = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() snake_case__ : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 snake_case__ : Tuple = """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 snake_case__ : str = 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` snake_case__ : Optional[Any] = os.path.join(args.output_dir , SCREAMING_SNAKE_CASE_ ) snake_case__ : int = 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 snake_case__ : int = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) snake_case__ : Union[str, Any] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(SCREAMING_SNAKE_CASE_ ) if args.do_eval: model.eval() snake_case__ , snake_case__ : List[str] = 0, 0 snake_case__ , snake_case__ : Union[str, Any] = 0, 0 for batch in tqdm(SCREAMING_SNAKE_CASE_ , desc="""Evaluating""" ): snake_case__ : Union[str, Any] = tuple(t.to(SCREAMING_SNAKE_CASE_ ) for t in batch ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = batch with torch.no_grad(): snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = model( SCREAMING_SNAKE_CASE_ , mc_token_ids=SCREAMING_SNAKE_CASE_ , lm_labels=SCREAMING_SNAKE_CASE_ , mc_labels=SCREAMING_SNAKE_CASE_ ) snake_case__ : Optional[int] = mc_logits.detach().cpu().numpy() snake_case__ : Union[str, Any] = mc_labels.to("""cpu""" ).numpy() snake_case__ : Union[str, Any] = 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 snake_case__ : Optional[int] = eval_loss / nb_eval_steps snake_case__ : Any = eval_accuracy / nb_eval_examples snake_case__ : Optional[int] = tr_loss / nb_tr_steps if args.do_train else None snake_case__ : Optional[int] = {"""eval_loss""": eval_loss, """eval_accuracy""": eval_accuracy, """train_loss""": train_loss} snake_case__ : Optional[int] = 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()
35
class a__ ( snake_case__ ): pass class a__ ( snake_case__ ): pass class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [ [], [], [], ] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(_A ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): """simple docstring""" return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if len(self.queue ) == 1_0_0: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(_A ) return data def __str__( self ): """simple docstring""" return str(self.queue ) def _a ( ): __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
92
0
'''simple docstring''' import os from math import logaa def snake_case ( UpperCAmelCase = "base_exp.txt" )-> Optional[Any]: """simple docstring""" __A = 0 __A = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) ): __A , __A = list(map(SCREAMING_SNAKE_CASE_ , line.split(',' ) ) ) if x * logaa(SCREAMING_SNAKE_CASE_ ) > largest: __A = x * logaa(SCREAMING_SNAKE_CASE_ ) __A = i + 1 return result if __name__ == "__main__": print(solution())
161
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a__ : def __init__( self , _A , _A=1_3 , _A=3_0 , _A=2 , _A=3 , _A=True , _A=True , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1_0 , _A=0.02 , _A=3 , _A=None , _A=2 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = scope __lowerCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 2 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTForMaskedImageModeling(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForMaskedImageModeling(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) _a : int = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) _a : Optional[Any] = False _a : Tuple = False _a : Tuple = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=False ): """simple docstring""" __lowerCAmelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.model_tester.is_training: return __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __lowerCAmelCase = False __lowerCAmelCase = True for model_class in self.all_model_classes: if model_class in get_values(_A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __lowerCAmelCase = model_class(_A ) model.gradient_checkpointing_enable() model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_A ), *get_values(_A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type['title']}""" ): __lowerCAmelCase = problem_type["title"] __lowerCAmelCase = problem_type["num_labels"] __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) if problem_type["num_labels"] > 1: __lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) __lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_A ) as warning_list: __lowerCAmelCase = model(**_A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DeiTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _a ( ): __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( _A ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ).to(_A ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**_A ) # verify the logits __lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _A ) __lowerCAmelCase = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ) __lowerCAmelCase = inputs.pixel_values.to(_A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowerCAmelCase = model(_A )
92
0
"""simple docstring""" import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures lowerCAmelCase__ = logging.get_logger(__name__) @dataclass class _lowerCamelCase : UpperCAmelCase_ = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys() )} ) UpperCAmelCase_ = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) UpperCAmelCase_ = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) UpperCAmelCase_ = field( default=snake_case__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def snake_case_ (self ) -> Optional[Any]: UpperCamelCase = self.task_name.lower() class _lowerCamelCase ( snake_case__ ): UpperCAmelCase_ = """train""" UpperCAmelCase_ = """dev""" UpperCAmelCase_ = """test""" class _lowerCamelCase ( snake_case__ ): UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 UpperCAmelCase_ = 42 def __init__(self , __a , __a , __a = None , __a = Split.train , __a = None , ) -> Optional[Any]: warnings.warn( "This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets " "library. You can have a look at this example script for pointers: " "https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py" , _A , ) UpperCamelCase = args UpperCamelCase = glue_processors[args.task_name]() UpperCamelCase = glue_output_modes[args.task_name] if isinstance(_A , _A ): try: UpperCamelCase = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) # Load data features from cache or dataset file UpperCamelCase = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}" , ) UpperCamelCase = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) UpperCamelCase , UpperCamelCase = label_list[2], label_list[1] UpperCamelCase = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. UpperCamelCase = cached_features_file + ".lock" with FileLock(_A ): if os.path.exists(_A ) and not args.overwrite_cache: UpperCamelCase = time.time() UpperCamelCase = torch.load(_A ) logger.info( F"Loading features from cached file {cached_features_file} [took %.3f s]" , time.time() - start ) else: logger.info(F"Creating features from dataset file at {args.data_dir}" ) if mode == Split.dev: UpperCamelCase = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: UpperCamelCase = self.processor.get_test_examples(args.data_dir ) else: UpperCamelCase = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: UpperCamelCase = examples[:limit_length] UpperCamelCase = glue_convert_examples_to_features( _A , _A , max_length=args.max_seq_length , label_list=_A , output_mode=self.output_mode , ) UpperCamelCase = time.time() torch.save(self.features , _A ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]" ) def __len__(self ) -> Union[str, Any]: return len(self.features ) def __getitem__(self , __a ) -> Any: return self.features[i] def snake_case_ (self ) -> int: return self.label_list
153
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
92
0
"""simple docstring""" import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __snake_case = logging.getLogger(__name__) __snake_case = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __snake_case = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _lowerCAmelCase : __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case__ )} , ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) __UpperCAmelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) __UpperCAmelCase : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) __UpperCAmelCase : bool = field( default=snake_case__ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def lowerCamelCase ( self ) -> List[str]: '''simple docstring''' if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path" ) @dataclass class _lowerCAmelCase : __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field(default=snake_case__ , metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''} , ) __UpperCAmelCase : Optional[str] = field( default=snake_case__ , metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''} , ) __UpperCAmelCase : bool = field( default=snake_case__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) __UpperCAmelCase : Optional[int] = field( default=5 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) __UpperCAmelCase : Optional[int] = field( default=snake_case__ , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) } , ) __UpperCAmelCase : Optional[int] = field( default=snake_case__ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) __UpperCAmelCase : float = field( default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) __UpperCAmelCase : bool = field( default=snake_case__ , metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) } , ) def lowerCamelCase ( self ) -> List[str]: '''simple docstring''' if self.train_file is not None: snake_case : Dict = self.train_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: snake_case : Tuple = self.validation_file.split("." )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def __lowerCAmelCase ( lowercase : Union[str, Any] , lowercase : Optional[int] ) -> str: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" ) as f: snake_case : List[str] = [json.loads(SCREAMING_SNAKE_CASE_ ) for line in f.read().splitlines() if (len(SCREAMING_SNAKE_CASE_ ) > 0 and not line.isspace())] assert len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) snake_case : List[Any] = {c: dataset[c] for c in dataset.column_names} snake_case : List[Any] = refs return Dataset.from_dict(SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( ) -> Optional[Any]: """simple docstring""" snake_case : Tuple = 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. snake_case ,snake_case ,snake_case : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case ,snake_case ,snake_case : List[str] = parser.parse_args_into_dataclasses() # Detecting last checkpoint. snake_case : str = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case : List[Any] = 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() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , SCREAMING_SNAKE_CASE_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case : Any = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): snake_case : List[str] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'train[:{data_args.validation_split_percentage}%]' , ) snake_case : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'train[{data_args.validation_split_percentage}%:]' , ) else: snake_case : Dict = {} if data_args.train_file is not None: snake_case : Optional[Any] = data_args.train_file if data_args.validation_file is not None: snake_case : Union[str, Any] = data_args.validation_file snake_case : List[Any] = data_args.train_file.split("." )[-1] if extension == "txt": snake_case : Dict = "text" snake_case : Any = load_dataset(SCREAMING_SNAKE_CASE_ , data_files=SCREAMING_SNAKE_CASE_ ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case : List[str] = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: snake_case : Tuple = AutoConfig.from_pretrained(model_args.config_name , **SCREAMING_SNAKE_CASE_ ) elif model_args.model_name_or_path: snake_case : int = AutoConfig.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE_ ) else: snake_case : str = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) snake_case : Tuple = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: snake_case : List[str] = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **SCREAMING_SNAKE_CASE_ ) elif model_args.model_name_or_path: snake_case : List[Any] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **SCREAMING_SNAKE_CASE_ ) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) if model_args.model_name_or_path: snake_case : str = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch" ) snake_case : Dict = AutoModelForMaskedLM.from_config(SCREAMING_SNAKE_CASE_ ) model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE_ ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: snake_case : Union[str, Any] = datasets["train"].column_names else: snake_case : Union[str, Any] = datasets["validation"].column_names snake_case : str = "text" if "text" in column_names else column_names[0] snake_case : Union[str, Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(lowercase : Union[str, Any] ): # Remove empty lines snake_case : Any = [line for line in examples["text"] if len(SCREAMING_SNAKE_CASE_ ) > 0 and not line.isspace()] return tokenizer(examples["text"] , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=data_args.max_seq_length ) snake_case : Union[str, Any] = datasets.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: snake_case : int = add_chinese_references(tokenized_datasets["train"] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: snake_case : str = add_chinese_references( tokenized_datasets["validation"] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer snake_case : Tuple = data_args.train_ref_file or data_args.validation_ref_file if has_ref: snake_case : Any = False # Data collator # This one will take care of randomly masking the tokens. snake_case : Dict = DataCollatorForWholeWordMask(tokenizer=SCREAMING_SNAKE_CASE_ , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer snake_case : Optional[int] = Trainer( model=SCREAMING_SNAKE_CASE_ , args=SCREAMING_SNAKE_CASE_ , train_dataset=tokenized_datasets["train"] if training_args.do_train else None , eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None , tokenizer=SCREAMING_SNAKE_CASE_ , data_collator=SCREAMING_SNAKE_CASE_ , ) # Training if training_args.do_train: if last_checkpoint is not None: snake_case : str = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): snake_case : Any = model_args.model_name_or_path else: snake_case : Union[str, Any] = None snake_case : Tuple = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_ ) trainer.save_model() # Saves the tokenizer too for easy upload snake_case : Tuple = os.path.join(training_args.output_dir , "train_results.txt" ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE_ , "w" ) as writer: logger.info("***** Train results *****" ) for key, value in sorted(train_result.metrics.items() ): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # Evaluation snake_case : int = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) snake_case : List[Any] = trainer.evaluate() snake_case : List[str] = math.exp(eval_output["eval_loss"] ) snake_case : int = perplexity snake_case : str = os.path.join(training_args.output_dir , "eval_results_mlm_wwm.txt" ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in sorted(results.items() ): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) return results def __lowerCAmelCase ( lowercase : Any ) -> Tuple: """simple docstring""" main() if __name__ == "__main__": main()
203
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
92
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a : Optional[int] = logging.get_logger(__name__) a : Union[str, Any] = { 'edbeeching/decision-transformer-gym-hopper-medium': ( 'https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a ( snake_case__ ): snake_case_ = """decision_transformer""" snake_case_ = ["""past_key_values"""] snake_case_ = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Optional[int] , lowercase_ : Optional[int]=17 , lowercase_ : List[Any]=4 , lowercase_ : List[str]=128 , lowercase_ : Tuple=4096 , lowercase_ : Tuple=True , lowercase_ : Tuple=1 , lowercase_ : List[Any]=1024 , lowercase_ : Optional[Any]=3 , lowercase_ : Union[str, Any]=1 , lowercase_ : Optional[Any]=None , lowercase_ : Tuple="relu" , lowercase_ : str=0.1 , lowercase_ : Optional[int]=0.1 , lowercase_ : Optional[Any]=0.1 , lowercase_ : Dict=1e-5 , lowercase_ : Tuple=0.02 , lowercase_ : Any=True , lowercase_ : str=True , lowercase_ : List[Any]=5_0256 , lowercase_ : int=5_0256 , lowercase_ : str=False , lowercase_ : Union[str, Any]=False , **lowercase_ : List[str] , ): snake_case_ = state_dim snake_case_ = act_dim snake_case_ = hidden_size snake_case_ = max_ep_len snake_case_ = action_tanh snake_case_ = vocab_size snake_case_ = n_positions snake_case_ = n_layer snake_case_ = n_head snake_case_ = n_inner snake_case_ = activation_function snake_case_ = resid_pdrop snake_case_ = embd_pdrop snake_case_ = attn_pdrop snake_case_ = layer_norm_epsilon snake_case_ = initializer_range snake_case_ = scale_attn_weights snake_case_ = use_cache snake_case_ = scale_attn_by_inverse_layer_idx snake_case_ = reorder_and_upcast_attn snake_case_ = bos_token_id snake_case_ = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
56
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType UpperCamelCase__ = get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {ckpt_dir}""" ) __lowerCAmelCase = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Model saved to {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " "initializing FSDP object" ) return __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) if F"""{MODEL_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading model from {ckpt_dir}""" ) __lowerCAmelCase = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) __lowerCAmelCase = state_dict["model"] logger.info(F"""Model loaded from {ckpt_dir}""" ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {output_optimizer_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state saved in {output_optimizer_file}""" ) else: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {ckpt_dir}""" ) dist_cp.save_state_dict( state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Optimizer state saved in {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading Optimizer state from {input_optimizer_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state loaded from {input_optimizer_file}""" ) else: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) if F"""{OPTIMIZER_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading Optimizer from {ckpt_dir}""" ) __lowerCAmelCase = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) __lowerCAmelCase = optim_state["optimizer"] logger.info(F"""Optimizer loaded from {ckpt_dir}""" ) __lowerCAmelCase = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
92
0
'''simple docstring''' import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __UpperCamelCase ( snake_case__ ): def __init__( self, *lowerCAmelCase, lowerCAmelCase=None, lowerCAmelCase=None, **lowerCAmelCase ): """simple docstring""" super().__init__(*_A, **_A ) lowerCamelCase_ =eval_examples lowerCamelCase_ =post_process_function def lowercase__ ( self, lowerCAmelCase = None, lowerCAmelCase=None, lowerCAmelCase = None, lowerCAmelCase = "eval", **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =gen_kwargs.copy() lowerCamelCase_ =( gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''' ) is not None else self.args.generation_max_length ) lowerCamelCase_ =( gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''' ) is not None else self.args.generation_num_beams ) lowerCamelCase_ =gen_kwargs lowerCamelCase_ =self.eval_dataset if eval_dataset is None else eval_dataset lowerCamelCase_ =self.get_eval_dataloader(_A ) lowerCamelCase_ =self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowerCamelCase_ =self.compute_metrics lowerCamelCase_ =None lowerCamelCase_ =time.time() lowerCamelCase_ =self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowerCamelCase_ =eval_loop( _A, description='''Evaluation''', prediction_loss_only=True if compute_metrics is None else None, ignore_keys=_A, metric_key_prefix=_A, ) finally: lowerCamelCase_ =compute_metrics lowerCamelCase_ =self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( _A, _A, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size ), ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default lowerCamelCase_ =self.post_process_function(_A, _A, _A ) lowerCamelCase_ =self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): lowerCamelCase_ =metrics.pop(_A ) metrics.update(output.metrics ) else: lowerCamelCase_ =output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_A ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowerCamelCase_ =self.callback_handler.on_evaluate(self.args, self.state, self.control, _A ) return metrics def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase=None, lowerCAmelCase = "test", **lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =gen_kwargs.copy() lowerCamelCase_ =self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. lowerCamelCase_ =self.compute_metrics lowerCamelCase_ =None lowerCamelCase_ =time.time() lowerCamelCase_ =self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowerCamelCase_ =eval_loop( _A, description='''Prediction''', prediction_loss_only=True if compute_metrics is None else None, ignore_keys=_A, metric_key_prefix=_A, ) finally: lowerCamelCase_ =compute_metrics lowerCamelCase_ =self.args.eval_batch_size * self.args.world_size if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( _A, _A, num_samples=output.num_samples, num_steps=math.ceil(output.num_samples / total_batch_size ), ) ) if self.post_process_function is None or self.compute_metrics is None: return output lowerCamelCase_ =self.post_process_function(_A, _A, _A, '''predict''' ) lowerCamelCase_ =self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): lowerCamelCase_ =metrics.pop(_A ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions, label_ids=predictions.label_ids, metrics=_A )
75
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( snake_case__ ): def __init__( self , *_A , _A=None , _A=None , **_A ): """simple docstring""" super().__init__(*_A , **_A ) __lowerCAmelCase = eval_examples __lowerCAmelCase = post_process_function def __SCREAMING_SNAKE_CASE( self , _A = None , _A=None , _A = None , _A = "eval" , **_A , ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = ( gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length ) __lowerCAmelCase = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams ) __lowerCAmelCase = gen_kwargs __lowerCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset __lowerCAmelCase = self.get_eval_dataloader(_A ) __lowerCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default __lowerCAmelCase = self.post_process_function(_A , _A , _A ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) else: __lowerCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_A ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __lowerCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , _A ) return metrics def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=None , _A = "test" , **_A ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output __lowerCAmelCase = self.post_process_function(_A , _A , _A , "predict" ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_A )
92
0
"""simple docstring""" import os def _SCREAMING_SNAKE_CASE ( __snake_case : str = "matrix.txt" ): '''simple docstring''' with open(os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) as in_file: lowercase = in_file.read() lowercase = [[int(SCREAMING_SNAKE_CASE_ ) for cell in row.split(',' )] for row in data.strip().splitlines()] lowercase = [[0 for cell in row] for row in grid] lowercase = len(grid[0] ) lowercase = [[0 for i in range(SCREAMING_SNAKE_CASE_ )] for j in range(SCREAMING_SNAKE_CASE_ )] lowercase = grid[0][0] for i in range(1 , SCREAMING_SNAKE_CASE_ ): lowercase = grid[0][i] + dp[0][i - 1] for i in range(1 , SCREAMING_SNAKE_CASE_ ): lowercase = grid[i][0] + dp[i - 1][0] for i in range(1 , SCREAMING_SNAKE_CASE_ ): for j in range(1 , SCREAMING_SNAKE_CASE_ ): lowercase = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(F'''{solution() = }''')
220
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 _a ( SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = filter(lambda SCREAMING_SNAKE_CASE_ : p.requires_grad , model.parameters() ) __lowerCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase__ = logging.getLogger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): if metric == "rouge2": __lowerCAmelCase = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __lowerCAmelCase = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __lowerCAmelCase = "{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." ) __lowerCAmelCase = 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 _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return EarlyStopping( monitor=F"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class a__ ( pl.Callback ): def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = {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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCAmelCase = 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 __lowerCAmelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCAmelCase = od / "test_results.txt" __lowerCAmelCase = 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. __lowerCAmelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCAmelCase = 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 __lowerCAmelCase = metrics[key] if isinstance(_A , torch.Tensor ): __lowerCAmelCase = val.item() __lowerCAmelCase = f"""{key}: {val:.6f}\n""" writer.write(_A ) if not save_generations: return if "preds" in metrics: __lowerCAmelCase = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: __lowerCAmelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCAmelCase = pl_module.model.num_parameters() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
92
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A : str = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Any = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys A : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
92
0
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def a ( *lowerCamelCase_ ): '''simple docstring''' with open(SCREAMING_SNAKE_CASE_ , '''r''' ) as fh: fcntl.flock(SCREAMING_SNAKE_CASE_ , fcntl.LOCK_EX ) try: print(*SCREAMING_SNAKE_CASE_ ) finally: fcntl.flock(SCREAMING_SNAKE_CASE_ , fcntl.LOCK_UN ) A__ : int = int(os.environ['LOCAL_RANK']) torch.cuda.set_device(local_rank) A__ : List[str] = torch.device('cuda', local_rank) A__ : Union[str, Any] = socket.gethostname() A__ : str = F"[{hostname}-{local_rank}]" try: # test distributed dist.init_process_group('nccl') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank A__ : Tuple = dist.get_rank() A__ : Optional[int] = dist.get_world_size() printflock(F"{gpu} is OK (global rank: {rank}/{world_size})") dist.barrier() if rank == 0: printflock(F"pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}") except Exception: printflock(F"{gpu} is broken") raise
207
from queue import PriorityQueue from typing import Any import numpy as np def _a ( 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 __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = 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(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = 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_ , ) __lowerCAmelCase = 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: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """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()
92
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase: Optional[Any] = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[str] = ['DeiTFeatureExtractor'] lowerCAmelCase: Optional[Any] = ['DeiTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Tuple = [ 'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DeiTForImageClassification', 'DeiTForImageClassificationWithTeacher', 'DeiTForMaskedImageModeling', 'DeiTModel', 'DeiTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: int = [ 'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDeiTForImageClassification', 'TFDeiTForImageClassificationWithTeacher', 'TFDeiTForMaskedImageModeling', 'TFDeiTModel', 'TFDeiTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_deit import DeiTFeatureExtractor from .image_processing_deit import DeiTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a__ ( snake_case__ ): _a : Optional[int] = """decision_transformer""" _a : Optional[int] = ["""past_key_values"""] _a : Dict = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _A=1_7 , _A=4 , _A=1_2_8 , _A=4_0_9_6 , _A=True , _A=1 , _A=1_0_2_4 , _A=3 , _A=1 , _A=None , _A="relu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1E-5 , _A=0.02 , _A=True , _A=True , _A=5_0_2_5_6 , _A=5_0_2_5_6 , _A=False , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = state_dim __lowerCAmelCase = act_dim __lowerCAmelCase = hidden_size __lowerCAmelCase = max_ep_len __lowerCAmelCase = action_tanh __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = bos_token_id __lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
92
0
from __future__ import annotations from math import pow, sqrt def __lowerCamelCase ( lowerCamelCase__ : float , lowerCamelCase__ : float , lowerCamelCase__ : float ): '''simple docstring''' if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if resistance == 0: return {"resistance": sqrt(pow(SCREAMING_SNAKE_CASE_ , 2 ) - pow(SCREAMING_SNAKE_CASE_ , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(SCREAMING_SNAKE_CASE_ , 2 ) - pow(SCREAMING_SNAKE_CASE_ , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(SCREAMING_SNAKE_CASE_ , 2 ) + pow(SCREAMING_SNAKE_CASE_ , 2 ) )} else: raise ValueError("""Exactly one argument must be 0""" ) if __name__ == "__main__": import doctest doctest.testmod()
252
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
0
'''simple docstring''' from __future__ import annotations from statistics import mean def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Optional[int]: snake_case__ : Optional[Any] = [0] * no_of_processes snake_case__ : Union[str, Any] = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(SCREAMING_SNAKE_CASE_ ): snake_case__ : List[str] = burst_time[i] snake_case__ : List[Any] = [] snake_case__ : Tuple = 0 snake_case__ : List[str] = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: snake_case__ : Dict = [] snake_case__ : Optional[Any] = -1 for i in range(SCREAMING_SNAKE_CASE_ ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0: snake_case__ : Optional[int] = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: snake_case__ : Union[str, Any] = i total_time += burst_time[target_process] completed += 1 snake_case__ : List[Any] = 0 snake_case__ : Tuple = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Any: snake_case__ : Any = [0] * no_of_processes for i in range(SCREAMING_SNAKE_CASE_ ): snake_case__ : Optional[int] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") __a = 4 __a = [2, 5, 3, 7] __a = [0, 0, 0, 0] __a = calculate_waitingtime(arrival_time, burst_time, no_of_processes) __a = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" F"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(F"\nAverage waiting time = {mean(waiting_time):.5f}") print(F"Average turnaround time = {mean(turn_around_time):.5f}")
35
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def snake_case ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , )-> int: """simple docstring""" for nxt, d in graph[v]: if nxt in visited_forward: continue __A = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __A = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __A = new_cost_f __A = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __A = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def snake_case ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )-> str: """simple docstring""" __A = -1 __A = set() __A = set() __A = {source: 0} __A = {destination: 0} __A = {source: None} __A = {destination: None} __A = PriorityQueue() __A = PriorityQueue() __A = 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(): __A , __A = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __A , __A = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __A = 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_ , ) __A = 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: __A = shortest_distance return shortest_path_distance a__ : Optional[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } a__ : Union[str, Any] = { "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()
161
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 UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 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, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 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" , )
92
0
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class _lowerCamelCase ( snake_case__ ): @add_start_docstrings(_A ) def __call__(self , __a , __a , **__a ) -> List[Any]: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class _lowerCamelCase ( snake_case__ ): def __init__(self , __a , __a = None ) -> int: UpperCamelCase = max_length UpperCamelCase = max_position_embeddings @add_start_docstrings(_A ) def __call__(self , __a , __a , **__a ) -> Dict: UpperCamelCase = input_ids.shape[-1] UpperCamelCase = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"maximum length ({self.max_position_embeddings}). Depending on the model, you may observe " "exceptions, performance degradation, or nothing at all." ) return is_done class _lowerCamelCase ( snake_case__ ): def __init__(self , __a , __a ) -> Tuple: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` " "with `max_length = start_length + max_new_tokens` instead." , _A , ) UpperCamelCase = start_length UpperCamelCase = max_new_tokens UpperCamelCase = start_length + max_new_tokens @add_start_docstrings(_A ) def __call__(self , __a , __a , **__a ) -> List[str]: return input_ids.shape[-1] >= self.max_length class _lowerCamelCase ( snake_case__ ): def __init__(self , __a , __a = None ) -> List[str]: UpperCamelCase = max_time UpperCamelCase = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(_A ) def __call__(self , __a , __a , **__a ) -> List[str]: return time.time() - self.initial_timestamp > self.max_time class _lowerCamelCase ( snake_case__ ): @add_start_docstrings(_A ) def __call__(self , __a , __a , **__a ) -> Tuple: return any(criteria(_A , _A ) for criteria in self ) @property def snake_case_ (self ) -> Any: for stopping_criterium in self: if isinstance(_A , _A ): return stopping_criterium.max_length elif isinstance(_A , _A ): return stopping_criterium.max_length return None def a__ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase = stopping_criteria.max_length UpperCamelCase = deepcopy(SCREAMING_SNAKE_CASE_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , SCREAMING_SNAKE_CASE_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=SCREAMING_SNAKE_CASE_ ) ) return new_stopping_criteria
153
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
0
"""simple docstring""" def __lowerCAmelCase ( lowercase : int = 100 ) -> Optional[Any]: """simple docstring""" snake_case : Tuple = (n * (n + 1) // 2) ** 2 snake_case : Tuple = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F'''{solution() = }''')
203
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 UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = 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) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 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. __lowerCAmelCase = [ "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 , )
92
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a : Optional[Any] = { 'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'], 'tokenization_canine': ['CanineTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : List[Any] = [ 'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST', 'CanineForMultipleChoice', 'CanineForQuestionAnswering', 'CanineForSequenceClassification', 'CanineForTokenClassification', 'CanineLayer', 'CanineModel', 'CaninePreTrainedModel', 'load_tf_weights_in_canine', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys a : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
56
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ): return x return (x, x) @require_tf class a__ : def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase = VisionTextDualEncoderConfig.from_vision_text_configs(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = after_output[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = np.abs((a - b) ).max() self.assertLessEqual(_A , _A , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_save_load(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_pretrained_model_and_inputs() __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = after_outputs[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFViTModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFViTModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFDeiTModel(_A , name="vision_model" ) __lowerCAmelCase = TFRobertaModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFDeiTModelTester(self ) __lowerCAmelCase = TFRobertaModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = clip_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=_A ) __lowerCAmelCase = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __lowerCAmelCase = processor( text=["una foto di un gatto", "una foto di un cane"] , images=_A , padding=_A , return_tensors="np" ) __lowerCAmelCase = model(**_A ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __lowerCAmelCase = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , _A , atol=1E-3 ) )
92
0
'''simple docstring''' def a_ ( __snake_case : int = 1000 ) -> str: """simple docstring""" lowerCamelCase_ =3 lowerCamelCase_ =0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(F"""{solution() = }""")
75
import json import os import torch from diffusers import UNetaDModel os.makedirs("""hub/hopper-medium-v2/unet/hor32""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/unet/hor128""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/value_function""", exist_ok=True) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): if hor == 1_28: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 64, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") __lowerCAmelCase = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) __lowerCAmelCase = model.state_dict() __lowerCAmelCase = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 6_55_36, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 1_28, 2_56), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 6_55_36, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } __lowerCAmelCase = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) __lowerCAmelCase = model __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
92
0
"""simple docstring""" import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _UpperCamelCase : Any = logging.get_logger(__name__) _UpperCamelCase : Any = {'vocab_file': 'vocab.txt'} _UpperCamelCase : List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } _UpperCamelCase : Union[str, Any] = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def _SCREAMING_SNAKE_CASE ( __snake_case : Optional[Any] ): '''simple docstring''' lowercase = collections.OrderedDict() with open(SCREAMING_SNAKE_CASE_ , 'r' , encoding='utf-8' ) as reader: lowercase = reader.readlines() for index, token in enumerate(SCREAMING_SNAKE_CASE_ ): lowercase = token.rstrip('\n' ) lowercase = index return vocab class a ( snake_case__ ): def __init__( self , _lowerCamelCase , _lowerCamelCase="<unk>" , _lowerCamelCase=2_0_0 ): lowercase = vocab lowercase = unk_token lowercase = max_input_chars_per_word def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = list(_A ) if len(_A ) > self.max_input_chars_per_word: return [self.unk_token] lowercase = 0 lowercase = [] while start < len(_A ): lowercase = len(_A ) lowercase = None while start < end: lowercase = ''.join(chars[start:end] ) if substr in self.vocab: lowercase = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(_A ) lowercase = end return sub_tokens class a ( snake_case__ ): UpperCAmelCase_ : Any =VOCAB_FILES_NAMES UpperCAmelCase_ : str =PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ : Optional[Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ : Any =["""input_ids""", """attention_mask"""] UpperCAmelCase_ : int =False def __init__( self , _lowerCamelCase , _lowerCamelCase="<d>" , _lowerCamelCase="</d>" , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<unk>" , _lowerCamelCase="</n>" , _lowerCamelCase="</_>" , _lowerCamelCase="left" , **_lowerCamelCase , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=_A , eod_token=_A , bos_token=_A , eos_token=_A , pad_token=_A , unk_token=_A , line_token=_A , space_token=_A , padding_side=_A , **_A , ) lowercase = bod_token lowercase = eod_token lowercase = load_vocab(_A ) lowercase = self.encoder[space_token] lowercase = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] lowercase = collections.OrderedDict(sorted(self.encoder.items() , key=lambda _lowerCamelCase : x[1] ) ) lowercase = {v: k for k, v in self.encoder.items()} lowercase = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def UpperCamelCase_ ( self ): return self.encoder[self.bod_token] @property def UpperCamelCase_ ( self ): return self.encoder[self.eod_token] @property def UpperCamelCase_ ( self ): return self.encoder["\n"] @property def UpperCamelCase_ ( self ): return len(self.encoder ) def UpperCamelCase_ ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = [] for x in jieba.cut(_A , cut_all=_A ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(_A ) ) return output_tokens def UpperCamelCase_ ( self , _lowerCamelCase , **_lowerCamelCase ): lowercase = [i for i in token_ids if i >= 0] lowercase = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(_A , **_A ) def UpperCamelCase_ ( self , _lowerCamelCase ): return token in self.encoder def UpperCamelCase_ ( self , _lowerCamelCase ): return "".join(_A ) def UpperCamelCase_ ( self , _lowerCamelCase ): return self.encoder.get(_A , self.encoder.get(self.unk_token ) ) def UpperCamelCase_ ( self , _lowerCamelCase ): return self.decoder.get(_A , self.unk_token ) def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase = None ): if os.path.isdir(_A ): lowercase = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: lowercase = (filename_prefix + '-' if filename_prefix else '') + save_directory lowercase = 0 if " " in self.encoder: lowercase = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: lowercase = self.encoder['\n'] del self.encoder["\n"] lowercase = collections.OrderedDict(sorted(self.encoder.items() , key=lambda _lowerCamelCase : x[1] ) ) with open(_A , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' ' Please check that the vocabulary is not corrupted!' ) lowercase = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_A , token_ids_a=_A , already_has_special_tokens=_A ) if token_ids_a is not None: return [1] + ([0] * len(_A )) + [1] + ([0] * len(_A )) return [1] + ([0] * len(_A ))
220
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = metric_id class a__ : _a : Optional[int] = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): if "tmp_path" in args: __lowerCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="https://huggingface.co/docs/evaluate" ): func(*SCREAMING_SNAKE_CASE_ )
92
0
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 __A( snake_case__ , unittest.TestCase ): snake_case_ = GPTaTokenizer snake_case_ = GPTaTokenizerFast snake_case_ = True snake_case_ = {"""add_prefix_space""": True} snake_case_ = False def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __a = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''<unk>''', '''<|endoftext|>''', ] __a = dict(zip(_A , range(len(_A ) ) ) ) __a = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] __a = {'''unk_token''': '''<unk>'''} __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_A ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(_A ) ) def SCREAMING_SNAKE_CASE_ ( self , **_snake_case ) -> str: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **_A ) def SCREAMING_SNAKE_CASE_ ( self , **_snake_case ) -> Any: '''simple docstring''' kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **_A ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Optional[Any]: '''simple docstring''' __a = '''lower newer''' __a = '''lower newer''' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' __a = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __a = '''lower newer''' __a = ['''\u0120low''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] __a = tokenizer.tokenize(_A , add_prefix_space=_A ) self.assertListEqual(_A , _A ) __a = tokens + [tokenizer.unk_token] __a = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , _A ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' if not self.test_rust_tokenizer: return __a = self.get_tokenizer() __a = self.get_rust_tokenizer(add_prefix_space=_A ) __a = '''lower newer''' # Testing tokenization __a = tokenizer.tokenize(_A , add_prefix_space=_A ) __a = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) # Testing conversion to ids without special tokens __a = tokenizer.encode(_A , add_special_tokens=_A , add_prefix_space=_A ) __a = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) # Testing conversion to ids with special tokens __a = self.get_rust_tokenizer(add_prefix_space=_A ) __a = tokenizer.encode(_A , add_prefix_space=_A ) __a = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) # Testing the unknown token __a = tokens + [rust_tokenizer.unk_token] __a = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(_A ) , _A ) def SCREAMING_SNAKE_CASE_ ( self , *_snake_case , **_snake_case ) -> Union[str, Any]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self , _snake_case=15 ) -> List[str]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __a = self.rust_tokenizer_class.from_pretrained(_A , **_A ) # Simple input __a = '''This is a simple input''' __a = ['''This is a simple input 1''', '''This is a simple input 2'''] __a = ('''This is a simple input''', '''This is a pair''') __a = [ ('''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 SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token='''<pad>''' ) # Simple input __a = '''This is a simple input''' __a = ['''This is a simple input looooooooong''', '''This is a simple input'''] __a = ('''This is a simple input''', '''This is a pair''') __a = [ ('''This is a simple input loooooong''', '''This is a simple input'''), ('''This is a simple pair loooooong''', '''This is a simple pair'''), ] __a = tokenizer.pad_token_id __a = tokenizer(_A , padding='''max_length''' , max_length=30 , return_tensors='''np''' ) __a = tokenizer(_A , padding=_A , truncate=_A , return_tensors='''np''' ) __a = tokenizer(*_A , padding='''max_length''' , max_length=60 , return_tensors='''np''' ) __a = 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 SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __a = '''$$$''' __a = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=_A , add_bos_token=_A ) __a = '''This is a simple input''' __a = ['''This is a simple input 1''', '''This is a simple input 2'''] __a = tokenizer.bos_token_id __a = tokenizer(_A ) __a = 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 ) ) __a = tokenizer.decode(out_s.input_ids ) __a = 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 SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = [self.get_tokenizer(do_lower_case=_A , add_bos_token=_A )] for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __a = '''Encode this.''' __a = '''This one too please.''' __a = tokenizer.encode(_A , add_special_tokens=_A ) encoded_sequence += tokenizer.encode(_A , add_special_tokens=_A ) __a = tokenizer.encode_plus( _A , _A , add_special_tokens=_A , return_special_tokens_mask=_A , ) __a = encoded_sequence_dict['''input_ids'''] __a = encoded_sequence_dict['''special_tokens_mask'''] self.assertEqual(len(_A ) , len(_A ) ) __a = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(_A ) ] __a = [x for x in filtered_sequence if x is not None] self.assertEqual(_A , _A ) @require_tokenizers class __A( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = AutoTokenizer.from_pretrained('''facebook/opt-350m''' , from_slow=_A ) __a = '''A photo of a cat''' __a = tokenizer.encode( _A , ) self.assertEqual(_A , [2, 250, 1_345, 9, 10, 4_758] ) tokenizer.save_pretrained('''test_opt''' ) __a = AutoTokenizer.from_pretrained('''./test_opt''' ) __a = tokenizer.encode( _A , ) self.assertEqual(_A , [2, 250, 1_345, 9, 10, 4_758] ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' __a = AutoTokenizer.from_pretrained('''facebook/opt-350m''' , use_slow=_A ) __a = '''A photo of a cat''' __a = tokenizer.encode( _A , ) # Same as above self.assertEqual(_A , [2, 250, 1_345, 9, 10, 4_758] ) @unittest.skip('''This test is failing because of a bug in the fast tokenizer''' ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = AutoTokenizer.from_pretrained('''facebook/opt-350m''' , from_slow=_A ) __a = '''bos''' __a = tokenizer.get_vocab()['''bos'''] __a = '''A photo of a cat''' __a = tokenizer.encode( _A , ) # We changed the bos token self.assertEqual(_A , [31_957, 250, 1_345, 9, 10, 4_758] ) tokenizer.save_pretrained('''./tok''' ) __a = AutoTokenizer.from_pretrained('''./tok''' ) self.assertTrue(tokenizer.is_fast ) __a = tokenizer.encode( _A , ) self.assertEqual(_A , [31_957, 250, 1_345, 9, 10, 4_758] )
6
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
0
from __future__ import annotations def a ( lowerCamelCase_ ): '''simple docstring''' if len(SCREAMING_SNAKE_CASE_ ) < 2: raise ValueError('''Monogons and Digons are not polygons in the Euclidean space''' ) if any(i <= 0 for i in nums ): raise ValueError('''All values must be greater than 0''' ) lowercase__ = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
207
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCamelCase__ = { """configuration_audio_spectrogram_transformer""": [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ASTConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = [ """AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """ASTForAudioClassification""", """ASTModel""", """ASTPreTrainedModel""", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ = ["""ASTFeatureExtractor"""] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase: Tuple = {'configuration_plbart': ['PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PLBartConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = ['PLBartTokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: int = [ 'PLBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'PLBartForCausalLM', 'PLBartForConditionalGeneration', 'PLBartForSequenceClassification', 'PLBartModel', 'PLBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure)
297
import argparse import os import re import packaging.version UpperCamelCase__ = """examples/""" UpperCamelCase__ = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } UpperCamelCase__ = { """init""": """src/transformers/__init__.py""", """setup""": """setup.py""", } UpperCamelCase__ = """README.md""" def _a ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[str] ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase , __lowerCAmelCase = REPLACE_PATTERNS[pattern] __lowerCAmelCase = replace.replace("VERSION" , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = re_pattern.sub(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): for folder, directories, fnames in os.walk(SCREAMING_SNAKE_CASE_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ , pattern="examples" ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if not patch: update_version_in_examples(SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = "🤗 Transformers currently provides the following architectures" __lowerCAmelCase = "1. Want to contribute a new model?" with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Find the start of the list. __lowerCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __lowerCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __lowerCAmelCase = lines[index].replace( "https://huggingface.co/docs/transformers/main/model_doc" , "https://huggingface.co/docs/transformers/model_doc" , ) index += 1 with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(SCREAMING_SNAKE_CASE_ ) def _a ( ): with open(REPLACE_FILES["init"] , "r" ) as f: __lowerCAmelCase = f.read() __lowerCAmelCase = REPLACE_PATTERNS["init"][0].search(SCREAMING_SNAKE_CASE_ ).groups()[0] return packaging.version.parse(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any]=False ): __lowerCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __lowerCAmelCase = default_version.base_version elif patch: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: __lowerCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. __lowerCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ , patch=SCREAMING_SNAKE_CASE_ ) if not patch: print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() def _a ( ): __lowerCAmelCase = get_version() __lowerCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" __lowerCAmelCase = current_version.base_version # Check with the user we got that right. __lowerCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(SCREAMING_SNAKE_CASE_ ) == 0: __lowerCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(SCREAMING_SNAKE_CASE_ ) print("Cleaning main README, don't forget to run `make fix-copies`." ) clean_main_ref_in_model_list() if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") UpperCamelCase__ = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
92
0
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) UpperCAmelCase : Optional[Any] = logging.getLogger() def __lowerCamelCase ( ): '''simple docstring''' lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""-f""" ) lowerCamelCase = parser.parse_args() return args.f class __lowercase ( snake_case__ ): """simple docstring""" def __A ( self ) -> Dict: '''simple docstring''' lowerCamelCase = logging.StreamHandler(sys.stdout ) logger.addHandler(_A ) def __A ( self , A ) -> List[Any]: '''simple docstring''' lowerCamelCase = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , """run_glue_deebert.py""" ) with patch.object(_A , """argv""" , _A ): lowerCamelCase = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(_A , 0.666 ) @slow @require_torch_non_multi_gpu def __A ( self ) -> Tuple: '''simple docstring''' lowerCamelCase = """\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n """.split() self.run_and_check(_A ) lowerCamelCase = """\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n """.split() self.run_and_check(_A ) lowerCamelCase = """\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n """.split() self.run_and_check(_A )
252
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 a__ ( snake_case__ , unittest.TestCase ): _a : Dict = KandinskyImgaImgPipeline _a : List[Any] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] _a : str = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] _a : List[Any] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _a : int = False @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 3_2 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.time_input_dim * 4 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return 1_0_0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) __lowerCAmelCase = MultilingualCLIP(_A ) __lowerCAmelCase = text_encoder.eval() return text_encoder @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = { "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, } __lowerCAmelCase = UNetaDConditionModel(**_A ) return model @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return { "block_out_channels": [3_2, 6_4], "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": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.manual_seed(0 ) __lowerCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_unet __lowerCAmelCase = self.dummy_movq __lowerCAmelCase = { "num_train_timesteps": 1_0_0_0, "beta_schedule": "linear", "beta_start": 0.0_00_85, "beta_end": 0.0_12, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } __lowerCAmelCase = DDIMScheduler(**_A ) __lowerCAmelCase = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(_A ) # create init_image __lowerCAmelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_A ) ).to(_A ) __lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCAmelCase = Image.fromarray(np.uinta(_A ) ).convert("RGB" ).resize((2_5_6, 2_5_6) ) if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "horse", "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 6_4, "width": 6_4, "num_inference_steps": 1_0, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "cpu" __lowerCAmelCase = self.get_dummy_components() __lowerCAmelCase = self.pipeline_class(**_A ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) __lowerCAmelCase = pipe(**self.get_dummy_inputs(_A ) ) __lowerCAmelCase = output.images __lowerCAmelCase = pipe( **self.get_dummy_inputs(_A ) , return_dict=_A , )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowerCAmelCase = np.array( [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33] ) 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 a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_img2img_frog.npy" ) __lowerCAmelCase = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) __lowerCAmelCase = "A red cartoon frog, 4k" __lowerCAmelCase = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(_A ) __lowerCAmelCase = KandinskyImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipeline.to(_A ) pipeline.set_progress_bar_config(disable=_A ) __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase , __lowerCAmelCase = pipe_prior( _A , generator=_A , num_inference_steps=5 , negative_prompt="" , ).to_tuple() __lowerCAmelCase = pipeline( _A , image=_A , image_embeds=_A , negative_image_embeds=_A , generator=_A , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A )
92
0
'''simple docstring''' import numpy as np def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = 1e-12 , _lowerCAmelCase = 100 , ) -> Optional[int]: assert np.shape(SCREAMING_SNAKE_CASE_ )[0] == np.shape(SCREAMING_SNAKE_CASE_ )[1] # Ensure proper dimensionality. assert np.shape(SCREAMING_SNAKE_CASE_ )[0] == np.shape(SCREAMING_SNAKE_CASE_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(SCREAMING_SNAKE_CASE_ ) == np.iscomplexobj(SCREAMING_SNAKE_CASE_ ) snake_case__ : Union[str, Any] = np.iscomplexobj(SCREAMING_SNAKE_CASE_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(SCREAMING_SNAKE_CASE_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. snake_case__ : int = False snake_case__ : Optional[int] = 0 snake_case__ : Optional[int] = 0 snake_case__ : Optional[Any] = 1e12 while not convergence: # Multiple matrix by the vector. snake_case__ : Union[str, Any] = np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Normalize the resulting output vector. snake_case__ : int = w / np.linalg.norm(SCREAMING_SNAKE_CASE_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) snake_case__ : str = vector.conj().T if is_complex else vector.T snake_case__ : Union[str, Any] = np.dot(SCREAMING_SNAKE_CASE_ , np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Check convergence. snake_case__ : Tuple = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: snake_case__ : Union[str, Any] = True snake_case__ : Union[str, Any] = lambda_ if is_complex: snake_case__ : Any = np.real(lambda_ ) return lambda_, vector def __snake_case( ) -> Tuple: snake_case__ : List[Any] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) snake_case__ : Optional[int] = np.array([41, 4, 20] ) snake_case__ : List[Any] = real_input_matrix.astype(np.complexaaa ) snake_case__ : Tuple = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T snake_case__ : Tuple = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": snake_case__ : Any = real_input_matrix snake_case__ : List[str] = real_vector elif problem_type == "complex": snake_case__ : Tuple = complex_input_matrix snake_case__ : int = complex_vector # Our implementation. snake_case__ , snake_case__ : Optional[int] = power_iteration(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). snake_case__ , snake_case__ : int = np.linalg.eigh(SCREAMING_SNAKE_CASE_ ) # Last eigenvalue is the maximum one. snake_case__ : Union[str, Any] = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. snake_case__ : Union[str, Any] = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(SCREAMING_SNAKE_CASE_ ) - np.abs(SCREAMING_SNAKE_CASE_ ) ) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
35
class a__ ( snake_case__ ): pass class a__ ( snake_case__ ): pass class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [ [], [], [], ] def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError("Maximum queue size is 100" ) self.queues[priority].append(_A ) except IndexError: raise ValueError("Valid priorities are 0, 1, and 2" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("All queues are empty" ) def __str__( self ): """simple docstring""" return "\n".join(f"""Priority {i}: {q}""" for i, q in enumerate(self.queues ) ) class a__ : def __init__( self ): """simple docstring""" __lowerCAmelCase = [] def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" if len(self.queue ) == 1_0_0: raise OverFlowError("Maximum queue size is 100" ) self.queue.append(_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.queue: raise UnderFlowError("The queue is empty" ) else: __lowerCAmelCase = min(self.queue ) self.queue.remove(_A ) return data def __str__( self ): """simple docstring""" return str(self.queue ) def _a ( ): __lowerCAmelCase = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): __lowerCAmelCase = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(SCREAMING_SNAKE_CASE_ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
92
0
'''simple docstring''' def snake_case ( UpperCAmelCase )-> List[Any]: """simple docstring""" __A , __A = [], [] while len(SCREAMING_SNAKE_CASE_ ) > 1: __A , __A = min(SCREAMING_SNAKE_CASE_ ), max(SCREAMING_SNAKE_CASE_ ) start.append(SCREAMING_SNAKE_CASE_ ) end.append(SCREAMING_SNAKE_CASE_ ) collection.remove(SCREAMING_SNAKE_CASE_ ) collection.remove(SCREAMING_SNAKE_CASE_ ) end.reverse() return start + collection + end if __name__ == "__main__": a__ : str = input("Enter numbers separated by a comma:\n").strip() a__ : List[str] = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
161
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a__ : def __init__( self , _A , _A=1_3 , _A=3_0 , _A=2 , _A=3 , _A=True , _A=True , _A=3_2 , _A=5 , _A=4 , _A=3_7 , _A="gelu" , _A=0.1 , _A=0.1 , _A=1_0 , _A=0.02 , _A=3 , _A=None , _A=2 , ): """simple docstring""" __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = image_size __lowerCAmelCase = patch_size __lowerCAmelCase = num_channels __lowerCAmelCase = is_training __lowerCAmelCase = use_labels __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = scope __lowerCAmelCase = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __lowerCAmelCase = (image_size // patch_size) ** 2 __lowerCAmelCase = num_patches + 2 def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = self.get_config() return config, pixel_values, labels def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTModel(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = DeiTForMaskedImageModeling(config=_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForMaskedImageModeling(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = self.type_sequence_label_size __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __lowerCAmelCase = 1 __lowerCAmelCase = DeiTForImageClassification(_A ) model.to(_A ) model.eval() __lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowerCAmelCase = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = config_and_inputs __lowerCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a__ ( snake_case__ , snake_case__ , unittest.TestCase ): _a : Optional[Any] = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) _a : int = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) _a : Optional[Any] = False _a : Tuple = False _a : Tuple = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=3_7 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_A , nn.Linear ) ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCAmelCase = model_class(_A ) __lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCAmelCase = [*signature.parameters.keys()] __lowerCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=False ): """simple docstring""" __lowerCAmelCase = super()._prepare_for_class(_A , _A , return_labels=_A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.model_tester.is_training: return __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return __lowerCAmelCase = False __lowerCAmelCase = True for model_class in self.all_model_classes: if model_class in get_values(_A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue __lowerCAmelCase = model_class(_A ) model.gradient_checkpointing_enable() model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) __lowerCAmelCase = model(**_A ).loss loss.backward() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCAmelCase = [ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, {"title": "regression", "num_labels": 1, "dtype": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_A ), *get_values(_A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"""Testing {model_class} with {problem_type['title']}""" ): __lowerCAmelCase = problem_type["title"] __lowerCAmelCase = problem_type["num_labels"] __lowerCAmelCase = model_class(_A ) model.to(_A ) model.train() __lowerCAmelCase = self._prepare_for_class(_A , _A , return_labels=_A ) if problem_type["num_labels"] > 1: __lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) __lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_A ) as warning_list: __lowerCAmelCase = model(**_A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = DeiTModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _a ( ): __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a__ ( unittest.TestCase ): @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( _A ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ).to(_A ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**_A ) # verify the logits __lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _A ) __lowerCAmelCase = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) __lowerCAmelCase = self.default_image_processor __lowerCAmelCase = prepare_img() __lowerCAmelCase = image_processor(images=_A , return_tensors="pt" ) __lowerCAmelCase = inputs.pixel_values.to(_A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __lowerCAmelCase = model(_A )
92
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_rembert''': ['''REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RemBertConfig''', '''RemBertOnnxConfig'''] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''RemBertTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''RemBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RemBertForCausalLM''', '''RemBertForMaskedLM''', '''RemBertForMultipleChoice''', '''RemBertForQuestionAnswering''', '''RemBertForSequenceClassification''', '''RemBertForTokenClassification''', '''RemBertLayer''', '''RemBertModel''', '''RemBertPreTrainedModel''', '''load_tf_weights_in_rembert''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRemBertForCausalLM''', '''TFRemBertForMaskedLM''', '''TFRemBertForMultipleChoice''', '''TFRemBertForQuestionAnswering''', '''TFRemBertForSequenceClassification''', '''TFRemBertForTokenClassification''', '''TFRemBertLayer''', '''TFRemBertModel''', '''TFRemBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
153
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
92
0
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING __snake_case = logging.get_logger(__name__) @add_end_docstrings(snake_case__ ) class _lowerCAmelCase ( snake_case__ ): def __init__( self , **UpperCamelCase__ ) -> Optional[int]: '''simple docstring''' super().__init__(**_A ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , "vision" ) self.check_model_type(_A ) def __call__( self , UpperCamelCase__ , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> Union[str, Any]: '''simple docstring''' if "text_queries" in kwargs: snake_case : Dict = kwargs.pop("text_queries" ) if isinstance(_A , (str, Image.Image) ): snake_case : Optional[int] = {"image": image, "candidate_labels": candidate_labels} else: snake_case : str = image snake_case : Any = super().__call__(_A , **_A ) return results def lowerCamelCase ( self , **UpperCamelCase__ ) -> Optional[int]: '''simple docstring''' snake_case : Optional[int] = {} if "threshold" in kwargs: snake_case : Any = kwargs["threshold"] if "top_k" in kwargs: snake_case : Dict = kwargs["top_k"] return {}, {}, postprocess_params def lowerCamelCase ( self , UpperCamelCase__ ) -> List[str]: '''simple docstring''' snake_case : int = load_image(inputs["image"] ) snake_case : Union[str, Any] = inputs["candidate_labels"] if isinstance(_A , _A ): snake_case : List[str] = candidate_labels.split("," ) snake_case : List[str] = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(_A ): snake_case : Union[str, Any] = self.tokenizer(_A , return_tensors=self.framework ) snake_case : Optional[int] = self.image_processor(_A , return_tensors=self.framework ) yield { "is_last": i == len(_A ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def lowerCamelCase ( self , UpperCamelCase__ ) -> Any: '''simple docstring''' snake_case : Optional[int] = model_inputs.pop("target_size" ) snake_case : Union[str, Any] = model_inputs.pop("candidate_label" ) snake_case : Tuple = model_inputs.pop("is_last" ) snake_case : str = self.model(**_A ) snake_case : Dict = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs} return model_outputs def lowerCamelCase ( self , UpperCamelCase__ , UpperCamelCase__=0.1 , UpperCamelCase__=None ) -> List[Any]: '''simple docstring''' snake_case : Union[str, Any] = [] for model_output in model_outputs: snake_case : Optional[Any] = model_output["candidate_label"] snake_case : Dict = BaseModelOutput(_A ) snake_case : int = self.image_processor.post_process_object_detection( outputs=_A , threshold=_A , target_sizes=model_output["target_size"] )[0] for index in outputs["scores"].nonzero(): snake_case : Any = outputs["scores"][index].item() snake_case : List[Any] = self._get_bounding_box(outputs["boxes"][index][0] ) snake_case : Optional[int] = {"score": score, "label": label, "box": box} results.append(_A ) snake_case : Optional[Any] = sorted(_A , key=lambda UpperCamelCase__ : x["score"] , reverse=_A ) if top_k: snake_case : int = results[:top_k] return results def lowerCamelCase ( self , UpperCamelCase__ ) -> Optional[int]: '''simple docstring''' if self.framework != "pt": raise ValueError("The ZeroShotObjectDetectionPipeline is only available in PyTorch." ) snake_case ,snake_case ,snake_case ,snake_case : Tuple = box.int().tolist() snake_case : Optional[int] = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
203
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
92
0
'''simple docstring''' import math class a : def A_ ( self : Tuple , lowercase_ : Optional[int] , lowercase_ : Optional[Any] ): snake_case_ = 0.0 snake_case_ = 0.0 for i in range(len(_A ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def A_ ( self : Tuple , lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : Optional[int] , lowercase_ : List[str] ): for i in range(len(_A ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def __magic_name__ ( ) -> Optional[Any]: '''simple docstring''' snake_case_ = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) snake_case_ = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training snake_case_ = SelfOrganizingMap() snake_case_ = 3 snake_case_ = 0.5 for _ in range(SCREAMING_SNAKE_CASE_ ): for j in range(len(SCREAMING_SNAKE_CASE_ ) ): # training sample snake_case_ = training_samples[j] # Compute the winning vector snake_case_ = self_organizing_map.get_winner(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) # Update the winning vector snake_case_ = self_organizing_map.update(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) # classify test sample snake_case_ = [0, 0, 0, 1] snake_case_ = self_organizing_map.get_winner(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) # results print(F"Clusters that the test sample belongs to : {winner}" ) print(F"Weights that have been trained : {weights}" ) # running the main() function if __name__ == "__main__": main()
56
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version(""">=""", FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType UpperCamelCase__ = get_logger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if accelerator.process_index == 0: logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {output_model_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model saved to {output_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving model to {ckpt_dir}""" ) __lowerCAmelCase = {"model": state_dict} dist_cp.save_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Model saved to {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(SCREAMING_SNAKE_CASE_ ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " "initializing FSDP object" ) return __lowerCAmelCase = F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin""" __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: __lowerCAmelCase = ( F"""{MODEL_NAME}_rank{accelerator.process_index}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading model from {input_model_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Model loaded from {input_model_file}""" ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{MODEL_NAME}_{model_index}""" ) if F"""{MODEL_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading model from {ckpt_dir}""" ) __lowerCAmelCase = {"model": model.state_dict()} dist_cp.load_state_dict( state_dict=SCREAMING_SNAKE_CASE_ , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , planner=DefaultLoadPlanner() , ) __lowerCAmelCase = state_dict["model"] logger.info(F"""Model loaded from {ckpt_dir}""" ) model.load_state_dict(SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : str=0 ): os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): __lowerCAmelCase = FSDP.optim_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {output_optimizer_file}""" ) torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state saved in {output_optimizer_file}""" ) else: __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) logger.info(F"""Saving Optimizer state to {ckpt_dir}""" ) dist_cp.save_state_dict( state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(SCREAMING_SNAKE_CASE_ ) , planner=DefaultSavePlanner() , ) logger.info(F"""Optimizer state saved in {ckpt_dir}""" ) def _a ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( SCREAMING_SNAKE_CASE_ , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: __lowerCAmelCase = None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: __lowerCAmelCase = ( F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin""" ) __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) logger.info(F"""Loading Optimizer state from {input_optimizer_file}""" ) __lowerCAmelCase = torch.load(SCREAMING_SNAKE_CASE_ ) logger.info(F"""Optimizer state loaded from {input_optimizer_file}""" ) else: __lowerCAmelCase = ( os.path.join(SCREAMING_SNAKE_CASE_ , F"""{OPTIMIZER_NAME}_{optimizer_index}""" ) if F"""{OPTIMIZER_NAME}""" not in input_dir else input_dir ) logger.info(F"""Loading Optimizer from {ckpt_dir}""" ) __lowerCAmelCase = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(SCREAMING_SNAKE_CASE_ ) , ) __lowerCAmelCase = optim_state["optimizer"] logger.info(F"""Optimizer loaded from {ckpt_dir}""" ) __lowerCAmelCase = FSDP.optim_state_dict_to_load(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) optimizer.load_state_dict(SCREAMING_SNAKE_CASE_ )
92
0
'''simple docstring''' # limitations under the License. from typing import Optional, Tuple, Union import torch from diffusers import DiffusionPipeline, ImagePipelineOutput class __UpperCamelCase ( snake_case__ ): def __init__( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" super().__init__() self.register_modules(unet=_A, scheduler=_A ) @torch.no_grad() def __call__( self, lowerCAmelCase = 1, lowerCAmelCase = None, lowerCAmelCase = 50, lowerCAmelCase = "pil", lowerCAmelCase = True, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =torch.randn( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size), generator=_A, ) lowerCamelCase_ =image.to(self.device ) # set step values self.scheduler.set_timesteps(_A ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowerCamelCase_ =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 lowerCamelCase_ =self.scheduler.step(_A, _A, _A ).prev_sample lowerCamelCase_ =(image / 2 + 0.5).clamp(0, 1 ) lowerCamelCase_ =image.cpu().permute(0, 2, 3, 1 ).numpy() if output_type == "pil": lowerCamelCase_ =self.numpy_to_pil(_A ) if not return_dict: return (image,), "This is a local test" return ImagePipelineOutput(images=_A ), "This is a local test"
75
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class a__ ( snake_case__ ): def __init__( self , *_A , _A=None , _A=None , **_A ): """simple docstring""" super().__init__(*_A , **_A ) __lowerCAmelCase = eval_examples __lowerCAmelCase = post_process_function def __SCREAMING_SNAKE_CASE( self , _A = None , _A=None , _A = None , _A = "eval" , **_A , ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = ( gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length ) __lowerCAmelCase = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams ) __lowerCAmelCase = gen_kwargs __lowerCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset __lowerCAmelCase = self.get_eval_dataloader(_A ) __lowerCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default __lowerCAmelCase = self.post_process_function(_A , _A , _A ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) else: __lowerCAmelCase = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(_A ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) __lowerCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , _A ) return metrics def __SCREAMING_SNAKE_CASE( self , _A , _A , _A=None , _A = "test" , **_A ): """simple docstring""" __lowerCAmelCase = gen_kwargs.copy() __lowerCAmelCase = self.get_test_dataloader(_A ) # Temporarily disable metric computation, we will do it in the loop here. __lowerCAmelCase = self.compute_metrics __lowerCAmelCase = None __lowerCAmelCase = time.time() __lowerCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: __lowerCAmelCase = eval_loop( _A , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=_A , metric_key_prefix=_A , ) finally: __lowerCAmelCase = compute_metrics __lowerCAmelCase = self.args.eval_batch_size * self.args.world_size if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics: start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""] output.metrics.update( speed_metrics( _A , _A , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output __lowerCAmelCase = self.post_process_function(_A , _A , _A , "predict" ) __lowerCAmelCase = self.compute_metrics(_A ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): __lowerCAmelCase = metrics.pop(_A ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=_A )
92
0
"""simple docstring""" import pickle import numpy as np from matplotlib import pyplot as plt class a : def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=0.2 , _lowerCamelCase=0.2 ): lowercase = bp_numa lowercase = bp_numa lowercase = bp_numa lowercase = conva_get[:2] lowercase = conva_get[2] lowercase = size_pa lowercase = rate_w lowercase = rate_t lowercase = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] lowercase = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowercase = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowercase = -2 * np.random.rand(self.conva[1] ) + 1 lowercase = -2 * np.random.rand(self.num_bpa ) + 1 lowercase = -2 * np.random.rand(self.num_bpa ) + 1 def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = { 'num_bp1': self.num_bpa, 'num_bp2': self.num_bpa, 'num_bp3': self.num_bpa, 'conv1': self.conva, 'step_conv1': self.step_conva, 'size_pooling1': self.size_poolinga, 'rate_weight': self.rate_weight, 'rate_thre': self.rate_thre, 'w_conv1': self.w_conva, 'wkj': self.wkj, 'vji': self.vji, 'thre_conv1': self.thre_conva, 'thre_bp2': self.thre_bpa, 'thre_bp3': self.thre_bpa, } with open(_A , 'wb' ) as f: pickle.dump(_A , _A ) print(F'Model saved: {save_path}' ) @classmethod def UpperCamelCase_ ( cls , _lowerCamelCase ): with open(_A , 'rb' ) as f: lowercase = pickle.load(_A ) # noqa: S301 lowercase = model_dic.get('conv1' ) conv_get.append(model_dic.get('step_conv1' ) ) lowercase = model_dic.get('size_pooling1' ) lowercase = model_dic.get('num_bp1' ) lowercase = model_dic.get('num_bp2' ) lowercase = model_dic.get('num_bp3' ) lowercase = model_dic.get('rate_weight' ) lowercase = model_dic.get('rate_thre' ) # create model instance lowercase = CNN(_A , _A , _A , _A , _A , _A , _A ) # modify model parameter lowercase = model_dic.get('w_conv1' ) lowercase = model_dic.get('wkj' ) lowercase = model_dic.get('vji' ) lowercase = model_dic.get('thre_conv1' ) lowercase = model_dic.get('thre_bp2' ) lowercase = model_dic.get('thre_bp3' ) return conv_ins def UpperCamelCase_ ( self , _lowerCamelCase ): return 1 / (1 + np.exp(-1 * x )) def UpperCamelCase_ ( self , _lowerCamelCase ): return round(_A , 3 ) def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): lowercase = convs[0] lowercase = convs[1] lowercase = np.shape(_A )[0] # get the data slice of original image data, data_focus lowercase = [] for i_focus in range(0 , size_data - size_conv + 1 , _A ): for j_focus in range(0 , size_data - size_conv + 1 , _A ): lowercase = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(_A ) # calculate the feature map of every single kernel, and saved as list of matrix lowercase = [] lowercase = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(_A ): lowercase = [] for i_focus in range(len(_A ) ): lowercase = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(_A ) ) lowercase = np.asmatrix(_A ).reshape( _A , _A ) data_featuremap.append(_A ) # expanding the data slice to One dimenssion lowercase = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(_A ) ) lowercase = np.asarray(_A ) return focus_list, data_featuremap def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase="average_pool" ): lowercase = len(featuremaps[0] ) lowercase = int(size_map / size_pooling ) lowercase = [] for i_map in range(len(_A ) ): lowercase = featuremaps[i_map] lowercase = [] for i_focus in range(0 , _A , _A ): for j_focus in range(0 , _A , _A ): lowercase = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(_A ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(_A ) ) lowercase = np.asmatrix(_A ).reshape(_A , _A ) featuremap_pooled.append(_A ) return featuremap_pooled def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = [] for i in range(len(_A ) ): lowercase = np.shape(data[i] ) lowercase = data[i].reshape(1 , shapes[0] * shapes[1] ) lowercase = data_listed.getA().tolist()[0] data_expanded.extend(_A ) lowercase = np.asarray(_A ) return data_expanded def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = np.asarray(_A ) lowercase = np.shape(_A ) lowercase = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): lowercase = [] lowercase = 0 for i_map in range(_A ): lowercase = np.ones((size_map, size_map) ) for i in range(0 , _A , _A ): for j in range(0 , _A , _A ): lowercase = pd_pool[ i_pool ] lowercase = i_pool + 1 lowercase = np.multiply( _A , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(_A ) return pd_all def UpperCamelCase_ ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=bool ): print('----------------------Start Training-------------------------' ) print((' - - Shape: Train_Data ', np.shape(_A )) ) print((' - - Shape: Teach_Data ', np.shape(_A )) ) lowercase = 0 lowercase = [] lowercase = 1_0_0_0_0 while rp < n_repeat and mse >= error_accuracy: lowercase = 0 print(F'-------------Learning Time {rp}--------------' ) for p in range(len(_A ) ): # print('------------Learning Image: %d--------------'%p) lowercase = np.asmatrix(datas_train[p] ) lowercase = np.asarray(datas_teach[p] ) lowercase , lowercase = self.convolute( _A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowercase = self.pooling(_A , self.size_poolinga ) lowercase = np.shape(_A ) lowercase = self._expand(_A ) lowercase = data_bp_input lowercase = np.dot(_A , self.vji.T ) - self.thre_bpa lowercase = self.sig(_A ) lowercase = np.dot(_A , self.wkj.T ) - self.thre_bpa lowercase = self.sig(_A ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- lowercase = np.multiply( (data_teach - bp_outa) , np.multiply(_A , (1 - bp_outa) ) ) lowercase = np.multiply( np.dot(_A , self.wkj ) , np.multiply(_A , (1 - bp_outa) ) ) lowercase = np.dot(_A , self.vji ) lowercase = pd_i_all / (self.size_poolinga * self.size_poolinga) lowercase = pd_conva_pooled.T.getA().tolist() lowercase = self._calculate_gradient_from_pool( _A , _A , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): lowercase = self._expand_mat(pd_conva_all[k_conv] ) lowercase = self.rate_weight * np.dot(_A , _A ) lowercase = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) lowercase = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer lowercase = self.wkj + pd_k_all.T * bp_outa * self.rate_weight lowercase = self.vji + pd_j_all.T * bp_outa * self.rate_weight lowercase = self.thre_bpa - pd_k_all * self.rate_thre lowercase = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image lowercase = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) lowercase = rp + 1 lowercase = error_count / patterns all_mse.append(_A ) def draw_error(): lowercase = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(_A , '+-' ) plt.plot(_A , 'r--' ) plt.xlabel('Learning Times' ) plt.ylabel('All_mse' ) plt.grid(_A , alpha=0.5 ) plt.show() print('------------------Training Complished---------------------' ) print((' - - Training epoch: ', rp, F' - - Mse: {mse:.6f}') ) if draw_e: draw_error() return mse def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = [] print('-------------------Start Testing-------------------------' ) print((' - - Shape: Test_Data ', np.shape(_A )) ) for p in range(len(_A ) ): lowercase = np.asmatrix(datas_test[p] ) lowercase , lowercase = self.convolute( _A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowercase = self.pooling(_A , self.size_poolinga ) lowercase = self._expand(_A ) lowercase = data_bp_input lowercase = bp_outa * self.vji.T - self.thre_bpa lowercase = self.sig(_A ) lowercase = bp_outa * self.wkj.T - self.thre_bpa lowercase = self.sig(_A ) produce_out.extend(bp_outa.getA().tolist() ) lowercase = [list(map(self.do_round , _A ) ) for each in produce_out] return np.asarray(_A ) def UpperCamelCase_ ( self , _lowerCamelCase ): lowercase = np.asmatrix(_A ) lowercase , lowercase = self.convolute( _A , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowercase = self.pooling(_A , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
220
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 _a ( SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = filter(lambda SCREAMING_SNAKE_CASE_ : p.requires_grad , model.parameters() ) __lowerCAmelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCamelCase__ = logging.getLogger(__name__) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any ): if metric == "rouge2": __lowerCAmelCase = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": __lowerCAmelCase = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": __lowerCAmelCase = "{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." ) __lowerCAmelCase = 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 _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return EarlyStopping( monitor=F"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=SCREAMING_SNAKE_CASE_ , verbose=SCREAMING_SNAKE_CASE_ , ) class a__ ( pl.Callback ): def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = {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 __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCAmelCase = 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 __lowerCAmelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCAmelCase = od / "test_results.txt" __lowerCAmelCase = 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. __lowerCAmelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCAmelCase = 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 __lowerCAmelCase = metrics[key] if isinstance(_A , torch.Tensor ): __lowerCAmelCase = val.item() __lowerCAmelCase = f"""{key}: {val:.6f}\n""" writer.write(_A ) if not save_generations: return if "preds" in metrics: __lowerCAmelCase = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(_A ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" try: __lowerCAmelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCAmelCase = pl_module.model.num_parameters() __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_A , _A , "test" ) @rank_zero_only def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
92
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A : Any = logging.get_logger(__name__) A : List[Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'} A : Tuple = { 'vocab_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json' ), }, 'merges_file': { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt', 'allenai/longformer-large-4096': ( 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt' ), }, } A : str = { 'allenai/longformer-base-4096': 4_0_9_6, 'allenai/longformer-large-4096': 4_0_9_6, 'allenai/longformer-large-4096-finetuned-triviaqa': 4_0_9_6, 'allenai/longformer-base-4096-extra.pos.embd.only': 4_0_9_6, 'allenai/longformer-large-4096-extra.pos.embd.only': 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def __lowerCAmelCase ( ) -> str: __a = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) __a = bs[:] __a = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE_ ) cs.append(2**8 + n ) n += 1 __a = [chr(SCREAMING_SNAKE_CASE_ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def __lowerCAmelCase ( a__ ) -> Optional[Any]: __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char return pairs class __A( snake_case__ ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["""input_ids""", """attention_mask"""] def __init__( self , _snake_case , _snake_case , _snake_case="replace" , _snake_case="<s>" , _snake_case="</s>" , _snake_case="</s>" , _snake_case="<s>" , _snake_case="<unk>" , _snake_case="<pad>" , _snake_case="<mask>" , _snake_case=False , **_snake_case , ) -> List[Any]: '''simple docstring''' __a = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else bos_token __a = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else eos_token __a = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else sep_token __a = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else cls_token __a = AddedToken(_A , lstrip=_A , rstrip=_A ) if isinstance(_A , _A ) else unk_token __a = 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 __a = 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: __a = json.load(_A ) __a = {v: k for k, v in self.encoder.items()} __a = errors # how to handle errors in decoding __a = bytes_to_unicode() __a = {v: k for k, v in self.byte_encoder.items()} with open(_A , encoding='''utf-8''' ) as merges_handle: __a = merges_handle.read().split('''\n''' )[1:-1] __a = [tuple(merge.split() ) for merge in bpe_merges] __a = dict(zip(_A , range(len(_A ) ) ) ) __a = {} __a = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __a = re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' return len(self.encoder ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Union[str, Any]: '''simple docstring''' if token in self.cache: return self.cache[token] __a = tuple(_A ) __a = get_pairs(_A ) if not pairs: return token while True: __a = min(_A , key=lambda _snake_case : self.bpe_ranks.get(_A , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(_A ): try: __a = word.index(_A , _A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = 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 __a = tuple(_A ) __a = new_word if len(_A ) == 1: break else: __a = get_pairs(_A ) __a = ''' '''.join(_A ) __a = word return word def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Union[str, Any]: '''simple docstring''' __a = [] for token in re.findall(self.pat , _A ): __a = ''''''.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 SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> Dict: '''simple docstring''' return self.encoder.get(_A , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> int: '''simple docstring''' return self.decoder.get(_A ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case ) -> List[str]: '''simple docstring''' __a = ''''''.join(_A ) __a = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case = None ) -> Optional[int]: '''simple docstring''' if not os.path.isdir(_A ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __a = os.path.join( _A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) __a = 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''' ) __a = 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 _snake_case : 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!''' ) __a = token_index writer.write(''' '''.join(_A ) + '''\n''' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case = None ) -> str: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __a = [self.cls_token_id] __a = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case = None , _snake_case = False ) -> List[str]: '''simple docstring''' 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 SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case = None ) -> Union[str, Any]: '''simple docstring''' __a = [self.sep_token_id] __a = [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 SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case=False , **_snake_case ) -> Dict: '''simple docstring''' __a = 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()): __a = ''' ''' + text return (text, kwargs)
6
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
92
0
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process A__ : Any = logging.getLogger(__name__) def a ( lowerCamelCase_ , lowerCamelCase_ ): '''simple docstring''' return (preds == labels).mean() @dataclass class _UpperCAmelCase : """simple docstring""" lowercase__ = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) lowercase__ = field( default=snake_case__ ,metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) lowercase__ = field( default=snake_case__ ,metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) lowercase__ = field( default=snake_case__ ,metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} ,) @dataclass class _UpperCAmelCase : """simple docstring""" lowercase__ = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(processors.keys() )} ) lowercase__ = field(metadata={"""help""": """Should contain the data files for the task."""} ) lowercase__ = field( default=128 ,metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } ,) lowercase__ = field( default=snake_case__ ,metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def a ( ): '''simple docstring''' # 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. lowercase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowercase__ , lowercase__ , lowercase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('''Training/evaluation parameters %s''' , SCREAMING_SNAKE_CASE_ ) # Set seed set_seed(training_args.seed ) try: lowercase__ = processors[data_args.task_name]() lowercase__ = processor.get_labels() lowercase__ = len(SCREAMING_SNAKE_CASE_ ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=SCREAMING_SNAKE_CASE_ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) lowercase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowercase__ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE_ , cache_dir=model_args.cache_dir , ) # Get datasets lowercase__ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowercase__ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=SCREAMING_SNAKE_CASE_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(lowerCamelCase_ ) -> Dict: lowercase__ = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(SCREAMING_SNAKE_CASE_ , p.label_ids )} # Data collator lowercase__ = DataCollatorWithPadding(SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowercase__ = Trainer( model=SCREAMING_SNAKE_CASE_ , args=SCREAMING_SNAKE_CASE_ , train_dataset=SCREAMING_SNAKE_CASE_ , eval_dataset=SCREAMING_SNAKE_CASE_ , compute_metrics=SCREAMING_SNAKE_CASE_ , data_collator=SCREAMING_SNAKE_CASE_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowercase__ = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) lowercase__ = trainer.evaluate() lowercase__ = os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): with open(SCREAMING_SNAKE_CASE_ , '''w''' ) as writer: logger.info('''***** Eval results *****''' ) for key, value in result.items(): logger.info(''' %s = %s''' , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) writer.write('''%s = %s\n''' % (key, value) ) results.update(SCREAMING_SNAKE_CASE_ ) return results def a ( lowerCamelCase_ ): '''simple docstring''' # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
207
from queue import PriorityQueue from typing import Any import numpy as np def _a ( 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 __lowerCAmelCase = cst_fwd.get(SCREAMING_SNAKE_CASE_ , np.inf ) __lowerCAmelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCAmelCase = new_cost_f __lowerCAmelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCAmelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : dict , SCREAMING_SNAKE_CASE_ : dict ): __lowerCAmelCase = -1 __lowerCAmelCase = set() __lowerCAmelCase = set() __lowerCAmelCase = {source: 0} __lowerCAmelCase = {destination: 0} __lowerCAmelCase = {source: None} __lowerCAmelCase = {destination: None} __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = PriorityQueue() __lowerCAmelCase = 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(): __lowerCAmelCase , __lowerCAmelCase = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase , __lowerCAmelCase = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = 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_ , ) __lowerCAmelCase = 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: __lowerCAmelCase = shortest_distance return shortest_path_distance UpperCamelCase__ = { """B""": [["""C""", 1]], """C""": [["""D""", 1]], """D""": [["""F""", 1]], """E""": [["""B""", 1], ["""G""", 2]], """F""": [], """G""": [["""F""", 1]], } UpperCamelCase__ = { """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()
92
0
'''simple docstring''' import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class a__( unittest.TestCase ): def lowercase_ ( self : Optional[Any] , __snake_case : str , __snake_case : Dict ): a : Optional[Any] = jnp.ones((batch_size, length) ) / length return scores def lowercase_ ( self : str ): a : Tuple = None a : Optional[int] = 20 a : List[str] = self._get_uniform_logits(batch_size=2 , length=_A ) # tweak scores to not be uniform anymore a : int = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch a : int = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax a : str = jax.nn.softmax(_A , axis=-1 ) a : List[str] = FlaxTemperatureLogitsWarper(temperature=0.5 ) a : List[Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) a : Tuple = jax.nn.softmax(temp_dist_warper_sharper(_A , scores.copy() , cur_len=_A ) , axis=-1 ) a : str = jax.nn.softmax(temp_dist_warper_smoother(_A , scores.copy() , cur_len=_A ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def lowercase_ ( self : Any ): a : int = None a : Optional[int] = 10 a : List[str] = 2 # create ramp distribution a : int = np.broadcast_to(np.arange(_A )[None, :] , (batch_size, vocab_size) ).copy() a : List[Any] = ramp_logits[1:, : vocab_size // 2] + vocab_size a : List[Any] = FlaxTopKLogitsWarper(3 ) a : str = top_k_warp(_A , _A , cur_len=_A ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case a : Any = 5 a : Any = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) a : str = np.broadcast_to(np.arange(_A )[None, :] , (batch_size, length) ).copy() a : Dict = top_k_warp_safety_check(_A , _A , cur_len=_A ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def lowercase_ ( self : List[Any] ): a : Optional[Any] = None a : Optional[Any] = 10 a : str = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) a : Optional[Any] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) a : Optional[int] = FlaxTopPLogitsWarper(0.8 ) a : Dict = np.exp(top_p_warp(_A , _A , cur_len=_A ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 a : Union[str, Any] = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(_A , _A , atol=1e-3 ) ) # check edge cases with negative and extreme logits a : int = np.broadcast_to(np.arange(_A )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme a : str = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept a : List[str] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) a : Union[str, Any] = top_p_warp(_A , _A , cur_len=_A ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def lowercase_ ( self : int ): a : Dict = 20 a : Union[str, Any] = 4 a : Optional[int] = 0 a : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_A ) # check that min length is applied at length 5 a : Dict = ids_tensor((batch_size, 20) , vocab_size=20 ) a : str = 5 a : List[Any] = self._get_uniform_logits(_A , _A ) a : List[Any] = min_dist_processor(_A , _A , cur_len=_A ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float('inf' )] ) # check that min length is not applied anymore at length 15 a : int = self._get_uniform_logits(_A , _A ) a : Union[str, Any] = 15 a : Union[str, Any] = min_dist_processor(_A , _A , cur_len=_A ) self.assertFalse(jnp.isinf(_A ).any() ) def lowercase_ ( self : Any ): a : List[str] = 20 a : Dict = 4 a : str = 0 a : List[str] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A ) # check that all scores are -inf except the bos_token_id score a : Tuple = ids_tensor((batch_size, 1) , vocab_size=20 ) a : List[str] = 1 a : List[str] = self._get_uniform_logits(_A , _A ) a : Dict = logits_processor(_A , _A , cur_len=_A ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 a : int = 3 a : Any = self._get_uniform_logits(_A , _A ) a : List[str] = logits_processor(_A , _A , cur_len=_A ) self.assertFalse(jnp.isinf(_A ).any() ) def lowercase_ ( self : Dict ): a : List[Any] = 20 a : str = 4 a : Optional[int] = 0 a : Optional[Any] = 5 a : List[Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=_A , eos_token_id=_A ) # check that all scores are -inf except the eos_token_id when max_length is reached a : str = ids_tensor((batch_size, 4) , vocab_size=20 ) a : int = 4 a : Dict = self._get_uniform_logits(_A , _A ) a : List[str] = logits_processor(_A , _A , cur_len=_A ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached a : str = 3 a : Dict = self._get_uniform_logits(_A , _A ) a : Tuple = logits_processor(_A , _A , cur_len=_A ) self.assertFalse(jnp.isinf(_A ).any() ) def lowercase_ ( self : Any ): a : str = 4 a : int = 10 a : str = 15 a : Optional[int] = 2 a : Optional[Any] = 1 a : List[Any] = 15 # dummy input_ids and scores a : List[str] = ids_tensor((batch_size, sequence_length) , _A ) a : Any = input_ids.copy() a : Union[str, Any] = self._get_uniform_logits(_A , _A ) a : List[Any] = scores.copy() # instantiate all dist processors a : str = FlaxTemperatureLogitsWarper(temperature=0.5 ) a : Any = FlaxTopKLogitsWarper(3 ) a : str = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors a : Union[str, Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_A ) a : int = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A ) a : Any = FlaxForcedEOSTokenLogitsProcessor(max_length=_A , eos_token_id=_A ) a : str = 10 # no processor list a : Tuple = temp_dist_warp(_A , _A , cur_len=_A ) a : Any = top_k_warp(_A , _A , cur_len=_A ) a : List[Any] = top_p_warp(_A , _A , cur_len=_A ) a : Dict = min_dist_proc(_A , _A , cur_len=_A ) a : Optional[Any] = bos_dist_proc(_A , _A , cur_len=_A ) a : Any = eos_dist_proc(_A , _A , cur_len=_A ) # with processor list a : str = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) a : Any = processor(_A , _A , cur_len=_A ) # scores should be equal self.assertTrue(jnp.allclose(_A , _A , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def lowercase_ ( self : Union[str, Any] ): a : Tuple = 4 a : Optional[Any] = 10 a : Tuple = 15 a : str = 2 a : Tuple = 1 a : str = 15 # dummy input_ids and scores a : int = ids_tensor((batch_size, sequence_length) , _A ) a : List[str] = input_ids.copy() a : Union[str, Any] = self._get_uniform_logits(_A , _A ) a : Optional[Any] = scores.copy() # instantiate all dist processors a : List[Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) a : Optional[int] = FlaxTopKLogitsWarper(3 ) a : int = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors a : List[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_A ) a : Any = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_A ) a : int = FlaxForcedEOSTokenLogitsProcessor(max_length=_A , eos_token_id=_A ) a : List[Any] = 10 # no processor list def run_no_processor_list(__snake_case : int , __snake_case : Optional[int] , __snake_case : List[Any] ): a : Optional[Any] = temp_dist_warp(_A , _A , cur_len=_A ) a : Optional[Any] = top_k_warp(_A , _A , cur_len=_A ) a : int = top_p_warp(_A , _A , cur_len=_A ) a : Tuple = min_dist_proc(_A , _A , cur_len=_A ) a : List[Any] = bos_dist_proc(_A , _A , cur_len=_A ) a : Optional[int] = eos_dist_proc(_A , _A , cur_len=_A ) return scores # with processor list def run_processor_list(__snake_case : Union[str, Any] , __snake_case : Union[str, Any] , __snake_case : Any ): a : Union[str, Any] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) a : Optional[Any] = processor(_A , _A , cur_len=_A ) return scores a : Optional[Any] = jax.jit(_A ) a : Dict = jax.jit(_A ) a : List[Any] = jitted_run_no_processor_list(_A , _A , _A ) a : int = jitted_run_processor_list(_A , _A , _A ) # scores should be equal self.assertTrue(jnp.allclose(_A , _A , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
297
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { """edbeeching/decision-transformer-gym-hopper-medium""": ( """https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json""" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class a__ ( snake_case__ ): _a : Optional[int] = """decision_transformer""" _a : Optional[int] = ["""past_key_values"""] _a : Dict = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , _A=1_7 , _A=4 , _A=1_2_8 , _A=4_0_9_6 , _A=True , _A=1 , _A=1_0_2_4 , _A=3 , _A=1 , _A=None , _A="relu" , _A=0.1 , _A=0.1 , _A=0.1 , _A=1E-5 , _A=0.02 , _A=True , _A=True , _A=5_0_2_5_6 , _A=5_0_2_5_6 , _A=False , _A=False , **_A , ): """simple docstring""" __lowerCAmelCase = state_dim __lowerCAmelCase = act_dim __lowerCAmelCase = hidden_size __lowerCAmelCase = max_ep_len __lowerCAmelCase = action_tanh __lowerCAmelCase = vocab_size __lowerCAmelCase = n_positions __lowerCAmelCase = n_layer __lowerCAmelCase = n_head __lowerCAmelCase = n_inner __lowerCAmelCase = activation_function __lowerCAmelCase = resid_pdrop __lowerCAmelCase = embd_pdrop __lowerCAmelCase = attn_pdrop __lowerCAmelCase = layer_norm_epsilon __lowerCAmelCase = initializer_range __lowerCAmelCase = scale_attn_weights __lowerCAmelCase = use_cache __lowerCAmelCase = scale_attn_by_inverse_layer_idx __lowerCAmelCase = reorder_and_upcast_attn __lowerCAmelCase = bos_token_id __lowerCAmelCase = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
92
0
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
252
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): _a : str = StableUnCLIPPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_BATCH_PARAMS _a : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS _a : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _a : Optional[Any] = False def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 3_2 __lowerCAmelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=1_2 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1_0_0_0 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) __lowerCAmelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) __lowerCAmelCase = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) ) torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock2D", "DownBlock2D") , up_block_types=("UpBlock2D", "CrossAttnUpBlock2D") , block_out_channels=(3_2, 6_4) , attention_head_dim=(2, 4) , class_embed_type="projection" , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) __lowerCAmelCase = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type="v_prediction" , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL() __lowerCAmelCase = { # prior components "prior_tokenizer": prior_tokenizer, "prior_text_encoder": prior_text_encoder, "prior": prior, "prior_scheduler": prior_scheduler, # image noising components "image_normalizer": image_normalizer, "image_noising_scheduler": image_noising_scheduler, # regular denoising components "tokenizer": tokenizer, "text_encoder": text_encoder, "unet": unet, "scheduler": scheduler, "vae": vae, } return components def __SCREAMING_SNAKE_CASE( self , _A , _A=0 ): """simple docstring""" if str(_A ).startswith("mps" ): __lowerCAmelCase = torch.manual_seed(_A ) else: __lowerCAmelCase = torch.Generator(device=_A ).manual_seed(_A ) __lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "prior_num_inference_steps": 2, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device == "cpu" self._test_attention_slicing_forward_pass(test_max_difference=_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = torch_device in ["cpu", "mps"] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) __lowerCAmelCase = pipe("anime turle" , generator=_A , output_type="np" ) __lowerCAmelCase = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCAmelCase = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) __lowerCAmelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCAmelCase = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) __lowerCAmelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 1_0**9
92
0
'''simple docstring''' import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def __snake_case( _lowerCAmelCase ) -> Dict: monkeypatch.setattr("""datasets.utils.deprecation_utils._emitted_deprecation_warnings""" , set() ) @pytest.fixture def __snake_case( _lowerCAmelCase ) -> Optional[int]: class UpperCAmelCase_ : """simple docstring""" def __init__( self : List[Any] , snake_case_ : str ): snake_case__ : Union[str, Any] = metric_id class UpperCAmelCase_ : """simple docstring""" lowercase = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def lowerCamelCase ( self : Optional[int] ): return self._metrics monkeypatch.setattr("""datasets.inspect.huggingface_hub""" , HfhMock() ) @pytest.mark.parametrize( """func, args""" , [(load_metric, ("""metrics/mse""",)), (list_metrics, ()), (inspect_metric, ("""metrics/mse""", """tmp_path"""))] ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> str: if "tmp_path" in args: snake_case__ : Optional[int] = tuple(arg if arg != """tmp_path""" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="""https://huggingface.co/docs/evaluate""" ): func(*SCREAMING_SNAKE_CASE_ )
35
from typing import TYPE_CHECKING from ...utils import _LazyModule UpperCamelCase__ = {"""tokenization_wav2vec2_phoneme""": ["""Wav2Vec2PhonemeCTCTokenizer"""]} if TYPE_CHECKING: from .tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizer else: import sys UpperCamelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class UpperCamelCase__ : def __init__( self :Optional[Any] , _A :Optional[int] , _A :Optional[Any]=99 , _A :Optional[int]=13 , _A :int=16 , _A :str=7 , _A :List[Any]=True , _A :List[Any]=True , _A :Any=True , _A :List[str]=False , _A :int=True , _A :Union[str, Any]=2 , _A :List[str]=32 , _A :Optional[Any]=4 , _A :int=4 , _A :int=30 , _A :Dict=0 , _A :List[str]=1 , _A :Union[str, Any]=2 , _A :int=None , ) -> Optional[int]: '''simple docstring''' __A = parent __A = batch_size __A = decoder_seq_length # For common tests __A = self.decoder_seq_length __A = is_training __A = use_attention_mask __A = use_labels __A = vocab_size __A = d_model __A = d_model __A = decoder_layers __A = decoder_layers __A = decoder_ffn_dim __A = decoder_attention_heads __A = decoder_attention_heads __A = eos_token_id __A = bos_token_id __A = pad_token_id __A = decoder_start_token_id __A = use_cache __A = max_position_embeddings __A = None __A = decoder_seq_length __A = 2 __A = 1 def lowercase_ ( self :List[str] ) -> Any: '''simple docstring''' __A = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) __A = None if self.use_attention_mask: __A = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) __A = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def lowercase_ ( self :int , _A :Tuple , _A :Union[str, Any] , _A :Dict , _A :Any , ) -> int: '''simple docstring''' __A = True __A = TrOCRDecoder(config=_A ).to(_A ).eval() __A = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass __A = model(_A , use_cache=_A ) __A = model(_A ) __A = model(_A , use_cache=_A ) self.parent.assertTrue(len(_A ) == len(_A ) ) self.parent.assertTrue(len(_A ) == len(_A ) + 1 ) __A = outputs['past_key_values'] # create hypothetical next token and extent to next_input_ids __A = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and __A = torch.cat([input_ids, next_tokens] , dim=-1 ) __A = model(_A )['last_hidden_state'] __A = model(_A , past_key_values=_A )['last_hidden_state'] # select random slice __A = ids_tensor((1,) , output_from_past.shape[-1] ).item() __A = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() __A = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(_A , _A , atol=1E-3 ) def lowercase_ ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): UpperCAmelCase__ : List[Any] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () UpperCAmelCase__ : Dict = (TrOCRForCausalLM,) if is_torch_available() else () UpperCAmelCase__ : Union[str, Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} UpperCAmelCase__ : List[Any] = True UpperCAmelCase__ : Dict = False def lowercase_ ( self :Any ) -> List[str]: '''simple docstring''' __A = TrOCRStandaloneDecoderModelTester(self , is_training=_A ) __A = ConfigTester(self , config_class=_A ) def lowercase_ ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' pass def lowercase_ ( self :List[Any] ) -> Dict: '''simple docstring''' pass def lowercase_ ( self :Any ) -> Tuple: '''simple docstring''' pass def lowercase_ ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def lowercase_ ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*_A ) def lowercase_ ( self :Union[str, Any] ) -> Any: '''simple docstring''' return @unittest.skip('The model doesn\'t support left padding' ) # and it's not used enough to be worth fixing :) def lowercase_ ( self :Any ) -> Union[str, Any]: '''simple docstring''' pass
161
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 UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = 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 __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 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, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 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" , )
92
0
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" if not all(x.isalpha() for x in string ): raise ValueError("String must only contain alphabetic characters." ) UpperCamelCase = sorted(string.lower() ) return len(SCREAMING_SNAKE_CASE_ ) == len(set(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": lowerCAmelCase__ = input('''Enter a string ''').strip() lowerCAmelCase__ = is_isogram(input_str) print(f'''{input_str} is {'an' if isogram else 'not an'} isogram.''')
153
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf UpperCamelCase__ = logging.get_logger(__name__) @dataclass class a__ ( snake_case__ ): _a : List[str] = [ """no_inference""", """no_cuda""", """no_tpu""", """no_speed""", """no_memory""", """no_env_print""", """no_multi_process""", ] def __init__( self , **_A ): """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __lowerCAmelCase = deprecated_arg[3:] __lowerCAmelCase = not kwargs.pop(_A ) logger.warning( f"""{deprecated_arg} is depreciated. Please use --no-{positive_arg} or""" f""" {positive_arg}={kwargs[positive_arg]}""" ) __lowerCAmelCase = kwargs.pop("tpu_name" , self.tpu_name ) __lowerCAmelCase = kwargs.pop("device_idx" , self.device_idx ) __lowerCAmelCase = kwargs.pop("eager_mode" , self.eager_mode ) __lowerCAmelCase = kwargs.pop("use_xla" , self.use_xla ) super().__init__(**_A ) _a : str = field( default=snake_case__ , metadata={"""help""": """Name of TPU"""} , ) _a : int = field( default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , ) _a : bool = field(default=snake_case__ , metadata={"""help""": """Benchmark models in eager model."""} ) _a : bool = field( default=snake_case__ , metadata={ """help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.""" } , ) @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) __lowerCAmelCase = None if self.tpu: try: if self.tpu_name: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __lowerCAmelCase = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __lowerCAmelCase = None return tpu @cached_property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __lowerCAmelCase = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , "GPU" ) __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/gpu:{self.device_idx}""" ) else: tf.config.set_visible_devices([] , "GPU" ) # disable GPU __lowerCAmelCase = tf.distribute.OneDeviceStrategy(device=f"""/cpu:{self.device_idx}""" ) return strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_tpu is not None @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return self._setup_strategy @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) return tf.config.list_physical_devices("GPU" ) @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" requires_backends(self , ["tf"] ) if self.cuda: return len(self.gpu_list ) return 0 @property def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self.n_gpu > 0
92
0
"""simple docstring""" __snake_case = """Alexander Joslin""" import operator as op from .stack import Stack def __lowerCAmelCase ( lowercase : str ) -> int: """simple docstring""" snake_case : List[Any] = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} snake_case : List[Any] = Stack() snake_case : Tuple = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(SCREAMING_SNAKE_CASE_ ) ) elif i in operators: # RULE 2 operator_stack.push(SCREAMING_SNAKE_CASE_ ) elif i == ")": # RULE 4 snake_case : int = operator_stack.peek() operator_stack.pop() snake_case : Dict = operand_stack.peek() operand_stack.pop() snake_case : List[Any] = operand_stack.peek() operand_stack.pop() snake_case : Optional[Any] = operators[opr](SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) operand_stack.push(SCREAMING_SNAKE_CASE_ ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": __snake_case = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
203
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 UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") UpperCamelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") UpperCamelCase__ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : int = CamembertTokenizer _a : Dict = CamembertTokenizerFast _a : Tuple = True _a : List[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = 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 ) , 1_0_0_4 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_5 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) __lowerCAmelCase = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = 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) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" if not self.test_rust_tokenizer: return __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.tokenize(_A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[5, 5_4, 7_1_9_6, 2_9_7, 3_0, 2_3, 7_7_6, 1_8, 1_1, 3_2_1_5, 3_7_0_5, 8_2_5_2, 2_2, 3_1_6_4, 1_1_8_1, 2_1_1_6, 2_9, 1_6, 8_1_3, 2_5, 7_9_1, 3_3_1_4, 2_0, 3_4_4_6, 3_8, 2_7_5_7_5, 1_2_0, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_6_8, 1_7, 1_1, 9_0_8_8, 2_0, 1_5_1_7, 8, 2_2_8_0_4, 1_8_8_1_8, 1_0, 3_8, 6_2_9, 6_0_7, 6_0_7, 1_4_2, 1_9, 7_1_9_6, 8_6_7, 5_6, 1_0_3_2_6, 2_4, 2_2_6_7, 2_0, 4_1_6, 5_0_7_2, 1_5_6_1_2, 2_3_3, 7_3_4, 7, 2_3_9_9, 2_7, 1_6, 3_0_1_5, 1_6_4_9, 7, 2_4, 2_0, 4_3_3_8, 2_3_9_9, 2_7, 1_3, 3_4_0_0, 1_4, 1_3, 6_1_8_9, 8, 9_3_0, 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. __lowerCAmelCase = [ "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 , )
92
0
'''simple docstring''' from __future__ import annotations a : Any = 1.60_21E-19 # units = C def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, ) -> Optional[int]: '''simple docstring''' if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif conductivity < 0: raise ValueError('''Conductivity cannot be negative''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative''' ) elif mobility < 0: raise ValueError('''mobility cannot be negative''' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
56
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any] ): if isinstance(SCREAMING_SNAKE_CASE_ , collections.abc.Iterable ): return x return (x, x) @require_tf class a__ : def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase = VisionTextDualEncoderConfig.from_vision_text_configs(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = {"vision_model": vision_model, "text_model": text_model} __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model(input_ids=_A , pixel_values=_A , attention_mask=_A ) __lowerCAmelCase = after_output[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A , _A ): """simple docstring""" __lowerCAmelCase = np.abs((a - b) ).max() self.assertLessEqual(_A , _A , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_save_load(**_A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_A ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_pretrained_model_and_inputs() __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_A ) __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained(_A ) __lowerCAmelCase = model_a(**_A ) __lowerCAmelCase = after_outputs[0].numpy() __lowerCAmelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_A , 1E-5 ) @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFViTModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFViTModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A , _A , _A , _A=None , **_A ): """simple docstring""" __lowerCAmelCase , __lowerCAmelCase = self.get_vision_text_model(_A , _A ) __lowerCAmelCase = TFVisionTextDualEncoderModel(vision_model=_A , text_model=_A ) __lowerCAmelCase = model( input_ids=_A , pixel_values=_A , attention_mask=_A , output_attentions=_A ) __lowerCAmelCase = output.vision_model_output.attentions self.assertEqual(len(_A ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __lowerCAmelCase = to_atuple(vision_model.config.image_size ) __lowerCAmelCase = to_atuple(vision_model.config.patch_size ) __lowerCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowerCAmelCase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowerCAmelCase = output.text_model_output.attentions self.assertEqual(len(_A ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFDeiTModel(_A , name="vision_model" ) __lowerCAmelCase = TFRobertaModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFDeiTModelTester(self ) __lowerCAmelCase = TFRobertaModelTester(self ) __lowerCAmelCase = vit_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class a__ ( snake_case__ , unittest.TestCase ): def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) __lowerCAmelCase = 1_3 __lowerCAmelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) __lowerCAmelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) __lowerCAmelCase = random_attention_mask([batch_size, 4] ) __lowerCAmelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __SCREAMING_SNAKE_CASE( self , _A , _A ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModel(_A , name="vision_model" ) __lowerCAmelCase = TFBertModel(_A , name="text_model" ) return vision_model, text_model def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFCLIPVisionModelTester(self ) __lowerCAmelCase = TFBertModelTester(self ) __lowerCAmelCase = clip_model_tester.prepare_config_and_inputs() __lowerCAmelCase = bert_model_tester.prepare_config_and_inputs() __lowerCAmelCase , __lowerCAmelCase = vision_config_and_inputs ( ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ( __lowerCAmelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class a__ ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=_A ) __lowerCAmelCase = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) __lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __lowerCAmelCase = processor( text=["una foto di un gatto", "una foto di un cane"] , images=_A , padding=_A , return_tensors="np" ) __lowerCAmelCase = model(**_A ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __lowerCAmelCase = np.array([[1.2_28_47_27, 0.3_10_41_22]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , _A , atol=1E-3 ) )
92
0
'''simple docstring''' import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer a_ : str = """bart""" a_ : List[Any] = True @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE_ ) def a_ ( ) -> List[Any]: """simple docstring""" if LOAD_DENSE_INDEX: lowerCamelCase_ =AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) lowerCamelCase_ =AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) lowerCamelCase_ =qar_model.eval() else: lowerCamelCase_, lowerCamelCase_ =(None, None) if MODEL_TYPE == "bart": lowerCamelCase_ =AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) lowerCamelCase_ =AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) lowerCamelCase_ =torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) lowerCamelCase_ =sas_model.eval() else: lowerCamelCase_, lowerCamelCase_ =make_qa_sas_model( model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE_ ) def a_ ( ) -> Optional[Any]: """simple docstring""" if LOAD_DENSE_INDEX: lowerCamelCase_ =faiss.StandardGpuResources() lowerCamelCase_ =datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] lowerCamelCase_ =np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) lowerCamelCase_ =faiss.IndexFlatIP(128 ) lowerCamelCase_ =faiss.index_cpu_to_gpu(SCREAMING_SNAKE_CASE_ , 1 , SCREAMING_SNAKE_CASE_ ) wikiaab_gpu_index_flat.add(SCREAMING_SNAKE_CASE_ ) # TODO fix for larger GPU else: lowerCamelCase_, lowerCamelCase_ =(None, None) lowerCamelCase_ =Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE_ ) def a_ ( ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ =datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) lowerCamelCase_ =elia['''train_eli5'''] lowerCamelCase_ =np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) lowerCamelCase_ =faiss.IndexFlatIP(128 ) eli5_train_q_index.add(SCREAMING_SNAKE_CASE_ ) return (elia_train, eli5_train_q_index) a_ , a_ , a_ : List[str] = load_indexes() a_ , a_ , a_ , a_ : int = load_models() a_ , a_ : Union[str, Any] = load_train_data() def a_ ( __snake_case : int , __snake_case : Optional[int]=10 ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ =embed_questions_for_retrieval([question] , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_, lowerCamelCase_ =eli5_train_q_index.search(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ =[elia_train[int(SCREAMING_SNAKE_CASE_ )] for i in I[0]] return nn_examples def a_ ( __snake_case : List[str] , __snake_case : int="wiki40b" , __snake_case : List[Any]="dense" , __snake_case : int=10 ) -> str: """simple docstring""" if source == "none": lowerCamelCase_, lowerCamelCase_ =(''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": lowerCamelCase_, lowerCamelCase_ =query_qa_dense_index( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: lowerCamelCase_, lowerCamelCase_ =query_es_index( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , index_name='''english_wiki40b_snippets_100w''' , n_results=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase_ =[ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] lowerCamelCase_ ='''question: {} context: {}'''.format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda __snake_case : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda __snake_case : None), } ) def a_ ( __snake_case : Any , __snake_case : Optional[Any] , __snake_case : Optional[int] , __snake_case : Any=64 , __snake_case : Dict=256 , __snake_case : List[str]=False , __snake_case : List[str]=2 , __snake_case : List[str]=0.9_5 , __snake_case : Union[str, Any]=0.8 ) -> Optional[int]: """simple docstring""" with torch.no_grad(): lowerCamelCase_ =qa_sas_generate( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , num_answers=1 , num_beams=SCREAMING_SNAKE_CASE_ , min_len=SCREAMING_SNAKE_CASE_ , max_len=SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ , temp=SCREAMING_SNAKE_CASE_ , top_p=SCREAMING_SNAKE_CASE_ , top_k=SCREAMING_SNAKE_CASE_ , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title("""Long Form Question Answering with ELI5""") # Start sidebar a_ : List[Any] = """<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>""" a_ : Union[str, Any] = """ <html> <head> <style> .img-container { padding-left: 90px; padding-right: 90px; padding-top: 50px; padding-bottom: 50px; background-color: #f0f3f9; } </style> </head> <body> <span class=\"img-container\"> <!-- Inline parent element --> %s </span> </body> </html> """ % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia a_ : str = """ This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html). First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset, a pre-processed fixed snapshot of Wikipedia. """ st.sidebar.markdown(description, unsafe_allow_html=True) a_ : str = [ """Answer the question""", """View the retrieved document only""", """View the most similar ELI5 question and answer""", """Show me everything, please!""", ] a_ : List[Any] = st.sidebar.checkbox("""Demo options""") if demo_options: a_ : List[Any] = st.sidebar.selectbox( """""", action_list, index=3, ) a_ : Dict = action_list.index(action_st) a_ : Dict = st.sidebar.selectbox( """""", ["""Show full text of passages""", """Show passage section titles"""], index=0, ) a_ : Optional[int] = show_type == """Show full text of passages""" else: a_ : List[Any] = 3 a_ : List[str] = True a_ : List[Any] = st.sidebar.checkbox("""Retrieval options""") if retrieval_options: a_ : List[str] = """ ### Information retriever options The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs. The answer is then generated by sequence to sequence model which takes the question and retrieved document as input. """ st.sidebar.markdown(retriever_info) a_ : Any = st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""]) a_ : Dict = st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""]) else: a_ : Optional[Any] = """wiki40b""" a_ : Optional[Any] = """dense""" a_ : str = """beam""" a_ : Optional[Any] = 2 a_ : str = 64 a_ : Union[str, Any] = 2_56 a_ : str = None a_ : Any = None a_ : Optional[Any] = st.sidebar.checkbox("""Generation options""") if generate_options: a_ : Tuple = """ ### Answer generation options The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large) weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with **beam** search, or **sample** from the decoder's output probabilities. """ st.sidebar.markdown(generate_info) a_ : Union[str, Any] = st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""]) a_ : Optional[int] = st.sidebar.slider( """Minimum generation length""", min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) a_ : Optional[int] = st.sidebar.slider( """Maximum generation length""", min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": a_ : int = st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: a_ : Tuple = st.sidebar.slider( """Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) a_ : str = st.sidebar.slider( """Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) a_ : Optional[int] = None # start main text a_ : List[Any] = [ """<MY QUESTION>""", """How do people make chocolate?""", """Why do we get a fever when we are sick?""", """How can different animals perceive different colors?""", """What is natural language processing?""", """What's the best way to treat a sunburn?""", """What exactly are vitamins ?""", """How does nuclear energy provide electricity?""", """What's the difference between viruses and bacteria?""", """Why are flutes classified as woodwinds when most of them are made out of metal ?""", """Why do people like drinking coffee even though it tastes so bad?""", """What happens when wine ages? How does it make the wine taste better?""", """If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?""", """How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?""", """How does New Zealand have so many large bird predators?""", ] a_ : str = st.selectbox( """What would you like to ask? ---- select <MY QUESTION> to enter a new query""", questions_list, index=1, ) if question_s == "<MY QUESTION>": a_ : Tuple = st.text_input("""Enter your question here:""", """""") else: a_ : Optional[Any] = question_s if st.button("""Show me!"""): if action in [0, 1, 3]: if index_type == "mixed": a_ , a_ : Any = make_support(question, source=wiki_source, method="""dense""", n_results=10) a_ , a_ : Dict = make_support(question, source=wiki_source, method="""sparse""", n_results=10) a_ : Dict = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] a_ : int = support_list[:10] a_ : Optional[int] = """<P> """ + """ <P> """.join([res[-1] for res in support_list]) else: a_ , a_ : Dict = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: a_ , a_ : int = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == """sampled"""), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("""### The model generated answer is:""") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""") for i, res in enumerate(support_list): a_ : Dict = """https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_""")) a_ : Tuple = res[1].strip() if sec_titles == "": a_ : Any = """[{}]({})""".format(res[0], wiki_url) else: a_ : int = sec_titles.split(""" & """) a_ : List[str] = """ & """.join( ["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list] ) st.markdown( """{0:02d} - **Article**: {1:<18} <br> _Section_: {2}""".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( """> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True ) if action in [2, 3]: a_ : List[Any] = find_nearest_training(question) a_ : Union[str, Any] = nn_train_list[0] st.markdown( """--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""]) ) a_ : Union[str, Any] = [ """{}. {}""".format(i + 1, """ \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""])) for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""])) if i == 0 or sc > 2 ] st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st))) a_ : str = """ --- **Disclaimer** *The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system. Evaluating biases of such a model and ensuring factual generations are still very much open research problems. Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.* """ st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
75
import json import os import torch from diffusers import UNetaDModel os.makedirs("""hub/hopper-medium-v2/unet/hor32""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/unet/hor128""", exist_ok=True) os.makedirs("""hub/hopper-medium-v2/value_function""", exist_ok=True) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): if hor == 1_28: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D") elif hor == 32: __lowerCAmelCase = ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D") __lowerCAmelCase = (32, 64, 1_28, 2_56) __lowerCAmelCase = ("UpResnetBlock1D", "UpResnetBlock1D", "UpResnetBlock1D") __lowerCAmelCase = torch.load(F"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) __lowerCAmelCase = model.state_dict() __lowerCAmelCase = { "down_block_types": down_block_types, "block_out_channels": block_out_channels, "up_block_types": up_block_types, "layers_per_block": 1, "use_timestep_embedding": True, "out_block_type": "OutConv1DBlock", "norm_num_groups": 8, "downsample_each_block": False, "in_channels": 14, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "flip_sin_to_cos": False, "freq_shift": 1, "sample_size": 6_55_36, "mid_block_type": "MidResTemporalBlock1D", "act_fn": "mish", } __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , F"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(F"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( ): __lowerCAmelCase = { "in_channels": 14, "down_block_types": ("DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D", "DownResnetBlock1D"), "up_block_types": (), "out_block_type": "ValueFunction", "mid_block_type": "ValueFunctionMidBlock1D", "block_out_channels": (32, 64, 1_28, 2_56), "layers_per_block": 1, "downsample_each_block": True, "sample_size": 6_55_36, "out_channels": 14, "extra_in_channels": 0, "time_embedding_type": "positional", "use_timestep_embedding": True, "flip_sin_to_cos": False, "freq_shift": 1, "norm_num_groups": 8, "act_fn": "mish", } __lowerCAmelCase = torch.load("/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch" ) __lowerCAmelCase = model __lowerCAmelCase = UNetaDModel(**SCREAMING_SNAKE_CASE_ ) print(F"""length of state dict: {len(state_dict.keys() )}""" ) print(F"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) __lowerCAmelCase = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): __lowerCAmelCase = state_dict.pop(SCREAMING_SNAKE_CASE_ ) hf_value_function.load_state_dict(SCREAMING_SNAKE_CASE_ ) torch.save(hf_value_function.state_dict() , "hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin" ) with open("hub/hopper-medium-v2/value_function/config.json" , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
92
0
"""simple docstring""" from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def _SCREAMING_SNAKE_CASE ( __snake_case : str , __snake_case : complex , __snake_case : str = "x" , __snake_case : float = 10**-10 , __snake_case : int = 1 , ): '''simple docstring''' lowercase = symbols(SCREAMING_SNAKE_CASE_ ) lowercase = lambdify(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase = lambdify(SCREAMING_SNAKE_CASE_ , diff(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) lowercase = starting_point while True: if diff_function(SCREAMING_SNAKE_CASE_ ) != 0: lowercase = prev_guess - multiplicity * func(SCREAMING_SNAKE_CASE_ ) / diff_function( SCREAMING_SNAKE_CASE_ ) else: raise ZeroDivisionError('Could not find root' ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess lowercase = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F'''The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}''') # Find root of polynomial # Find fourth Root of 5 print(F'''The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5J)}''') # Find value of e print( 'The root of log(y) - 1 = 0 is ', F'''{newton_raphson('log(y) - 1', 2, variable='y')}''', ) # Exponential Roots print( 'The root of exp(x) - 1 = 0 is', F'''{newton_raphson('exp(x) - 1', 1_0, precision=0.0_0_5)}''', ) # Find root of cos(x) print(F'''The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}''')
220
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): monkeypatch.setattr("datasets.utils.deprecation_utils._emitted_deprecation_warnings" , set() ) @pytest.fixture def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): class a__ : def __init__( self , _A ): """simple docstring""" __lowerCAmelCase = metric_id class a__ : _a : Optional[int] = [MetricMock(snake_case__ ) for metric_id in ["""accuracy""", """mse""", """precision""", """codeparrot/apps_metric"""]] def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" return self._metrics monkeypatch.setattr("datasets.inspect.huggingface_hub" , HfhMock() ) @pytest.mark.parametrize( "func, args" , [(load_metric, ("metrics/mse",)), (list_metrics, ()), (inspect_metric, ("metrics/mse", "tmp_path"))] ) def _a ( SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[int] ): if "tmp_path" in args: __lowerCAmelCase = tuple(arg if arg != "tmp_path" else tmp_path for arg in args ) with pytest.warns(SCREAMING_SNAKE_CASE_ , match="https://huggingface.co/docs/evaluate" ): func(*SCREAMING_SNAKE_CASE_ )
92
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A : List[Any] = { 'configuration_poolformer': [ 'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PoolFormerConfig', 'PoolFormerOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = ['PoolFormerFeatureExtractor'] A : List[str] = ['PoolFormerImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : int = [ 'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PoolFormerForImageClassification', 'PoolFormerModel', 'PoolFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys A : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure)
6
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = 0 if start < end: __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase , __lowerCAmelCase = _in_place_partition(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE_ , p + 1 , SCREAMING_SNAKE_CASE_ ) return count def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[int] ): __lowerCAmelCase = 0 __lowerCAmelCase = randint(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = a[end] __lowerCAmelCase = a[pivot] __lowerCAmelCase = temp __lowerCAmelCase = start - 1 for index in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCAmelCase = new_pivot_index + 1 __lowerCAmelCase = a[new_pivot_index] __lowerCAmelCase = a[index] __lowerCAmelCase = temp __lowerCAmelCase = a[new_pivot_index + 1] __lowerCAmelCase = a[end] __lowerCAmelCase = temp return new_pivot_index + 1, count UpperCamelCase__ = TemporaryFile() UpperCamelCase__ = 100 # 1000 elements are to be sorted UpperCamelCase__ , UpperCamelCase__ = 0, 1 # mean and standard deviation UpperCamelCase__ = np.random.normal(mu, sigma, p) np.save(outfile, X) print("""The array is""") print(X) outfile.seek(0) # using the same array UpperCamelCase__ = np.load(outfile) UpperCamelCase__ = len(M) - 1 UpperCamelCase__ = _in_place_quick_sort(M, 0, r) print( """No of Comparisons for 100 elements selected from a standard normal distribution""" """is :""" ) print(z)
92
0