code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse import math import traceback import dateutil.parser as date_parser import requests def lowercase_ ( _UpperCAmelCase ): """simple docstring""" A_ : str = {} A_ : Tuple = job['''started_at'''] A_ : Dict = job['''completed_at'''] A_ : List[str] = date_parser.parse(_UpperCAmelCase ) A_ : List[str] = date_parser.parse(_UpperCAmelCase ) A_ : List[Any] = round((end_datetime - start_datetime).total_seconds() / 60.0 ) A_ : Optional[int] = start A_ : Dict = end A_ : Any = duration_in_min return job_info def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase=None ): """simple docstring""" A_ : List[Any] = None if token is not None: A_ : Dict = {'''Accept''': '''application/vnd.github+json''', '''Authorization''': f"""Bearer {token}"""} A_ : str = f"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" A_ : Any = requests.get(_UpperCAmelCase , headers=_UpperCAmelCase ).json() A_ : Optional[int] = {} try: job_time.update({job['''name''']: extract_time_from_single_job(_UpperCAmelCase ) for job in result['''jobs''']} ) A_ : List[str] = math.ceil((result['''total_count'''] - 100) / 100 ) for i in range(_UpperCAmelCase ): A_ : List[Any] = requests.get(url + f"""&page={i + 2}""" , headers=_UpperCAmelCase ).json() job_time.update({job['''name''']: extract_time_from_single_job(_UpperCAmelCase ) for job in result['''jobs''']} ) return job_time except Exception: print(f"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} if __name__ == "__main__": _lowerCamelCase : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') _lowerCamelCase : List[Any] = parser.parse_args() _lowerCamelCase : Optional[int] = get_job_time(args.workflow_run_id) _lowerCamelCase : str = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'{k}: {v["duration"]}')
167
"""simple docstring""" from __future__ import annotations from typing import Generic, TypeVar _lowerCamelCase : Any = TypeVar('T') class lowercase ( Generic[T]): def __init__( self : Tuple , _lowerCamelCase : T ): """simple docstring""" A_ : Union[str, Any] = data A_ : List[Any] = self A_ : Optional[Any] = 0 class lowercase ( Generic[T]): def __init__( self : int ): """simple docstring""" A_ : dict[T, DisjointSetTreeNode[T]] = {} def a_ ( self : List[str] , _lowerCamelCase : T ): """simple docstring""" A_ : List[str] = DisjointSetTreeNode(_lowerCamelCase ) def a_ ( self : Dict , _lowerCamelCase : T ): """simple docstring""" A_ : Any = self.map[data] if elem_ref != elem_ref.parent: A_ : Any = self.find_set(elem_ref.parent.data ) return elem_ref.parent def a_ ( self : Union[str, Any] , _lowerCamelCase : DisjointSetTreeNode[T] , _lowerCamelCase : DisjointSetTreeNode[T] ): """simple docstring""" if nodea.rank > nodea.rank: A_ : List[str] = nodea else: A_ : Optional[Any] = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def a_ ( self : Optional[Any] , _lowerCamelCase : T , _lowerCamelCase : T ): """simple docstring""" self.link(self.find_set(_lowerCamelCase ) , self.find_set(_lowerCamelCase ) ) class lowercase ( Generic[T]): def __init__( self : Tuple ): """simple docstring""" A_ : dict[T, dict[T, int]] = {} def a_ ( self : List[Any] , _lowerCamelCase : T ): """simple docstring""" if node not in self.connections: A_ : Tuple = {} def a_ ( self : Optional[Any] , _lowerCamelCase : T , _lowerCamelCase : T , _lowerCamelCase : int ): """simple docstring""" self.add_node(_lowerCamelCase ) self.add_node(_lowerCamelCase ) A_ : int = weight A_ : Dict = weight def a_ ( self : Any ): """simple docstring""" A_ : Tuple = [] A_ : Tuple = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda _lowerCamelCase : x[2] ) # creating the disjoint set A_ : Optional[Any] = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(_lowerCamelCase ) # MST generation A_ : Any = 0 A_ : Optional[int] = 0 A_ : Union[str, Any] = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: A_ , A_ , A_ : int = edges[index] index += 1 A_ : Tuple = disjoint_set.find_set(_lowerCamelCase ) A_ : int = disjoint_set.find_set(_lowerCamelCase ) if parent_u != parent_v: num_edges += 1 graph.add_edge(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) disjoint_set.union(_lowerCamelCase , _lowerCamelCase ) return graph
167
1
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class SCREAMING_SNAKE_CASE : def __init__( self : Union[str, Any] , a : List[Any] , a : Dict=2 , a : List[Any]=32 , a : int=16 , a : Optional[Any]=3 , a : Optional[int]=True , a : List[Any]=True , a : Union[str, Any]=32 , a : List[Any]=4 , a : List[Any]=[0, 1, 2, 3] , a : Union[str, Any]=4 , a : Tuple=37 , a : Dict="gelu" , a : Dict=0.1 , a : int=0.1 , a : Dict=0.02 , a : Tuple=3 , a : List[str]=[1, 384, 24, 24] , a : int=True , a : List[str]=None , )-> Optional[int]: """simple docstring""" lowercase__ = parent lowercase__ = batch_size lowercase__ = image_size lowercase__ = patch_size lowercase__ = num_channels lowercase__ = is_training lowercase__ = use_labels lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = backbone_out_indices lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = num_labels lowercase__ = backbone_featmap_shape lowercase__ = scope lowercase__ = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) lowercase__ = (image_size // patch_size) ** 2 lowercase__ = num_patches + 1 def SCREAMING_SNAKE_CASE_ ( self : Dict )-> Any: """simple docstring""" lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowercase__ = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self : str )-> List[Any]: """simple docstring""" lowercase__ = { 'global_padding': 'same', 'layer_type': 'bottleneck', 'depths': [3, 4, 9], 'out_features': ['stage1', 'stage2', 'stage3'], 'embedding_dynamic_padding': True, 'hidden_sizes': [96, 192, 384, 768], 'num_groups': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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 , is_hybrid=self.is_hybrid , backbone_config=a , backbone_featmap_shape=self.backbone_featmap_shape , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , a : str , a : List[Any] , a : List[Any] )-> Optional[Any]: """simple docstring""" lowercase__ = DPTModel(config=a ) model.to(a ) model.eval() lowercase__ = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , a : Union[str, Any] , a : List[Any] , a : int )-> Union[str, Any]: """simple docstring""" lowercase__ = self.num_labels lowercase__ = DPTForDepthEstimation(a ) model.to(a ) model.eval() lowercase__ = model(a ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def SCREAMING_SNAKE_CASE_ ( self : Dict , a : Union[str, Any] , a : str , a : int )-> Dict: """simple docstring""" lowercase__ = self.num_labels lowercase__ = DPTForSemanticSegmentation(a ) model.to(a ) model.eval() lowercase__ = model(a , labels=a ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> str: """simple docstring""" lowercase__ = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ = config_and_inputs lowercase__ = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE (UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _UpperCamelCase : str = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () _UpperCamelCase : List[str] = ( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) _UpperCamelCase : str = False _UpperCamelCase : List[Any] = False _UpperCamelCase : List[str] = False def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" lowercase__ = DPTModelTester(self ) lowercase__ = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> List[str]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DPT does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE_ ( self : Dict )-> Optional[Any]: """simple docstring""" pass def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> List[Any]: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Any: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(a ) lowercase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ = [*signature.parameters.keys()] lowercase__ = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] )-> List[str]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> Optional[int]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*a ) def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> List[Any]: """simple docstring""" lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> List[Any]: """simple docstring""" for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = True if model_class in get_values(a ): continue lowercase__ = model_class(a ) model.to(a ) model.train() lowercase__ = self._prepare_for_class(a , a , return_labels=a ) lowercase__ = model(**a ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self : Any )-> str: """simple docstring""" for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = False lowercase__ = True if model_class in get_values(a ) or not model_class.supports_gradient_checkpointing: continue lowercase__ = model_class(a ) model.to(a ) model.gradient_checkpointing_enable() model.train() lowercase__ = self._prepare_for_class(a , a , return_labels=a ) lowercase__ = model(**a ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self : Dict )-> int: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = _config_zero_init(a ) for model_class in self.all_model_classes: lowercase__ = model_class(config=a ) # Skip the check for the backbone lowercase__ = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": lowercase__ = [f"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def SCREAMING_SNAKE_CASE_ ( self : str )-> Any: """simple docstring""" pass @slow def SCREAMING_SNAKE_CASE_ ( self : str )-> Tuple: """simple docstring""" for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: lowercase__ = DPTModel.from_pretrained(a ) self.assertIsNotNone(a ) def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> Any: """simple docstring""" lowercase__ , lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = 'add' with self.assertRaises(a ): lowercase__ = DPTForDepthEstimation(a ) def __UpperCamelCase () -> List[Any]: lowercase__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision @slow class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Optional[int] )-> str: """simple docstring""" lowercase__ = DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas' ) lowercase__ = DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas' ).to(a ) lowercase__ = prepare_img() lowercase__ = image_processor(images=a , return_tensors='pt' ).to(a ) # forward pass with torch.no_grad(): lowercase__ = model(**a ) lowercase__ = outputs.predicted_depth # verify the predicted depth lowercase__ = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , a ) lowercase__ = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(a ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , a , atol=1E-4 ) )
355
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class SCREAMING_SNAKE_CASE (UpperCAmelCase , UpperCAmelCase ): @register_to_config def __init__( self : str , a : int = 128 , a : int = 256 , a : float = 2000.0 , a : int = 768 , a : int = 12 , a : int = 12 , a : int = 64 , a : int = 2_048 , a : float = 0.1 , )-> Any: """simple docstring""" super().__init__() lowercase__ = nn.Sequential( nn.Linear(a , d_model * 4 , bias=a ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=a ) , nn.SiLU() , ) lowercase__ = nn.Embedding(a , a ) lowercase__ = False lowercase__ = nn.Linear(a , a , bias=a ) lowercase__ = nn.Dropout(p=a ) lowercase__ = nn.ModuleList() for lyr_num in range(a ): # FiLM conditional T5 decoder lowercase__ = DecoderLayer(d_model=a , d_kv=a , num_heads=a , d_ff=a , dropout_rate=a ) self.decoders.append(a ) lowercase__ = TaLayerNorm(a ) lowercase__ = nn.Dropout(p=a ) lowercase__ = nn.Linear(a , a , bias=a ) def SCREAMING_SNAKE_CASE_ ( self : str , a : int , a : List[Any] )-> str: """simple docstring""" lowercase__ = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , a : Dict , a : int , a : int )-> int: """simple docstring""" lowercase__ , lowercase__ , lowercase__ = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. lowercase__ = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) lowercase__ = self.conditioning_emb(a ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) lowercase__ = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. lowercase__ = torch.broadcast_to( torch.arange(a , device=decoder_input_tokens.device ) , (batch, seq_length) , ) lowercase__ = self.position_encoding(a ) lowercase__ = self.continuous_inputs_projection(a ) inputs += position_encodings lowercase__ = self.dropout(a ) # decoder: No padding present. lowercase__ = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. lowercase__ = [(x, self.encoder_decoder_mask(a , a )) for x, y in encodings_and_masks] # cross attend style: concat encodings lowercase__ = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) lowercase__ = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: lowercase__ = lyr( a , conditioning_emb=a , encoder_hidden_states=a , encoder_attention_mask=a , )[0] lowercase__ = self.decoder_norm(a ) lowercase__ = self.post_dropout(a ) lowercase__ = self.spec_out(a ) return spec_out class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : Dict , a : List[Any] , a : str , a : Union[str, Any] , a : Optional[int] , a : Optional[int] , a : Tuple=1E-6 )-> Union[str, Any]: """simple docstring""" super().__init__() lowercase__ = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=a , d_kv=a , num_heads=a , dropout_rate=a ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=a , d_kv=a , num_heads=a , dropout_rate=a , layer_norm_epsilon=a , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=a , d_ff=a , dropout_rate=a , layer_norm_epsilon=a ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , a : str , a : Union[str, Any]=None , a : Dict=None , a : Union[str, Any]=None , a : List[Any]=None , a : List[str]=None , )-> List[Any]: """simple docstring""" lowercase__ = self.layer[0]( a , conditioning_emb=a , attention_mask=a , ) if encoder_hidden_states is not None: lowercase__ = torch.where(encoder_attention_mask > 0 , 0 , -1E1_0 ).to( encoder_hidden_states.dtype ) lowercase__ = self.layer[1]( a , key_value_states=a , attention_mask=a , ) # Apply Film Conditional Feed Forward layer lowercase__ = self.layer[-1](a , a ) return (hidden_states,) class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : List[str] , a : List[Any] , a : Tuple , a : Union[str, Any] , a : int )-> List[str]: """simple docstring""" super().__init__() lowercase__ = TaLayerNorm(a ) lowercase__ = TaFiLMLayer(in_features=d_model * 4 , out_features=a ) lowercase__ = Attention(query_dim=a , heads=a , dim_head=a , out_bias=a , scale_qk=a ) lowercase__ = nn.Dropout(a ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , a : List[Any] , a : Union[str, Any]=None , a : Tuple=None , )-> int: """simple docstring""" lowercase__ = self.layer_norm(a ) if conditioning_emb is not None: lowercase__ = self.FiLMLayer(a , a ) # Self-attention block lowercase__ = self.attention(a ) lowercase__ = hidden_states + self.dropout(a ) return hidden_states class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : Optional[int] , a : Optional[int] , a : int , a : Optional[int] , a : Dict , a : Any )-> Optional[int]: """simple docstring""" super().__init__() lowercase__ = Attention(query_dim=a , heads=a , dim_head=a , out_bias=a , scale_qk=a ) lowercase__ = TaLayerNorm(a , eps=a ) lowercase__ = nn.Dropout(a ) def SCREAMING_SNAKE_CASE_ ( self : int , a : List[Any] , a : str=None , a : Dict=None , )-> int: """simple docstring""" lowercase__ = self.layer_norm(a ) lowercase__ = self.attention( a , encoder_hidden_states=a , attention_mask=attention_mask.squeeze(1 ) , ) lowercase__ = hidden_states + self.dropout(a ) return layer_output class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : Dict , a : str , a : int , a : List[Any] , a : List[str] )-> Dict: """simple docstring""" super().__init__() lowercase__ = TaDenseGatedActDense(d_model=a , d_ff=a , dropout_rate=a ) lowercase__ = TaFiLMLayer(in_features=d_model * 4 , out_features=a ) lowercase__ = TaLayerNorm(a , eps=a ) lowercase__ = nn.Dropout(a ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , a : List[Any] , a : List[Any]=None )-> List[Any]: """simple docstring""" lowercase__ = self.layer_norm(a ) if conditioning_emb is not None: lowercase__ = self.film(a , a ) lowercase__ = self.DenseReluDense(a ) lowercase__ = hidden_states + self.dropout(a ) return hidden_states class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : Optional[Any] , a : Tuple , a : Tuple , a : Dict )-> Union[str, Any]: """simple docstring""" super().__init__() lowercase__ = nn.Linear(a , a , bias=a ) lowercase__ = nn.Linear(a , a , bias=a ) lowercase__ = nn.Linear(a , a , bias=a ) lowercase__ = nn.Dropout(a ) lowercase__ = NewGELUActivation() def SCREAMING_SNAKE_CASE_ ( self : Any , a : str )-> str: """simple docstring""" lowercase__ = self.act(self.wi_a(a ) ) lowercase__ = self.wi_a(a ) lowercase__ = hidden_gelu * hidden_linear lowercase__ = self.dropout(a ) lowercase__ = self.wo(a ) return hidden_states class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : Dict , a : Dict , a : Dict=1E-6 )-> Optional[int]: """simple docstring""" super().__init__() lowercase__ = nn.Parameter(torch.ones(a ) ) lowercase__ = eps def SCREAMING_SNAKE_CASE_ ( self : Any , a : Optional[Any] )-> List[str]: """simple docstring""" lowercase__ = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=a ) lowercase__ = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: lowercase__ = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class SCREAMING_SNAKE_CASE (nn.Module ): def SCREAMING_SNAKE_CASE_ ( self : Tuple , a : torch.Tensor )-> torch.Tensor: """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044715 * torch.pow(a , 3.0 )) )) class SCREAMING_SNAKE_CASE (nn.Module ): def __init__( self : int , a : Optional[Any] , a : Any )-> Optional[Any]: """simple docstring""" super().__init__() lowercase__ = nn.Linear(a , out_features * 2 , bias=a ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , a : Tuple , a : Dict )-> Optional[int]: """simple docstring""" lowercase__ = self.scale_bias(a ) lowercase__ , lowercase__ = torch.chunk(a , 2 , -1 ) lowercase__ = x * (1 + scale) + shift return x
269
0
def UpperCAmelCase__ ( _A : int ): '''simple docstring''' if not isinstance(_A , _A ): a__ =F"""Input value of [number={number}] must be an integer""" raise TypeError(_A ) if number < 1: a__ =F"""Input value of [number={number}] must be > 0""" raise ValueError(_A ) a__ =1 for i in range(1 , _A ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
188
import os import string import sys lowerCamelCase = 1 << 8 lowerCamelCase = { '''tab''': ord('''\t'''), '''newline''': ord('''\r'''), '''esc''': 27, '''up''': 65 + ARROW_KEY_FLAG, '''down''': 66 + ARROW_KEY_FLAG, '''right''': 67 + ARROW_KEY_FLAG, '''left''': 68 + ARROW_KEY_FLAG, '''mod_int''': 91, '''undefined''': sys.maxsize, '''interrupt''': 3, '''insert''': 50, '''delete''': 51, '''pg_up''': 53, '''pg_down''': 54, } lowerCamelCase = KEYMAP['''up'''] lowerCamelCase = KEYMAP['''left'''] if sys.platform == "win32": lowerCamelCase = [] lowerCamelCase = { b'''\xe0H''': KEYMAP['''up'''] - ARROW_KEY_FLAG, b'''\x00H''': KEYMAP['''up'''] - ARROW_KEY_FLAG, b'''\xe0P''': KEYMAP['''down'''] - ARROW_KEY_FLAG, b'''\x00P''': KEYMAP['''down'''] - ARROW_KEY_FLAG, b'''\xe0M''': KEYMAP['''right'''] - ARROW_KEY_FLAG, b'''\x00M''': KEYMAP['''right'''] - ARROW_KEY_FLAG, b'''\xe0K''': KEYMAP['''left'''] - ARROW_KEY_FLAG, b'''\x00K''': KEYMAP['''left'''] - ARROW_KEY_FLAG, } for i in range(10): lowerCamelCase = ord(str(i)) def UpperCAmelCase__ ( ): '''simple docstring''' if os.name == "nt": import msvcrt a__ ='''mbcs''' # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(_A ) == 0: # Read the keystroke a__ =msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): a__ =ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: a__ =chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP['''mod_int'''] ) ) WIN_CH_BUFFER.append(_A ) if ord(_A ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) a__ =chr(KEYMAP['''esc'''] ) except KeyError: a__ =cha[1] else: a__ =ch.decode(_A ) else: a__ =WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty a__ =sys.stdin.fileno() a__ =termios.tcgetattr(_A ) try: tty.setraw(_A ) a__ =sys.stdin.read(1 ) finally: termios.tcsetattr(_A , termios.TCSADRAIN , _A ) return ch def UpperCAmelCase__ ( ): '''simple docstring''' a__ =get_raw_chars() if ord(_A ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(_A ) == KEYMAP["esc"]: a__ =get_raw_chars() if ord(_A ) == KEYMAP["mod_int"]: a__ =get_raw_chars() if ord(_A ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(_A ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(_A ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
188
1
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss UpperCAmelCase_ = pytest.mark.integration @require_faiss class lowerCAmelCase_ ( lowerCamelCase__ ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" UpperCAmelCase__ = Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(__lowerCamelCase ) for x in np.arange(30 ).tolist()]} ) return dset def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" import faiss UpperCAmelCase__ = self._create_dummy_dataset() UpperCAmelCase__ = dset.map( lambda _UpperCAmelCase , _UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__lowerCamelCase , keep_in_memory=__lowerCamelCase ) UpperCAmelCase__ = dset.add_faiss_index("""vecs""" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT ) UpperCAmelCase__ = dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) dset.drop_index("""vecs""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" import faiss UpperCAmelCase__ = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" , batch_size=1_00 , metric_type=faiss.METRIC_INNER_PRODUCT , ) UpperCAmelCase__ = dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" import faiss UpperCAmelCase__ = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__lowerCamelCase ) as tmp_file: dset.save_faiss_index("""vecs""" , tmp_file.name ) dset.load_faiss_index("""vecs2""" , tmp_file.name ) os.unlink(tmp_file.name ) UpperCAmelCase__ = dset.get_nearest_examples("""vecs2""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" UpperCAmelCase__ = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" ) dset.drop_index("""vecs""" ) self.assertRaises(__lowerCamelCase , partial(dset.get_nearest_examples , """vecs2""" , np.ones(5 , dtype=np.floataa ) ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" from elasticsearch import Elasticsearch UpperCAmelCase__ = self._create_dummy_dataset() with patch("""elasticsearch.Elasticsearch.search""" ) as mocked_search, patch( """elasticsearch.client.IndicesClient.create""" ) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""" ) as mocked_bulk: UpperCAmelCase__ = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) UpperCAmelCase__ = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} UpperCAmelCase__ = Elasticsearch() dset.add_elasticsearch_index("""filename""" , es_client=__lowerCamelCase ) UpperCAmelCase__ = dset.get_nearest_examples("""filename""" , """my_name-train_29""" ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) @require_faiss class lowerCAmelCase_ ( lowerCamelCase__ ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" import faiss UpperCAmelCase__ = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query UpperCAmelCase__ = np.zeros(5 , dtype=np.floataa ) UpperCAmelCase__ = 1 UpperCAmelCase__ = index.search(__lowerCamelCase ) self.assertRaises(__lowerCamelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries UpperCAmelCase__ = np.eye(5 , dtype=np.floataa )[::-1] UpperCAmelCase__ = index.search_batch(__lowerCamelCase ) self.assertRaises(__lowerCamelCase , index.search_batch , queries[0] ) UpperCAmelCase__ = [scores[0] for scores in total_scores] UpperCAmelCase__ = [indices[0] for indices in total_indices] self.assertGreater(np.min(__lowerCamelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" import faiss UpperCAmelCase__ = FaissIndex(string_factory="""Flat""" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) UpperCAmelCase__ = FaissIndex(string_factory="""LSH""" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__lowerCamelCase ): UpperCAmelCase__ = FaissIndex(string_factory="""Flat""" , custom_index=faiss.IndexFlat(5 ) ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" import faiss UpperCAmelCase__ = faiss.IndexFlat(5 ) UpperCAmelCase__ = FaissIndex(custom_index=__lowerCamelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" import faiss UpperCAmelCase__ = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__lowerCamelCase ) as tmp_file: index.save(tmp_file.name ) UpperCAmelCase__ = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) UpperCAmelCase__ = np.zeros(5 , dtype=np.floataa ) UpperCAmelCase__ = 1 UpperCAmelCase__ = index.search(__lowerCamelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' import faiss UpperCAmelCase__ = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) UpperCAmelCase__ = '''index.faiss''' UpperCAmelCase__ = F'''mock://{index_name}''' index.save(lowerCamelCase_ , storage_options=mockfs.storage_options ) UpperCAmelCase__ = FaissIndex.load(lowerCamelCase_ , storage_options=mockfs.storage_options ) UpperCAmelCase__ = np.zeros(5 , dtype=np.floataa ) UpperCAmelCase__ = 1 UpperCAmelCase__ = index.search(lowerCamelCase_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowerCAmelCase_ ( lowerCamelCase__ ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" from elasticsearch import Elasticsearch with patch("""elasticsearch.Elasticsearch.search""" ) as mocked_search, patch( """elasticsearch.client.IndicesClient.create""" ) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""" ) as mocked_bulk: UpperCAmelCase__ = Elasticsearch() UpperCAmelCase__ = {'''acknowledged''': True} UpperCAmelCase__ = ElasticSearchIndex(es_client=__lowerCamelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["""foo""", """bar""", """foobar"""] ) # single query UpperCAmelCase__ = '''foo''' UpperCAmelCase__ = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} UpperCAmelCase__ = index.search(__lowerCamelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout UpperCAmelCase__ = '''foo''' UpperCAmelCase__ = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} UpperCAmelCase__ = index.search(__lowerCamelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries UpperCAmelCase__ = ['''foo''', '''bar''', '''foobar'''] UpperCAmelCase__ = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} UpperCAmelCase__ = index.search_batch(__lowerCamelCase ) UpperCAmelCase__ = [scores[0] for scores in total_scores] UpperCAmelCase__ = [indices[0] for indices in total_indices] self.assertGreater(np.min(__lowerCamelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __lowerCamelCase ) # batched queries with timeout UpperCAmelCase__ = ['''foo''', '''bar''', '''foobar'''] UpperCAmelCase__ = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} UpperCAmelCase__ = index.search_batch(__lowerCamelCase , request_timeout=30 ) UpperCAmelCase__ = [scores[0] for scores in total_scores] UpperCAmelCase__ = [indices[0] for indices in total_indices] self.assertGreater(np.min(__lowerCamelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __lowerCamelCase )
355
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' return int(input_a == input_a == 0 ) def _UpperCamelCase ( ): '''simple docstring''' print("""Truth Table of NOR Gate:""" ) print("""| Input 1 | Input 2 | Output |""" ) print(F'''| 0 | 0 | {nor_gate(0 , 0 )} |''' ) print(F'''| 0 | 1 | {nor_gate(0 , 1 )} |''' ) print(F'''| 1 | 0 | {nor_gate(1 , 0 )} |''' ) print(F'''| 1 | 1 | {nor_gate(1 , 1 )} |''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel UpperCamelCase = False UpperCamelCase = True UpperCamelCase = False if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--repo_path''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') UpperCamelCase = parser.parse_args() UpperCamelCase = { '''image_size''': '''sample_size''', '''num_res_blocks''': '''layers_per_block''', '''block_channels''': '''block_out_channels''', '''down_blocks''': '''down_block_types''', '''up_blocks''': '''up_block_types''', '''downscale_freq_shift''': '''freq_shift''', '''resnet_num_groups''': '''norm_num_groups''', '''resnet_act_fn''': '''act_fn''', '''resnet_eps''': '''norm_eps''', '''num_head_channels''': '''attention_head_dim''', } UpperCamelCase = { '''time_steps''': '''time_proj''', '''mid''': '''mid_block''', '''downsample_blocks''': '''down_blocks''', '''upsample_blocks''': '''up_blocks''', } UpperCamelCase = '''''' if has_file(args.repo_path, '''config.json''') else '''unet''' with open(os.path.join(args.repo_path, subfolder, '''config.json'''), '''r''', encoding='''utf-8''') as reader: UpperCamelCase = reader.read() UpperCamelCase = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, '''config.json'''): UpperCamelCase = UNetaDModel(**config) else: UpperCamelCase = UNetaDConditionModel if '''ldm-text2im-large-256''' in args.repo_path else UNetaDModel UpperCamelCase = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) UpperCamelCase = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: UpperCamelCase = config[key] del config[key] UpperCamelCase = [k.replace('''UNetRes''', '''''') for k in config['''down_block_types''']] UpperCamelCase = [k.replace('''UNetRes''', '''''') for k in config['''up_block_types''']] if do_only_weights: UpperCamelCase = torch.load(os.path.join(args.repo_path, subfolder, '''diffusion_pytorch_model.bin''')) UpperCamelCase = {} for param_key, param_value in state_dict.items(): if param_key.endswith('''.op.bias''') or param_key.endswith('''.op.weight'''): continue UpperCamelCase = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('''.''')[0] == key: UpperCamelCase = param_value UpperCamelCase = True if not has_changed: UpperCamelCase = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
319
'''simple docstring''' import fire from utils import calculate_rouge, save_json def SCREAMING_SNAKE_CASE( __lowercase , __lowercase , __lowercase=None , **__lowercase ) -> Any: A: Any = [x.strip() for x in open(__lowercase ).readlines()] A: Dict = [x.strip() for x in open(__lowercase ).readlines()][: len(__lowercase )] A: Union[str, Any] = calculate_rouge(__lowercase , __lowercase , **__lowercase ) if save_path is not None: save_json(__lowercase , __lowercase , indent=__lowercase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
319
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class a__ ( unittest.TestCase ): @slow def lowercase ( self : str ) -> Any: lowercase : str = TFAutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' ) lowercase : Union[str, Any] = AutoTokenizer.from_pretrained('google/mt5-small' ) lowercase : Any = tokenizer('Hello there', return_tensors='tf' ).input_ids lowercase : Dict = tokenizer('Hi I am', return_tensors='tf' ).input_ids lowercase : Dict = model(lowerCAmelCase, labels=lowerCAmelCase ).loss lowercase : Union[str, Any] = -tf.math.reduce_mean(lowerCAmelCase ).numpy() lowercase : Tuple = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
367
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class a__ : def __init__( self : Union[str, Any], lowerCAmelCase : Any, lowerCAmelCase : Tuple=13, lowerCAmelCase : List[Any]=2, lowerCAmelCase : Tuple=24, lowerCAmelCase : Any=16, lowerCAmelCase : Optional[Any]=True, lowerCAmelCase : Tuple=True, lowerCAmelCase : Optional[int]=32, lowerCAmelCase : Optional[int]=5, lowerCAmelCase : Optional[int]=4, lowerCAmelCase : Optional[int]=37, lowerCAmelCase : Tuple="gelu", lowerCAmelCase : str=0.1, lowerCAmelCase : Tuple=0.1, lowerCAmelCase : List[Any]=10, lowerCAmelCase : List[Any]=0.02, lowerCAmelCase : List[str]=None, lowerCAmelCase : Any=2, lowerCAmelCase : str=2, ) -> Union[str, Any]: lowercase : str = parent lowercase : Optional[int] = batch_size lowercase : str = patch_size lowercase : List[Any] = max_length lowercase : Optional[Any] = num_mel_bins lowercase : int = is_training lowercase : Dict = use_labels lowercase : List[str] = hidden_size lowercase : str = num_hidden_layers lowercase : Any = num_attention_heads lowercase : List[str] = intermediate_size lowercase : int = hidden_act lowercase : Optional[Any] = hidden_dropout_prob lowercase : Optional[Any] = attention_probs_dropout_prob lowercase : int = type_sequence_label_size lowercase : Optional[int] = initializer_range lowercase : int = scope lowercase : int = frequency_stride lowercase : Dict = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowercase : Tuple = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 lowercase : Dict = (self.max_length - self.patch_size) // self.time_stride + 1 lowercase : Any = frequency_out_dimension * time_out_dimension lowercase : List[str] = num_patches + 2 def lowercase ( self : int ) -> Optional[int]: lowercase : List[Any] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) lowercase : List[Any] = None if self.use_labels: lowercase : Optional[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) lowercase : str = self.get_config() return config, input_values, labels def lowercase ( self : List[str] ) -> Any: return ASTConfig( patch_size=self.patch_size, max_length=self.max_length, num_mel_bins=self.num_mel_bins, 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=lowerCAmelCase, initializer_range=self.initializer_range, frequency_stride=self.frequency_stride, time_stride=self.time_stride, ) def lowercase ( self : str, lowerCAmelCase : List[Any], lowerCAmelCase : Optional[Any], lowerCAmelCase : Union[str, Any] ) -> Optional[int]: lowercase : Any = ASTModel(config=lowerCAmelCase ) model.to(lowerCAmelCase ) model.eval() lowercase : Any = model(lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase ( self : Any ) -> Tuple: lowercase : List[Any] = self.prepare_config_and_inputs() ( ( lowercase ) , ( lowercase ) , ( lowercase ) , ) : Dict = config_and_inputs lowercase : Union[str, Any] = {'input_values': input_values} return config, inputs_dict @require_torch class a__ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, unittest.TestCase ): _lowerCamelCase = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) _lowerCamelCase = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False def lowercase ( self : Any, lowerCAmelCase : Any, lowerCAmelCase : Tuple, lowerCAmelCase : Dict, lowerCAmelCase : List[str], lowerCAmelCase : int ) -> Tuple: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def lowercase ( self : Optional[Any] ) -> Dict: lowercase : List[Any] = ASTModelTester(self ) lowercase : Any = ConfigTester(self, config_class=lowerCAmelCase, has_text_modality=lowerCAmelCase, hidden_size=37 ) def lowercase ( self : Tuple ) -> Optional[int]: self.config_tester.run_common_tests() @unittest.skip(reason='AST does not use inputs_embeds' ) def lowercase ( self : Tuple ) -> List[Any]: pass def lowercase ( self : Union[str, Any] ) -> List[str]: lowercase , lowercase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : Optional[Any] = model_class(lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) lowercase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase, nn.Linear ) ) def lowercase ( self : Union[str, Any] ) -> Optional[Any]: lowercase , lowercase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : Optional[int] = model_class(lowerCAmelCase ) lowercase : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase : List[Any] = [*signature.parameters.keys()] lowercase : str = ['input_values'] self.assertListEqual(arg_names[:1], lowerCAmelCase ) def lowercase ( self : Optional[int] ) -> Tuple: lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase ) @slow def lowercase ( self : List[str] ) -> Optional[Any]: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : Dict = ASTModel.from_pretrained(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase ) def lowercase__ ( ) -> Any: '''simple docstring''' lowercase : Tuple = hf_hub_download( repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' ) lowercase , lowercase : List[str] = torchaudio.load(_UpperCAmelCase ) return audio, sampling_rate @require_torch @require_torchaudio class a__ ( unittest.TestCase ): @cached_property def lowercase ( self : Union[str, Any] ) -> Optional[int]: return ( ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ) if is_torchaudio_available() else None ) @slow def lowercase ( self : Any ) -> Optional[Any]: lowercase : List[str] = self.default_feature_extractor lowercase : Tuple = ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ).to(lowerCAmelCase ) lowercase : List[str] = self.default_feature_extractor lowercase , lowercase : Optional[int] = prepare_audio() lowercase : List[str] = audio.squeeze().numpy() lowercase : List[Any] = feature_extractor(lowerCAmelCase, sampling_rate=lowerCAmelCase, return_tensors='pt' ).to(lowerCAmelCase ) # forward pass with torch.no_grad(): lowercase : List[Any] = model(**lowerCAmelCase ) # verify the logits lowercase : Union[str, Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape, lowerCAmelCase ) lowercase : Any = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3], lowerCAmelCase, atol=1e-4 ) )
53
0
from __future__ import annotations import math def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_UpperCAmelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True _UpperCAmelCase : Any = [num for num in range(3, 10_00_01, 2) if not is_prime(num)] def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> list[int]: if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) lowerCamelCase__ : int = [] for num in range(len(_UpperCAmelCase ) ): lowerCamelCase__ : Union[str, Any] = 0 while 2 * i * i <= odd_composites[num]: lowerCamelCase__ : Dict = odd_composites[num] - 2 * i * i if is_prime(_UpperCAmelCase ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(_UpperCAmelCase ) == n: return list_nums return [] def SCREAMING_SNAKE_CASE ( ) -> int: return compute_nums(1 )[0] if __name__ == "__main__": print(F"""{solution() = }""")
50
'''simple docstring''' import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase : Union[str, Any] = old_name if "patch_embed" in old_name: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Dict = old_name.split("." ) if layer == "0": _UpperCAmelCase : List[str] = old_name.replace("0" , "convolution1" ) elif layer == "1": _UpperCAmelCase : Dict = old_name.replace("1" , "batchnorm_before" ) elif layer == "3": _UpperCAmelCase : Tuple = old_name.replace("3" , "convolution2" ) else: _UpperCAmelCase : Tuple = old_name.replace("4" , "batchnorm_after" ) if "network" in old_name and re.search(R"\d\.\d" , __lowerCAmelCase ): _UpperCAmelCase : List[Any] = R"\b\d{2}\b" if bool(re.search(__lowerCAmelCase , __lowerCAmelCase ) ): _UpperCAmelCase : Optional[int] = re.search(R"\d\.\d\d." , __lowerCAmelCase ).group() else: _UpperCAmelCase : Any = re.search(R"\d\.\d." , __lowerCAmelCase ).group() if int(match[0] ) < 6: _UpperCAmelCase : str = old_name.replace(__lowerCAmelCase , "" ) _UpperCAmelCase : Optional[Any] = trimmed_name.replace("network" , match[0] + ".meta4D_layers.blocks." + match[2:-1] ) _UpperCAmelCase : Union[str, Any] = "intermediate_stages." + trimmed_name else: _UpperCAmelCase : Tuple = old_name.replace(__lowerCAmelCase , "" ) if int(match[2] ) < num_meta4D_last_stage: _UpperCAmelCase : Any = trimmed_name.replace("network" , "meta4D_layers.blocks." + match[2] ) else: _UpperCAmelCase : List[str] = str(int(match[2] ) - num_meta4D_last_stage ) _UpperCAmelCase : int = trimmed_name.replace("network" , "meta3D_layers.blocks." + layer_index ) if "norm1" in old_name: _UpperCAmelCase : Tuple = trimmed_name.replace("norm1" , "layernorm1" ) elif "norm2" in old_name: _UpperCAmelCase : int = trimmed_name.replace("norm2" , "layernorm2" ) elif "fc1" in old_name: _UpperCAmelCase : Optional[int] = trimmed_name.replace("fc1" , "linear_in" ) elif "fc2" in old_name: _UpperCAmelCase : List[str] = trimmed_name.replace("fc2" , "linear_out" ) _UpperCAmelCase : Optional[Any] = "last_stage." + trimmed_name elif "network" in old_name and re.search(R".\d." , __lowerCAmelCase ): _UpperCAmelCase : Optional[Any] = old_name.replace("network" , "intermediate_stages" ) if "fc" in new_name: _UpperCAmelCase : Union[str, Any] = new_name.replace("fc" , "convolution" ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): _UpperCAmelCase : List[Any] = new_name.replace("norm1" , "batchnorm_before" ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): _UpperCAmelCase : List[Any] = new_name.replace("norm2" , "batchnorm_after" ) if "proj" in new_name: _UpperCAmelCase : Union[str, Any] = new_name.replace("proj" , "projection" ) if "dist_head" in new_name: _UpperCAmelCase : List[Any] = new_name.replace("dist_head" , "distillation_classifier" ) elif "head" in new_name: _UpperCAmelCase : str = new_name.replace("head" , "classifier" ) elif "patch_embed" in new_name: _UpperCAmelCase : List[str] = "efficientformer." + new_name elif new_name == "norm.weight" or new_name == "norm.bias": _UpperCAmelCase : List[Any] = new_name.replace("norm" , "layernorm" ) _UpperCAmelCase : Any = "efficientformer." + new_name else: _UpperCAmelCase : Dict = "efficientformer.encoder." + new_name return new_name def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase ): for key in checkpoint.copy().keys(): _UpperCAmelCase : List[Any] = checkpoint.pop(__lowerCAmelCase ) _UpperCAmelCase : List[Any] = val return checkpoint def __lowerCAmelCase (): _UpperCAmelCase : Optional[int] = "http://images.cocodataset.org/val2017/000000039769.jpg" _UpperCAmelCase : Tuple = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) return image def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase : Union[str, Any] = torch.load(__lowerCAmelCase , map_location="cpu" )["model"] _UpperCAmelCase : Dict = EfficientFormerConfig.from_json_file(__lowerCAmelCase ) _UpperCAmelCase : Optional[Any] = EfficientFormerForImageClassificationWithTeacher(__lowerCAmelCase ) _UpperCAmelCase : Tuple = "_".join(checkpoint_path.split("/" )[-1].split("." )[0].split("_" )[:-1] ) _UpperCAmelCase : Union[str, Any] = config.depths[-1] - config.num_metaad_blocks + 1 _UpperCAmelCase : Optional[int] = convert_torch_checkpoint(__lowerCAmelCase , __lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() _UpperCAmelCase : Optional[Any] = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } # prepare image _UpperCAmelCase : int = prepare_img() _UpperCAmelCase : List[str] = 256 _UpperCAmelCase : Optional[int] = 224 _UpperCAmelCase : Tuple = EfficientFormerImageProcessor( size={"shortest_edge": image_size} , crop_size={"height": crop_size, "width": crop_size} , resample=pillow_resamplings["bicubic"] , ) _UpperCAmelCase : Any = processor(images=__lowerCAmelCase , return_tensors="pt" ).pixel_values # original processing pipeline _UpperCAmelCase : int = Compose( [ Resize(__lowerCAmelCase , interpolation=pillow_resamplings["bicubic"] ), CenterCrop(__lowerCAmelCase ), ToTensor(), Normalize(__lowerCAmelCase , __lowerCAmelCase ), ] ) _UpperCAmelCase : Any = image_transforms(__lowerCAmelCase ).unsqueeze(0 ) assert torch.allclose(__lowerCAmelCase , __lowerCAmelCase ) _UpperCAmelCase : Union[str, Any] = model(__lowerCAmelCase ) _UpperCAmelCase : Dict = outputs.logits _UpperCAmelCase : Optional[int] = (1, 1_000) if "l1" in model_name: _UpperCAmelCase : List[Any] = torch.Tensor( [-0.1_3_1_2, 0.4_3_5_3, -1.0_4_9_9, -0.5_1_2_4, 0.4_1_8_3, -0.6_7_9_3, -1.3_7_7_7, -0.0_8_9_3, -0.7_3_5_8, -2.4_3_2_8] ) assert torch.allclose(logits[0, :10] , __lowerCAmelCase , atol=1e-3 ) assert logits.shape == expected_shape elif "l3" in model_name: _UpperCAmelCase : List[Any] = torch.Tensor( [-1.3_1_5_0, -1.5_4_5_6, -1.2_5_5_6, -0.8_4_9_6, -0.7_1_2_7, -0.7_8_9_7, -0.9_7_2_8, -0.3_0_5_2, 0.3_7_5_1, -0.3_1_2_7] ) assert torch.allclose(logits[0, :10] , __lowerCAmelCase , atol=1e-3 ) assert logits.shape == expected_shape elif "l7" in model_name: _UpperCAmelCase : List[Any] = torch.Tensor( [-1.0_2_8_3, -1.4_1_3_1, -0.5_6_4_4, -1.3_1_1_5, -0.5_7_8_5, -1.2_0_4_9, -0.7_5_2_8, 0.1_9_9_2, -0.3_8_2_2, -0.0_8_7_8] ) assert logits.shape == expected_shape else: raise ValueError( F"""Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7""" ) # Save Checkpoints Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) print(F"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) processor.save_pretrained(__lowerCAmelCase ) print(F"""Processor successfuly saved at {pytorch_dump_path}""" ) if push_to_hub: print("Pushing model to the hub..." ) model.push_to_hub( repo_id=F"""Bearnardd/{pytorch_dump_path}""" , commit_message="Add model" , use_temp_dir=__lowerCAmelCase , ) processor.push_to_hub( repo_id=F"""Bearnardd/{pytorch_dump_path}""" , commit_message="Add image processor" , use_temp_dir=__lowerCAmelCase , ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) lowerCamelCase__ = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
234
0
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : List[str] , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] ) -> Any: """simple docstring""" if index == r: for j in range(__magic_name__ ): print(data[j] , end=""" """ ) print(""" """ ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location UpperCamelCase :Union[str, Any] = arr[i] combination_util(__magic_name__ , __magic_name__ , __magic_name__ , index + 1 , __magic_name__ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict ) -> List[Any]: """simple docstring""" UpperCamelCase :Any = [0] * r # Print all combination using temporary array 'data[]' combination_util(__magic_name__ , __magic_name__ , __magic_name__ , 0 , __magic_name__ , 0 ) if __name__ == "__main__": # Driver code to check the function above UpperCAmelCase_ : Any = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
62
from __future__ import annotations from collections import deque class _SCREAMING_SNAKE_CASE : def __init__( self : Optional[Any] , __lowerCamelCase : list[str] ): UpperCamelCase :list[dict] = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(__lowerCamelCase ) self.set_fail_transitions() def _A ( self : Tuple , __lowerCamelCase : int , __lowerCamelCase : str ): for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def _A ( self : int , __lowerCamelCase : str ): UpperCamelCase :List[str] = 0 for character in keyword: UpperCamelCase :List[Any] = self.find_next_state(__lowerCamelCase , __lowerCamelCase ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) UpperCamelCase :Optional[int] = len(self.adlist ) - 1 else: UpperCamelCase :Union[str, Any] = next_state self.adlist[current_state]["output"].append(__lowerCamelCase ) def _A ( self : List[str] ): UpperCamelCase :deque = deque() for node in self.adlist[0]["next_states"]: q.append(__lowerCamelCase ) UpperCamelCase :Tuple = 0 while q: UpperCamelCase :Union[str, Any] = q.popleft() for child in self.adlist[r]["next_states"]: q.append(__lowerCamelCase ) UpperCamelCase :Optional[int] = self.adlist[r]["""fail_state"""] while ( self.find_next_state(__lowerCamelCase , self.adlist[child]["""value"""] ) is None and state != 0 ): UpperCamelCase :List[Any] = self.adlist[state]["""fail_state"""] UpperCamelCase :List[str] = self.find_next_state( __lowerCamelCase , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: UpperCamelCase :Any = 0 UpperCamelCase :Tuple = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def _A ( self : Union[str, Any] , __lowerCamelCase : str ): UpperCamelCase :dict = {} # returns a dict with keywords and list of its occurrences UpperCamelCase :Union[str, Any] = 0 for i in range(len(__lowerCamelCase ) ): while ( self.find_next_state(__lowerCamelCase , string[i] ) is None and current_state != 0 ): UpperCamelCase :List[Any] = self.adlist[current_state]["""fail_state"""] UpperCamelCase :Optional[Any] = self.find_next_state(__lowerCamelCase , string[i] ) if next_state is None: UpperCamelCase :Dict = 0 else: UpperCamelCase :List[str] = next_state for key in self.adlist[current_state]["output"]: if key not in result: UpperCamelCase :Optional[int] = [] result[key].append(i - len(__lowerCamelCase ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
62
1
"""simple docstring""" from typing import Any import numpy as np def a__ ( SCREAMING_SNAKE_CASE : np.ndarray ): '''simple docstring''' return np.array_equal(SCREAMING_SNAKE_CASE , matrix.conjugate().T ) def a__ ( SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : np.ndarray ): '''simple docstring''' lowerCAmelCase : Union[str, Any] = v.conjugate().T lowerCAmelCase : int = v_star.dot(SCREAMING_SNAKE_CASE ) assert isinstance(SCREAMING_SNAKE_CASE , np.ndarray ) return (v_star_dot.dot(SCREAMING_SNAKE_CASE )) / (v_star.dot(SCREAMING_SNAKE_CASE )) def a__ ( ): '''simple docstring''' lowerCAmelCase : Dict = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) lowerCAmelCase : Any = np.array([[1], [2], [3]] ) assert is_hermitian(SCREAMING_SNAKE_CASE ), f"""{a} is not hermitian.""" print(rayleigh_quotient(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) lowerCAmelCase : Dict = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(SCREAMING_SNAKE_CASE ), f"""{a} is not hermitian.""" assert rayleigh_quotient(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
108
"""simple docstring""" import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration __snake_case : Optional[int] = 50_000 __snake_case : Dict = 5_000 __snake_case , __snake_case : Union[str, Any] = os.path.split(__file__) __snake_case : Any = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def _lowercase ( __snake_case ,__snake_case ) -> Dict: for i in range(__snake_case ): __lowerCAmelCase : Union[str, Any] = dataset[i] @get_duration def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Dict: for i in range(0 ,len(__snake_case ) ,__snake_case ): __lowerCAmelCase : List[str] = dataset[i : i + batch_size] @get_duration def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Dict: with dataset.formatted_as(type=__snake_case ): for i in range(__snake_case ): __lowerCAmelCase : Union[str, Any] = dataset[i] @get_duration def _lowercase ( __snake_case ,__snake_case ,__snake_case ,__snake_case ) -> str: with dataset.formatted_as(type=__snake_case ): for i in range(0 ,__snake_case ,__snake_case ): __lowerCAmelCase : Optional[int] = dataset[i : i + batch_size] def _lowercase ( ) -> Union[str, Any]: __lowerCAmelCase : Optional[int] = {"num examples": SPEED_TEST_N_EXAMPLES} __lowerCAmelCase : Optional[int] = [ (read, {"length": SMALL_TEST}), (read, {"length": SPEED_TEST_N_EXAMPLES}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 10}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 100}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_000}), (read_formatted, {"type": "numpy", "length": SMALL_TEST}), (read_formatted, {"type": "pandas", "length": SMALL_TEST}), (read_formatted, {"type": "torch", "length": SMALL_TEST}), (read_formatted, {"type": "tensorflow", "length": SMALL_TEST}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 10}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_000}), ] __lowerCAmelCase : Any = [ (read, {"length": SMALL_TEST}), (read, {"length": SPEED_TEST_N_EXAMPLES}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 10}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 100}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_000}), (read_formatted, {"type": "numpy", "length": SMALL_TEST}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 10}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("generating dataset" ) __lowerCAmelCase : int = datasets.Features( {"list": datasets.Sequence(datasets.Value("float32" ) ), "numbers": datasets.Value("float32" )} ) __lowerCAmelCase : str = generate_example_dataset( os.path.join(__snake_case ,"dataset.arrow" ) ,__snake_case ,num_examples=__snake_case ,seq_shapes={"list": (100,)} ,) print("first set of iterations" ) for func, kwargs in functions: print(func.__name__ ,str(__snake_case ) ) __lowerCAmelCase : str = func(__snake_case ,**__snake_case ) print("shuffling dataset" ) __lowerCAmelCase : Optional[int] = dataset.shuffle() print("Second set of iterations (after shuffling" ) for func, kwargs in functions_shuffled: print("shuffled " ,func.__name__ ,str(__snake_case ) ) __lowerCAmelCase : List[str] = func( __snake_case ,**__snake_case ) with open(__snake_case ,"wb" ) as f: f.write(json.dumps(__snake_case ).encode("utf-8" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
269
0
'''simple docstring''' import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) a_ : Optional[Any] = logging.getLogger(__name__) def _A () -> Tuple: '''simple docstring''' _a = argparse.ArgumentParser( description='Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).' ) parser.add_argument('--file_path' , type=lowerCamelCase_ , default='data/dump.txt' , help='The path to the data.' ) parser.add_argument('--tokenizer_type' , type=lowerCamelCase_ , default='bert' , choices=['bert', 'roberta', 'gpt2'] ) parser.add_argument('--tokenizer_name' , type=lowerCamelCase_ , default='bert-base-uncased' , help='The tokenizer to use.' ) parser.add_argument('--dump_file' , type=lowerCamelCase_ , default='data/dump' , help='The dump file prefix.' ) _a = parser.parse_args() logger.info(f'Loading Tokenizer ({args.tokenizer_name})' ) if args.tokenizer_type == "bert": _a = BertTokenizer.from_pretrained(args.tokenizer_name ) _a = tokenizer.special_tokens_map['cls_token'] # `[CLS]` _a = tokenizer.special_tokens_map['sep_token'] # `[SEP]` elif args.tokenizer_type == "roberta": _a = RobertaTokenizer.from_pretrained(args.tokenizer_name ) _a = tokenizer.special_tokens_map['cls_token'] # `<s>` _a = tokenizer.special_tokens_map['sep_token'] # `</s>` elif args.tokenizer_type == "gpt2": _a = GPTaTokenizer.from_pretrained(args.tokenizer_name ) _a = tokenizer.special_tokens_map['bos_token'] # `<|endoftext|>` _a = tokenizer.special_tokens_map['eos_token'] # `<|endoftext|>` logger.info(f'Loading text from {args.file_path}' ) with open(args.file_path , 'r' , encoding='utf8' ) as fp: _a = fp.readlines() logger.info('Start encoding' ) logger.info(f'{len(lowerCamelCase_ )} examples to process.' ) _a = [] _a = 0 _a = 1_00_00 _a = time.time() for text in data: _a = f'{bos} {text.strip()} {sep}' _a = tokenizer.encode(lowerCamelCase_ , add_special_tokens=lowerCamelCase_ ) rslt.append(lowerCamelCase_ ) iter += 1 if iter % interval == 0: _a = time.time() logger.info(f'{iter} examples processed. - {(end-start):.2f}s/{interval}expl' ) _a = time.time() logger.info('Finished binarization' ) logger.info(f'{len(lowerCamelCase_ )} examples processed.' ) _a = f'{args.dump_file}.{args.tokenizer_name}.pickle' _a = tokenizer.vocab_size if vocab_size < (1 << 16): _a = [np.uintaa(lowerCamelCase_ ) for d in rslt] else: _a = [np.intaa(lowerCamelCase_ ) for d in rslt] random.shuffle(rslt_ ) logger.info(f'Dump to {dp_file}' ) with open(lowerCamelCase_ , 'wb' ) as handle: pickle.dump(rslt_ , lowerCamelCase_ , protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
368
'''simple docstring''' def _A (lowerCAmelCase__ :list ) -> float: '''simple docstring''' _a = 0 while len(lowerCAmelCase__ ) > 1: _a = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): _a = files.index(min(lowerCAmelCase__ ) ) temp += files[min_index] files.pop(lowerCAmelCase__ ) files.append(lowerCAmelCase__ ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
104
0
def _a ( SCREAMING_SNAKE_CASE_ : int = 1_00_00_00 ): __lowerCAmelCase = set(range(3 , SCREAMING_SNAKE_CASE_ , 2 ) ) primes.add(2 ) for p in range(3 , SCREAMING_SNAKE_CASE_ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) ) __lowerCAmelCase = [float(SCREAMING_SNAKE_CASE_ ) for n in range(limit + 1 )] for p in primes: for n in range(SCREAMING_SNAKE_CASE_ , limit + 1 , SCREAMING_SNAKE_CASE_ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'''{solution() = }''')
92
"""simple docstring""" 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_ : '''simple docstring''' def __init__( self , lowercase_ , lowercase_=13 , lowercase_=30 , lowercase_=2 , lowercase_=3 , lowercase_=True , lowercase_=True , lowercase_=32 , lowercase_=5 , lowercase_=4 , lowercase_=37 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=10 , lowercase_=0.02 , lowercase_=3 , lowercase_=None , lowercase_=2 , ): """simple docstring""" UpperCAmelCase_ : List[str] = parent UpperCAmelCase_ : int = batch_size UpperCAmelCase_ : int = image_size UpperCAmelCase_ : List[Any] = patch_size UpperCAmelCase_ : Any = num_channels UpperCAmelCase_ : Optional[int] = is_training UpperCAmelCase_ : Union[str, Any] = use_labels UpperCAmelCase_ : Union[str, Any] = hidden_size UpperCAmelCase_ : str = num_hidden_layers UpperCAmelCase_ : List[str] = num_attention_heads UpperCAmelCase_ : str = intermediate_size UpperCAmelCase_ : str = hidden_act UpperCAmelCase_ : List[Any] = hidden_dropout_prob UpperCAmelCase_ : Union[str, Any] = attention_probs_dropout_prob UpperCAmelCase_ : str = type_sequence_label_size UpperCAmelCase_ : str = initializer_range UpperCAmelCase_ : Union[str, Any] = scope UpperCAmelCase_ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) UpperCAmelCase_ : int = (image_size // patch_size) ** 2 UpperCAmelCase_ : Optional[Any] = num_patches + 2 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase_ : Tuple = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Union[str, Any] = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( 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=lowercase_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = DeiTModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : List[Any] = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = DeiTForMaskedImageModeling(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : List[Any] = model(lowercase_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCAmelCase_ : List[str] = 1 UpperCAmelCase_ : Optional[Any] = DeiTForMaskedImageModeling(lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase_ : Optional[int] = model(lowercase_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Tuple = self.type_sequence_label_size UpperCAmelCase_ : Union[str, Any] = DeiTForImageClassification(lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : List[str] = model(lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase_ : Union[str, Any] = 1 UpperCAmelCase_ : Optional[int] = DeiTForImageClassification(lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase_ : List[Any] = model(lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[str] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Dict = config_and_inputs UpperCAmelCase_ : Optional[int] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class A_ (lowercase__ ,lowercase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ : Tuple = ( { """feature-extraction""": DeiTModel, """image-classification""": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : List[str] = False def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Any = DeiTModelTester(self ) UpperCAmelCase_ : Optional[int] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37 ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : List[Any] = model_class(lowercase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase_ : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_ , nn.Linear ) ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : Dict = model_class(lowercase_ ) UpperCAmelCase_ : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ : str = [*signature.parameters.keys()] UpperCAmelCase_ : Optional[int] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_=False ): """simple docstring""" UpperCAmelCase_ : Tuple = super()._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def UpperCamelCase__ ( self ): """simple docstring""" if not self.model_tester.is_training: return UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Union[str, Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(lowercase_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue UpperCAmelCase_ : Optional[int] = model_class(lowercase_ ) model.to(lowercase_ ) model.train() UpperCAmelCase_ : List[Any] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_ ) UpperCAmelCase_ : Dict = model(**lowercase_ ).loss loss.backward() def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return UpperCAmelCase_ : Dict = False UpperCAmelCase_ : Optional[int] = True for model_class in self.all_model_classes: if model_class in get_values(lowercase_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue UpperCAmelCase_ : List[str] = model_class(lowercase_ ) model.gradient_checkpointing_enable() model.to(lowercase_ ) model.train() UpperCAmelCase_ : Optional[int] = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_ ) UpperCAmelCase_ : Any = model(**lowercase_ ).loss loss.backward() def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : Dict = [ {"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(lowercase_ ), *get_values(lowercase_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"""Testing {model_class} with {problem_type["title"]}""" ): UpperCAmelCase_ : str = problem_type["title"] UpperCAmelCase_ : List[Any] = problem_type["num_labels"] UpperCAmelCase_ : Union[str, Any] = model_class(lowercase_ ) model.to(lowercase_ ) model.train() UpperCAmelCase_ : int = self._prepare_for_class(lowercase_ , lowercase_ , return_labels=lowercase_ ) if problem_type["num_labels"] > 1: UpperCAmelCase_ : List[Any] = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) UpperCAmelCase_ : Tuple = 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=lowercase_ ) as warning_list: UpperCAmelCase_ : List[str] = model(**lowercase_ ).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 UpperCamelCase__ ( self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Union[str, Any] = DeiTModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def __a ( ): UpperCAmelCase_ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class A_ (unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( lowercase_ ) UpperCAmelCase_ : List[str] = self.default_image_processor UpperCAmelCase_ : List[str] = prepare_img() UpperCAmelCase_ : int = image_processor(images=lowercase_ , return_tensors="pt" ).to(lowercase_ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Dict = model(**lowercase_ ) # verify the logits UpperCAmelCase_ : List[str] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowercase_ ) UpperCAmelCase_ : str = torch.tensor([-1.02_66, 0.19_12, -1.28_61] ).to(lowercase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[str] = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) UpperCAmelCase_ : str = self.default_image_processor UpperCAmelCase_ : Union[str, Any] = prepare_img() UpperCAmelCase_ : List[Any] = image_processor(images=lowercase_ , return_tensors="pt" ) UpperCAmelCase_ : List[str] = inputs.pixel_values.to(lowercase_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): UpperCAmelCase_ : int = model(lowercase_ )
61
0
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def _snake_case ( _snake_case : Union[str, Any] , _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : str , _snake_case : Union[str, Any]=True , _snake_case : List[Any]="pt" ): lowerCAmelCase : int = {'''add_prefix_space''': True} if isinstance(A__ , A__ ) and not line.startswith(''' ''' ) else {} lowerCAmelCase : List[Any] = padding_side return tokenizer( [line] , max_length=A__ , padding='''max_length''' if pad_to_max_length else None , truncation=A__ , return_tensors=A__ , add_special_tokens=A__ , **A__ , ) def _snake_case ( _snake_case : Union[str, Any] , _snake_case : int , _snake_case : str=None , ): lowerCAmelCase : int = input_ids.ne(A__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case_( lowerCamelCase__ ): def __init__( self : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Tuple="train" , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Optional[int]=None , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : List[Any]="" , ): super().__init__() lowerCAmelCase : Tuple = Path(lowercase__ ).joinpath(type_path + '''.source''' ) lowerCAmelCase : Any = Path(lowercase__ ).joinpath(type_path + '''.target''' ) lowerCAmelCase : Dict = self.get_char_lens(self.src_file ) lowerCAmelCase : str = max_source_length lowerCAmelCase : str = max_target_length assert min(self.src_lens ) > 0, F'''found empty line in {self.src_file}''' lowerCAmelCase : Tuple = tokenizer lowerCAmelCase : Dict = prefix if n_obs is not None: lowerCAmelCase : Any = self.src_lens[:n_obs] lowerCAmelCase : List[str] = src_lang lowerCAmelCase : List[str] = tgt_lang def __len__( self : Optional[Any] ): return len(self.src_lens ) def __getitem__( self : Optional[Any] , UpperCamelCase_ : List[Any] ): lowerCAmelCase : Any = index + 1 # linecache starts at 1 lowerCAmelCase : List[Any] = self.prefix + linecache.getline(str(self.src_file ) , lowercase__ ).rstrip('''\n''' ) lowerCAmelCase : Dict = linecache.getline(str(self.tgt_file ) , lowercase__ ).rstrip('''\n''' ) assert source_line, F'''empty source line for index {index}''' assert tgt_line, F'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , lowercase__ ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right lowerCAmelCase : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer ) lowerCAmelCase : Any = self.tokenizer.generator if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer lowerCAmelCase : Optional[int] = encode_line(lowercase__ , lowercase__ , self.max_source_length , '''right''' ) lowerCAmelCase : Tuple = encode_line(lowercase__ , lowercase__ , self.max_target_length , '''right''' ) lowerCAmelCase : List[Any] = source_inputs['''input_ids'''].squeeze() lowerCAmelCase : Union[str, Any] = target_inputs['''input_ids'''].squeeze() lowerCAmelCase : Union[str, Any] = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowerCamelCase__ ( UpperCamelCase_ : List[str] ): return [len(lowercase__ ) for x in Path(lowercase__ ).open().readlines()] def lowerCamelCase__ ( self : int , UpperCamelCase_ : Tuple ): lowerCAmelCase : Tuple = torch.stack([x['''input_ids'''] for x in batch] ) lowerCAmelCase : List[Any] = torch.stack([x['''attention_mask'''] for x in batch] ) lowerCAmelCase : str = torch.stack([x['''decoder_input_ids'''] for x in batch] ) lowerCAmelCase : List[Any] = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer.pad_token_id ) lowerCAmelCase : Optional[Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , lowercase__ ) else self.tokenizer.pad_token_id ) lowerCAmelCase : List[str] = trim_batch(lowercase__ , lowercase__ ) lowerCAmelCase, lowerCAmelCase : Dict = trim_batch(lowercase__ , lowercase__ , attention_mask=lowercase__ ) lowerCAmelCase : Tuple = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch snake_case__ : Optional[int] = getLogger(__name__) def _snake_case ( _snake_case : Optional[Any] ): return list(itertools.chain.from_iterable(A__ ) ) def _snake_case ( _snake_case : Dict ): lowerCAmelCase : Union[str, Any] = get_git_info() save_json(A__ , os.path.join(A__ , '''git_log.json''' ) ) def _snake_case ( _snake_case : Dict , _snake_case : int , _snake_case : Optional[Any]=4 , **_snake_case : str ): with open(A__ , '''w''' ) as f: json.dump(A__ , A__ , indent=A__ , **A__ ) def _snake_case ( _snake_case : Any ): with open(A__ ) as f: return json.load(A__ ) def _snake_case ( ): lowerCAmelCase : List[str] = git.Repo(search_parent_directories=A__ ) lowerCAmelCase : Tuple = { '''repo_id''': str(A__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def _snake_case ( _snake_case : Tuple , _snake_case : Optional[Any] ): return list(map(A__ , A__ ) ) def _snake_case ( _snake_case : Union[str, Any] , _snake_case : List[Any] ): with open(A__ , '''wb''' ) as f: return pickle.dump(A__ , A__ ) def _snake_case ( _snake_case : int ): def remove_articles(_snake_case : Tuple ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , A__ ) def white_space_fix(_snake_case : List[Any] ): return " ".join(text.split() ) def remove_punc(_snake_case : Optional[Any] ): lowerCAmelCase : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_snake_case : Union[str, Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A__ ) ) ) ) def _snake_case ( _snake_case : Optional[int] , _snake_case : Tuple ): lowerCAmelCase : Union[str, Any] = normalize_answer(A__ ).split() lowerCAmelCase : Optional[Any] = normalize_answer(A__ ).split() lowerCAmelCase : List[Any] = Counter(A__ ) & Counter(A__ ) lowerCAmelCase : List[str] = sum(common.values() ) if num_same == 0: return 0 lowerCAmelCase : Union[str, Any] = 1.0 * num_same / len(A__ ) lowerCAmelCase : str = 1.0 * num_same / len(A__ ) lowerCAmelCase : Any = (2 * precision * recall) / (precision + recall) return fa def _snake_case ( _snake_case : int , _snake_case : Any ): return normalize_answer(A__ ) == normalize_answer(A__ ) def _snake_case ( _snake_case : List[Any] , _snake_case : Union[str, Any] ): assert len(A__ ) == len(A__ ) lowerCAmelCase : str = 0 for hypo, pred in zip(A__ , A__ ): em += exact_match_score(A__ , A__ ) if len(A__ ) > 0: em /= len(A__ ) return {"em": em} def _snake_case ( _snake_case : str ): return model_prefix.startswith('''rag''' ) def _snake_case ( _snake_case : List[Any] , _snake_case : List[str] , _snake_case : Optional[Any] ): lowerCAmelCase : Optional[Any] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead lowerCAmelCase : List[Any] = '''dropout_rate''' for p in extra_params: if getattr(A__ , A__ , A__ ): if not hasattr(A__ , A__ ) and not hasattr(A__ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(A__ ) ) delattr(A__ , A__ ) continue lowerCAmelCase : Any = p if hasattr(A__ , A__ ) else equivalent_param[p] setattr(A__ , A__ , getattr(A__ , A__ ) ) delattr(A__ , A__ ) return hparams, config
358
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer snake_case__ : str = logging.get_logger(__name__) snake_case__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} snake_case__ : str = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } snake_case__ : Union[str, Any] = { '''bert-base-uncased''': 512, '''bert-large-uncased''': 512, '''bert-base-cased''': 512, '''bert-large-cased''': 512, '''bert-base-multilingual-uncased''': 512, '''bert-base-multilingual-cased''': 512, '''bert-base-chinese''': 512, '''bert-base-german-cased''': 512, '''bert-large-uncased-whole-word-masking''': 512, '''bert-large-cased-whole-word-masking''': 512, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 512, '''bert-large-cased-whole-word-masking-finetuned-squad''': 512, '''bert-base-cased-finetuned-mrpc''': 512, '''bert-base-german-dbmdz-cased''': 512, '''bert-base-german-dbmdz-uncased''': 512, '''TurkuNLP/bert-base-finnish-cased-v1''': 512, '''TurkuNLP/bert-base-finnish-uncased-v1''': 512, '''wietsedv/bert-base-dutch-cased''': 512, } snake_case__ : Optional[Any] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = BertTokenizer def __init__( self : int , UpperCamelCase_ : Union[str, Any]=None , UpperCamelCase_ : Optional[Any]=None , UpperCamelCase_ : str=True , UpperCamelCase_ : Dict="[UNK]" , UpperCamelCase_ : Any="[SEP]" , UpperCamelCase_ : Any="[PAD]" , UpperCamelCase_ : Tuple="[CLS]" , UpperCamelCase_ : List[Any]="[MASK]" , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : Tuple=None , **UpperCamelCase_ : Optional[int] , ): super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) lowerCAmelCase : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCamelCase_ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCamelCase_ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCamelCase_ ) != tokenize_chinese_chars ): lowerCAmelCase : Optional[int] = getattr(UpperCamelCase_ , normalizer_state.pop('''type''' ) ) lowerCAmelCase : Tuple = do_lower_case lowerCAmelCase : Union[str, Any] = strip_accents lowerCAmelCase : Tuple = tokenize_chinese_chars lowerCAmelCase : str = normalizer_class(**UpperCamelCase_ ) lowerCAmelCase : Optional[int] = do_lower_case def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple=None ): lowerCAmelCase : List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : Optional[Any] = [self.sep_token_id] lowerCAmelCase : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): lowerCAmelCase : str = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
314
0
'''simple docstring''' from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class lowerCAmelCase__ ( __lowerCamelCase ): lowerCAmelCase : Any = "dandelin/vilt-b32-finetuned-vqa" lowerCAmelCase : Optional[int] = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) lowerCAmelCase : Tuple = "image_qa" lowerCAmelCase : List[str] = AutoProcessor lowerCAmelCase : List[Any] = AutoModelForVisualQuestionAnswering lowerCAmelCase : Optional[Any] = ["image", "text"] lowerCAmelCase : Optional[int] = ["text"] def __init__( self : List[str] , *lowerCamelCase__ : str , **lowerCamelCase__ : List[str] ) ->List[str]: '''simple docstring''' requires_backends(self , ["vision"] ) super().__init__(*__A , **__A ) def lowerCAmelCase__ ( self : List[Any] , lowerCamelCase__ : "Image" , lowerCamelCase__ : str ) ->str: '''simple docstring''' return self.pre_processor(__A , __A , return_tensors="pt" ) def lowerCAmelCase__ ( self : Any , lowerCamelCase__ : Tuple ) ->Optional[Any]: '''simple docstring''' with torch.no_grad(): return self.model(**__A ).logits def lowerCAmelCase__ ( self : Tuple , lowerCamelCase__ : int ) ->Any: '''simple docstring''' _UpperCAmelCase : Union[str, Any] = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
234
'''simple docstring''' import random def lowercase__ ( __lowercase : list , __lowercase : Optional[Any] ) -> tuple: """simple docstring""" __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = [], [], [] for element in data: if element < pivot: less.append(__lowercase ) elif element > pivot: greater.append(__lowercase ) else: equal.append(__lowercase ) return less, equal, greater def lowercase__ ( __lowercase : list , __lowercase : int ) -> Dict: """simple docstring""" if index >= len(__lowercase ) or index < 0: return None __UpperCamelCase = items[random.randint(0 , len(__lowercase ) - 1 )] __UpperCamelCase = 0 __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = _partition(__lowercase , __lowercase ) __UpperCamelCase = len(__lowercase ) __UpperCamelCase = len(__lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(__lowercase , __lowercase ) # must be in larger else: return quick_select(__lowercase , index - (m + count) )
53
0
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : str, lowerCamelCase : Union[str, Any], lowerCamelCase : Dict=None, lowerCamelCase : int=True, lowerCamelCase : Optional[Any]=None, **lowerCamelCase : Optional[Any] )-> Optional[int]: lowerCamelCase__ : Tuple =parent lowerCamelCase__ : Union[str, Any] =config_class lowerCamelCase__ : str =has_text_modality lowerCamelCase__ : Any =kwargs lowerCamelCase__ : List[str] =common_properties def snake_case ( self : Dict )-> str: lowerCamelCase__ : int =self.config_class(**self.inputs_dict ) lowerCamelCase__ : str =( ['''hidden_size''', '''num_attention_heads''', '''num_hidden_layers'''] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(['''vocab_size'''] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(lowerCamelCase, lowerCamelCase ), msg=F'''`{prop}` does not exist''' ) # Test that config has the common properties as setter for idx, name in enumerate(lowerCamelCase ): try: setattr(lowerCamelCase, lowerCamelCase, lowerCamelCase ) self.parent.assertEqual( getattr(lowerCamelCase, lowerCamelCase ), lowerCamelCase, msg=F'''`{name} value {idx} expected, but was {getattr(lowerCamelCase, lowerCamelCase )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(lowerCamelCase ): try: lowerCamelCase__ : Tuple =self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(lowerCamelCase, lowerCamelCase ), lowerCamelCase, msg=F'''`{name} value {idx} expected, but was {getattr(lowerCamelCase, lowerCamelCase )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def snake_case ( self : str )-> Union[str, Any]: lowerCamelCase__ : Dict =self.config_class(**self.inputs_dict ) lowerCamelCase__ : Optional[int] =json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key], lowerCamelCase ) def snake_case ( self : Tuple )-> Union[str, Any]: lowerCamelCase__ : Optional[int] =self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase__ : Tuple =os.path.join(lowerCamelCase, '''config.json''' ) config_first.to_json_file(lowerCamelCase ) lowerCamelCase__ : Tuple =self.config_class.from_json_file(lowerCamelCase ) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict() ) def snake_case ( self : Optional[int] )-> List[Any]: lowerCamelCase__ : Optional[int] =self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(lowerCamelCase ) lowerCamelCase__ : Tuple =self.config_class.from_pretrained(lowerCamelCase ) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict() ) def snake_case ( self : Union[str, Any] )-> Any: lowerCamelCase__ : Dict =self.config_class(**self.inputs_dict ) lowerCamelCase__ : int ='''test''' with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase__ : Union[str, Any] =os.path.join(lowerCamelCase, lowerCamelCase ) config_first.save_pretrained(lowerCamelCase ) lowerCamelCase__ : int =self.config_class.from_pretrained(lowerCamelCase, subfolder=lowerCamelCase ) self.parent.assertEqual(config_second.to_dict(), config_first.to_dict() ) def snake_case ( self : str )-> Tuple: lowerCamelCase__ : int =self.config_class(**self.inputs_dict, num_labels=5 ) self.parent.assertEqual(len(config.idalabel ), 5 ) self.parent.assertEqual(len(config.labelaid ), 5 ) lowerCamelCase__ : List[Any] =3 self.parent.assertEqual(len(config.idalabel ), 3 ) self.parent.assertEqual(len(config.labelaid ), 3 ) def snake_case ( self : Optional[int] )-> int: if self.config_class.is_composition: return lowerCamelCase__ : Union[str, Any] =self.config_class() self.parent.assertIsNotNone(lowerCamelCase ) def snake_case ( self : Optional[int] )-> str: lowerCamelCase__ : Optional[Any] =copy.deepcopy(lowerCamelCase ) lowerCamelCase__ : List[Any] =self.config_class(**lowerCamelCase ) lowerCamelCase__ : Tuple =[] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(('''torch_dtype''', config.torch_dtype, torch.floataa) ) elif getattr(lowerCamelCase, lowerCamelCase ) != value: wrong_values.append((key, getattr(lowerCamelCase, lowerCamelCase ), value) ) if len(lowerCamelCase ) > 0: lowerCamelCase__ : Optional[int] ='''\n'''.join([F'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values] ) raise ValueError(F'''The following keys were not properly set in the config:\n{errors}''' ) def snake_case ( self : List[Any] )-> str: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
355
"""simple docstring""" import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device _lowercase : Tuple = False class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' pass @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def snake_case ( self : List[Any] )-> Dict: lowerCamelCase__ : str =VersatileDiffusionImageVariationPipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) lowerCamelCase__ : int =load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) lowerCamelCase__ : Dict =torch.manual_seed(0 ) lowerCamelCase__ : str =pipe( image=lowerCamelCase, generator=lowerCamelCase, guidance_scale=7.5, num_inference_steps=50, output_type='''numpy''', ).images lowerCamelCase__ : Dict =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase__ : List[Any] =np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
272
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _A = logging.get_logger(__name__) _A = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = "beit" def __init__( self , A_=8192 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.0 , A_=0.0 , A_=0.02 , A_=1E-12 , A_=224 , A_=16 , A_=3 , A_=False , A_=False , A_=False , A_=False , A_=0.1 , A_=0.1 , A_=True , A_=[3, 5, 7, 11] , A_=[1, 2, 3, 6] , A_=True , A_=0.4 , A_=256 , A_=1 , A_=False , A_=255 , **A_ , ) -> List[str]: super().__init__(**A_ ) __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =initializer_range __UpperCamelCase =layer_norm_eps __UpperCamelCase =image_size __UpperCamelCase =patch_size __UpperCamelCase =num_channels __UpperCamelCase =use_mask_token __UpperCamelCase =use_absolute_position_embeddings __UpperCamelCase =use_relative_position_bias __UpperCamelCase =use_shared_relative_position_bias __UpperCamelCase =layer_scale_init_value __UpperCamelCase =drop_path_rate __UpperCamelCase =use_mean_pooling # decode head attributes (semantic segmentation) __UpperCamelCase =out_indices __UpperCamelCase =pool_scales # auxiliary head attributes (semantic segmentation) __UpperCamelCase =use_auxiliary_head __UpperCamelCase =auxiliary_loss_weight __UpperCamelCase =auxiliary_channels __UpperCamelCase =auxiliary_num_convs __UpperCamelCase =auxiliary_concat_input __UpperCamelCase =semantic_loss_ignore_index class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Tuple = version.parse("1.11" ) @property def _a ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _a ( self ) -> float: return 1E-4
62
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
1
from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time UpperCAmelCase : List[str] = Lock() def __lowerCamelCase ( lowerCamelCase__ : List[Any] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : str , lowerCamelCase__ : List[Any] , lowerCamelCase__ : int , lowerCamelCase__ : List[str] ): '''simple docstring''' global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(lowerCamelCase__ ) process_lock.release() # receive your right neighbor's value process_lock.acquire() lowerCamelCase = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left lowerCamelCase = min(lowerCamelCase__ , lowerCamelCase__ ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(lowerCamelCase__ ) process_lock.release() # receive your left neighbor's value process_lock.acquire() lowerCamelCase = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right lowerCamelCase = max(lowerCamelCase__ , lowerCamelCase__ ) # after all swaps are performed, send the values back to main result_pipe[1].send(lowerCamelCase__ ) def __lowerCamelCase ( lowerCamelCase__ : List[Any] ): '''simple docstring''' lowerCamelCase = [] lowerCamelCase = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop lowerCamelCase = Pipe() lowerCamelCase = Pipe() process_array_.append( Process( target=lowerCamelCase__ , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) lowerCamelCase = temp_rs lowerCamelCase = temp_rr for i in range(1 , len(lowerCamelCase__ ) - 1 ): lowerCamelCase = Pipe() lowerCamelCase = Pipe() process_array_.append( Process( target=lowerCamelCase__ , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) lowerCamelCase = temp_rs lowerCamelCase = temp_rr process_array_.append( Process( target=lowerCamelCase__ , args=( len(lowerCamelCase__ ) - 1, arr[len(lowerCamelCase__ ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(lowerCamelCase__ ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(lowerCamelCase__ ) ): lowerCamelCase = result_pipe[p][0].recv() process_array_[p].join() return arr def __lowerCamelCase ( ): '''simple docstring''' lowerCamelCase = list(range(10 , 0 , -1 ) ) print("""Initial List""" ) print(*lowerCamelCase__ ) lowerCamelCase = odd_even_transposition(lowerCamelCase__ ) print("""Sorted List\n""" ) print(*lowerCamelCase__ ) if __name__ == "__main__": main()
66
import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) enable_full_determinism() class __lowercase ( a_ , a_ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Union[str, Any] = UNetaDModel UpperCamelCase : Union[str, Any] = "sample" @property def __A ( self ) -> str: '''simple docstring''' lowerCamelCase = 4 lowerCamelCase = 3 lowerCamelCase = (32, 32) lowerCamelCase = floats_tensor((batch_size, num_channels) + sizes ).to(A ) lowerCamelCase = torch.tensor([10] ).to(A ) return {"sample": noise, "timestep": time_step} @property def __A ( self ) -> Optional[int]: '''simple docstring''' return (3, 32, 32) @property def __A ( self ) -> Dict: '''simple docstring''' return (3, 32, 32) def __A ( self ) -> str: '''simple docstring''' lowerCamelCase = { """block_out_channels""": (32, 64), """down_block_types""": ("""DownBlock2D""", """AttnDownBlock2D"""), """up_block_types""": ("""AttnUpBlock2D""", """UpBlock2D"""), """attention_head_dim""": 3, """out_channels""": 3, """in_channels""": 3, """layers_per_block""": 2, """sample_size""": 32, } lowerCamelCase = self.dummy_input return init_dict, inputs_dict class __lowercase ( a_ , a_ , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = UNetaDModel UpperCamelCase : Dict = "sample" @property def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = 4 lowerCamelCase = 4 lowerCamelCase = (32, 32) lowerCamelCase = floats_tensor((batch_size, num_channels) + sizes ).to(A ) lowerCamelCase = torch.tensor([10] ).to(A ) return {"sample": noise, "timestep": time_step} @property def __A ( self ) -> Tuple: '''simple docstring''' return (4, 32, 32) @property def __A ( self ) -> Dict: '''simple docstring''' return (4, 32, 32) def __A ( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase = { """sample_size""": 32, """in_channels""": 4, """out_channels""": 4, """layers_per_block""": 2, """block_out_channels""": (32, 64), """attention_head_dim""": 32, """down_block_types""": ("""DownBlock2D""", """DownBlock2D"""), """up_block_types""": ("""UpBlock2D""", """UpBlock2D"""), } lowerCamelCase = self.dummy_input return init_dict, inputs_dict def __A ( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase , lowerCamelCase = UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" , output_loading_info=A ) self.assertIsNotNone(A ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(A ) lowerCamelCase = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != """cuda""" , """This test is supposed to run on GPU""" ) def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase , lowerCamelCase = UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" , output_loading_info=A ) model.to(A ) lowerCamelCase = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != """cuda""" , """This test is supposed to run on GPU""" ) def __A ( self ) -> Tuple: '''simple docstring''' lowerCamelCase , lowerCamelCase = UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" , output_loading_info=A ) model_accelerate.to(A ) model_accelerate.eval() lowerCamelCase = torch.randn( 1 , model_accelerate.config.in_channels , model_accelerate.config.sample_size , model_accelerate.config.sample_size , generator=torch.manual_seed(0 ) , ) lowerCamelCase = noise.to(A ) lowerCamelCase = torch.tensor([10] * noise.shape[0] ).to(A ) lowerCamelCase = model_accelerate(A , A )["""sample"""] # two models don't need to stay in the device at the same time del model_accelerate torch.cuda.empty_cache() gc.collect() lowerCamelCase , lowerCamelCase = UNetaDModel.from_pretrained( """fusing/unet-ldm-dummy-update""" , output_loading_info=A , low_cpu_mem_usage=A ) model_normal_load.to(A ) model_normal_load.eval() lowerCamelCase = model_normal_load(A , A )["""sample"""] assert torch_all_close(A , A , rtol=1e-3 ) def __A ( self ) -> Tuple: '''simple docstring''' lowerCamelCase = UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" ) model.eval() model.to(A ) lowerCamelCase = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) lowerCamelCase = noise.to(A ) lowerCamelCase = torch.tensor([10] * noise.shape[0] ).to(A ) with torch.no_grad(): lowerCamelCase = model(A , A ).sample lowerCamelCase = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off lowerCamelCase = torch.tensor([-13.3258, -20.1100, -15.9873, -17.6617, -23.0596, -17.9419, -13.3675, -16.1889, -12.3800] ) # fmt: on self.assertTrue(torch_all_close(A , A , rtol=1e-3 ) ) class __lowercase ( a_ , a_ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = UNetaDModel UpperCamelCase : Optional[int] = "sample" @property def __A ( self , A=(32, 32) ) -> List[Any]: '''simple docstring''' lowerCamelCase = 4 lowerCamelCase = 3 lowerCamelCase = floats_tensor((batch_size, num_channels) + sizes ).to(A ) lowerCamelCase = torch.tensor(batch_size * [10] ).to(dtype=torch.intaa , device=A ) return {"sample": noise, "timestep": time_step} @property def __A ( self ) -> Optional[int]: '''simple docstring''' return (3, 32, 32) @property def __A ( self ) -> Dict: '''simple docstring''' return (3, 32, 32) def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = { """block_out_channels""": [32, 64, 64, 64], """in_channels""": 3, """layers_per_block""": 1, """out_channels""": 3, """time_embedding_type""": """fourier""", """norm_eps""": 1e-6, """mid_block_scale_factor""": math.sqrt(2.0 ), """norm_num_groups""": None, """down_block_types""": [ """SkipDownBlock2D""", """AttnSkipDownBlock2D""", """SkipDownBlock2D""", """SkipDownBlock2D""", ], """up_block_types""": [ """SkipUpBlock2D""", """SkipUpBlock2D""", """AttnSkipUpBlock2D""", """SkipUpBlock2D""", ], } lowerCamelCase = self.dummy_input return init_dict, inputs_dict @slow def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase , lowerCamelCase = UNetaDModel.from_pretrained("""google/ncsnpp-celebahq-256""" , output_loading_info=A ) self.assertIsNotNone(A ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(A ) lowerCamelCase = self.dummy_input lowerCamelCase = floats_tensor((4, 3) + (2_56, 2_56) ).to(A ) lowerCamelCase = noise lowerCamelCase = model(**A ) assert image is not None, "Make sure output is not None" @slow def __A ( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase = UNetaDModel.from_pretrained("""google/ncsnpp-celebahq-256""" ) model.to(A ) lowerCamelCase = 4 lowerCamelCase = 3 lowerCamelCase = (2_56, 2_56) lowerCamelCase = torch.ones((batch_size, num_channels) + sizes ).to(A ) lowerCamelCase = torch.tensor(batch_size * [1e-4] ).to(A ) with torch.no_grad(): lowerCamelCase = model(A , A ).sample lowerCamelCase = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off lowerCamelCase = torch.tensor([-4842.8691, -6499.6631, -3800.1953, -7978.2686, -10980.7129, -20028.8535, 8148.2822, 2342.2905, 567.7608] ) # fmt: on self.assertTrue(torch_all_close(A , A , rtol=1e-2 ) ) def __A ( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase = UNetaDModel.from_pretrained("""fusing/ncsnpp-ffhq-ve-dummy-update""" ) model.to(A ) lowerCamelCase = 4 lowerCamelCase = 3 lowerCamelCase = (32, 32) lowerCamelCase = torch.ones((batch_size, num_channels) + sizes ).to(A ) lowerCamelCase = torch.tensor(batch_size * [1e-4] ).to(A ) with torch.no_grad(): lowerCamelCase = model(A , A ).sample lowerCamelCase = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off lowerCamelCase = torch.tensor([-0.0325, -0.0900, -0.0869, -0.0332, -0.0725, -0.0270, -0.0101, 0.0227, 0.0256] ) # fmt: on self.assertTrue(torch_all_close(A , A , rtol=1e-2 ) ) def __A ( self ) -> List[str]: '''simple docstring''' pass
66
1
"""simple docstring""" from __future__ import annotations import numpy as np def _A ( lowercase ): """simple docstring""" a , a =np.shape(lowercase ) if rows != columns: a =( '''\'table\' has to be of square shaped array but got a ''' f'''{rows}x{columns} array:\n{table}''' ) raise ValueError(lowercase ) a =np.zeros((rows, columns) ) a =np.zeros((rows, columns) ) for i in range(lowercase ): for j in range(lowercase ): a =sum(lower[i][k] * upper[k][j] for k in range(lowercase ) ) if upper[j][j] == 0: raise ArithmeticError('''No LU decomposition exists''' ) a =(table[i][j] - total) / upper[j][j] a =1 for j in range(lowercase , lowercase ): a =sum(lower[i][k] * upper[k][j] for k in range(lowercase ) ) a =table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
81
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def _A ( A__ ): """simple docstring""" __lowercase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(A__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowercase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowercase = [[0.0, 0.0], [0.0, 0.0]] __lowercase , __lowercase = matrix[1][1], matrix[0][0] __lowercase , __lowercase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(A__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(A__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowercase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowercase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowercase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowercase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowercase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowercase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowercase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowercase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowercase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowercase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowercase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowercase = array(A__ ) for i in range(3 ): for j in range(3 ): __lowercase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowercase = array(A__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(A__ ) # Calculate the inverse of the matrix return [[float(d(A__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
104
0
'''simple docstring''' from __future__ import annotations from math import gcd def __lowerCamelCase ( A__ , A__ = 2 , A__ = 1 , A__ = 3 , ) -> int | None: """simple docstring""" # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError('The input value cannot be less than 2' ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(A__ , A__ , A__ ) -> int: return (pow(A__ , 2 ) + step) % modulus for _ in range(A__ ): # These track the position within the cycle detection logic. UpperCamelCase = seed UpperCamelCase = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. UpperCamelCase = rand_fn(A__ , A__ , A__ ) UpperCamelCase = rand_fn(A__ , A__ , A__ ) UpperCamelCase = rand_fn(A__ , A__ , A__ ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. UpperCamelCase = gcd(hare - tortoise , A__ ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. UpperCamelCase = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse _lowerCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) _lowerCamelCase : Optional[Any] = parser.parse_args() _lowerCamelCase : str = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f'''{args.num} is probably prime''') else: _lowerCamelCase : Optional[Any] = args.num // divisor print(f'''{args.num} = {divisor} * {quotient}''')
249
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TextaTextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_tf, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _SCREAMING_SNAKE_CASE = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def A ( self : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] ): """simple docstring""" UpperCamelCase = TextaTextGenerationPipeline(model=UpperCamelCase__ , tokenizer=UpperCamelCase__ ) return generator, ["Something to write", "Something else"] def A ( self : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any] ): """simple docstring""" UpperCamelCase = generator('Something there' ) self.assertEqual(UpperCamelCase__ , [{'generated_text': ANY(UpperCamelCase__ )}] ) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]['generated_text'].startswith('Something there' ) ) UpperCamelCase = generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ [{'generated_text': ANY(UpperCamelCase__ )}, {'generated_text': ANY(UpperCamelCase__ )}], [{'generated_text': ANY(UpperCamelCase__ )}, {'generated_text': ANY(UpperCamelCase__ )}], ] , ) UpperCamelCase = generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ [{'generated_text': ANY(UpperCamelCase__ )}, {'generated_text': ANY(UpperCamelCase__ )}], [{'generated_text': ANY(UpperCamelCase__ )}, {'generated_text': ANY(UpperCamelCase__ )}], ] , ) with self.assertRaises(UpperCamelCase__ ): generator(4 ) @require_torch def A ( self : Dict ): """simple docstring""" UpperCamelCase = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='pt' ) # do_sample=False necessary for reproducibility UpperCamelCase = generator('Something there' , do_sample=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , [{'generated_text': ''}] ) UpperCamelCase = 3 UpperCamelCase = generator( 'Something there' , num_return_sequences=UpperCamelCase__ , num_beams=UpperCamelCase__ , ) UpperCamelCase = [ {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'}, {'generated_text': ''}, ] self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = generator('This is a test' , do_sample=UpperCamelCase__ , num_return_sequences=2 , return_tensors=UpperCamelCase__ ) self.assertEqual( UpperCamelCase__ , [ {'generated_token_ids': ANY(torch.Tensor )}, {'generated_token_ids': ANY(torch.Tensor )}, ] , ) UpperCamelCase = generator.model.config.eos_token_id UpperCamelCase = '<pad>' UpperCamelCase = generator( ['This is a test', 'This is a second test'] , do_sample=UpperCamelCase__ , num_return_sequences=2 , batch_size=2 , return_tensors=UpperCamelCase__ , ) self.assertEqual( UpperCamelCase__ , [ [ {'generated_token_ids': ANY(torch.Tensor )}, {'generated_token_ids': ANY(torch.Tensor )}, ], [ {'generated_token_ids': ANY(torch.Tensor )}, {'generated_token_ids': ANY(torch.Tensor )}, ], ] , ) @require_tf def A ( self : str ): """simple docstring""" UpperCamelCase = pipeline('text2text-generation' , model='patrickvonplaten/t5-tiny-random' , framework='tf' ) # do_sample=False necessary for reproducibility UpperCamelCase = generator('Something there' , do_sample=UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , [{'generated_text': ''}] )
249
1
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available __lowerCamelCase : Dict = logging.getLogger(__name__) @dataclass class A__ : _UpperCAmelCase :str _UpperCAmelCase :List[str] _UpperCAmelCase :Optional[List[str]] @dataclass class A__ : _UpperCAmelCase :List[int] _UpperCAmelCase :List[int] _UpperCAmelCase :Optional[List[int]] = None _UpperCAmelCase :Optional[List[int]] = None class A__ ( __snake_case ): _UpperCAmelCase :List[str] = 'train' _UpperCAmelCase :Dict = 'dev' _UpperCAmelCase :str = 'test' class A__ : @staticmethod def __UpperCamelCase( A_ , A_ ): '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCamelCase( A_ ): '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCamelCase( A_ , A_ , A_ , A_ , A_=False , A_="[CLS]" , A_=1 , A_="[SEP]" , A_=False , A_=False , A_=0 , A_=0 , A_=-100 , A_=0 , A_=True , ): '''simple docstring''' UpperCamelCase : Optional[Any] = {label: i for i, label in enumerate(A_ )} UpperCamelCase : List[str] = [] for ex_index, example in enumerate(A_ ): if ex_index % 1_0000 == 0: logger.info("Writing example %d of %d" , A_ , len(A_ ) ) UpperCamelCase : Optional[int] = [] UpperCamelCase : Optional[Any] = [] for word, label in zip(example.words , example.labels ): UpperCamelCase : str = tokenizer.tokenize(A_ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(A_ ) > 0: tokens.extend(A_ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(A_ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. UpperCamelCase : Tuple = tokenizer.num_special_tokens_to_add() if len(A_ ) > max_seq_length - special_tokens_count: UpperCamelCase : str = tokens[: (max_seq_length - special_tokens_count)] UpperCamelCase : str = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] UpperCamelCase : Optional[int] = [sequence_a_segment_id] * len(A_ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: UpperCamelCase : Optional[Any] = [cls_token] + tokens UpperCamelCase : Optional[Any] = [pad_token_label_id] + label_ids UpperCamelCase : Any = [cls_token_segment_id] + segment_ids UpperCamelCase : Any = tokenizer.convert_tokens_to_ids(A_ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. UpperCamelCase : List[str] = [1 if mask_padding_with_zero else 0] * len(A_ ) # Zero-pad up to the sequence length. UpperCamelCase : Tuple = max_seq_length - len(A_ ) if pad_on_left: UpperCamelCase : str = ([pad_token] * padding_length) + input_ids UpperCamelCase : Dict = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask UpperCamelCase : Optional[Any] = ([pad_token_segment_id] * padding_length) + segment_ids UpperCamelCase : int = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(A_ ) == max_seq_length assert len(A_ ) == max_seq_length assert len(A_ ) == max_seq_length assert len(A_ ) == max_seq_length if ex_index < 5: logger.info("*** Example ***" ) logger.info("guid: %s" , example.guid ) logger.info("tokens: %s" , " ".join([str(A_ ) for x in tokens] ) ) logger.info("input_ids: %s" , " ".join([str(A_ ) for x in input_ids] ) ) logger.info("input_mask: %s" , " ".join([str(A_ ) for x in input_mask] ) ) logger.info("segment_ids: %s" , " ".join([str(A_ ) for x in segment_ids] ) ) logger.info("label_ids: %s" , " ".join([str(A_ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: UpperCamelCase : Tuple = None features.append( InputFeatures( input_ids=A_ , attention_mask=A_ , token_type_ids=A_ , label_ids=A_ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( __snake_case ): _UpperCAmelCase :List[InputFeatures] _UpperCAmelCase :int = nn.CrossEntropyLoss().ignore_index def __init__( self , A_ , A_ , A_ , A_ , A_ , A_ = None , A_=False , A_ = Split.train , ): '''simple docstring''' UpperCamelCase : Union[str, Any] = os.path.join( A_ , "cached_{}_{}_{}".format(mode.value , tokenizer.__class__.__name__ , str(A_ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. UpperCamelCase : List[Any] = cached_features_file + ".lock" with FileLock(A_ ): if os.path.exists(A_ ) and not overwrite_cache: logger.info(F"""Loading features from cached file {cached_features_file}""" ) UpperCamelCase : Dict = torch.load(A_ ) else: logger.info(F"""Creating features from dataset file at {data_dir}""" ) UpperCamelCase : List[Any] = token_classification_task.read_examples_from_file(A_ , A_ ) # TODO clean up all this to leverage built-in features of tokenizers UpperCamelCase : int = token_classification_task.convert_examples_to_features( A_ , A_ , A_ , A_ , cls_token_at_end=bool(model_type in ["xlnet"] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["xlnet"] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=A_ , pad_on_left=bool(tokenizer.padding_side == "left" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(F"""Saving features into cached file {cached_features_file}""" ) torch.save(self.features , A_ ) def __len__( self ): '''simple docstring''' return len(self.features ) def __getitem__( self , A_ ): '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : _UpperCAmelCase :List[InputFeatures] _UpperCAmelCase :int = -1_0_0 def __init__( self , A_ , A_ , A_ , A_ , A_ , A_ = None , A_=False , A_ = Split.train , ): '''simple docstring''' UpperCamelCase : str = token_classification_task.read_examples_from_file(A_ , A_ ) # TODO clean up all this to leverage built-in features of tokenizers UpperCamelCase : str = token_classification_task.convert_examples_to_features( A_ , A_ , A_ , A_ , cls_token_at_end=bool(model_type in ["xlnet"] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["xlnet"] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=A_ , pad_on_left=bool(tokenizer.padding_side == "left" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: UpperCamelCase : Optional[int] = tf.data.Dataset.from_generator( A_ , ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa) , ( {"input_ids": tf.TensorShape([None] ), "attention_mask": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: UpperCamelCase : Optional[int] = tf.data.Dataset.from_generator( A_ , ({"input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa}, tf.intaa) , ( { "input_ids": tf.TensorShape([None] ), "attention_mask": tf.TensorShape([None] ), "token_type_ids": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : List[str] = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self ): '''simple docstring''' return len(self.features ) def __getitem__( self , A_ ): '''simple docstring''' return self.features[i]
52
def UpperCAmelCase_ ( _A = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = set(range(3 , _A , 2 ) ) primes.add(2 ) for p in range(3 , _A , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , _A , _A ) ) ) SCREAMING_SNAKE_CASE__ = [float(_A ) for n in range(limit + 1 )] for p in primes: for n in range(_A , limit + 1 , _A ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
314
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __A ( __SCREAMING_SNAKE_CASE ): lowerCAmelCase_ : Optional[int] = ["image_processor", "tokenizer"] lowerCAmelCase_ : List[Any] = "LayoutLMv2ImageProcessor" lowerCAmelCase_ : List[str] = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : str=None , **UpperCAmelCase_ : int ): if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _snake_case , ) lowerCAmelCase : List[str] = kwargs.pop('feature_extractor' ) lowerCAmelCase : Tuple = 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__(_snake_case , _snake_case ) def __call__( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] = None , UpperCAmelCase_ : List[str] = None , UpperCAmelCase_ : Dict = None , UpperCAmelCase_ : str = None , UpperCAmelCase_ : Tuple = True , UpperCAmelCase_ : List[Any] = False , UpperCAmelCase_ : str = None , UpperCAmelCase_ : Tuple = None , UpperCAmelCase_ : Optional[Any] = 0 , UpperCAmelCase_ : int = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : str = None , UpperCAmelCase_ : Optional[int] = False , UpperCAmelCase_ : Tuple = False , UpperCAmelCase_ : str = False , UpperCAmelCase_ : Union[str, Any] = False , UpperCAmelCase_ : Dict = True , UpperCAmelCase_ : Optional[Any] = None , **UpperCAmelCase_ : Any , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( 'You cannot provide bounding boxes ' 'if you initialized the image processor with apply_ocr set to True.' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.' ) # first, apply the image processor lowerCAmelCase : str = self.image_processor(images=_snake_case , return_tensors=_snake_case ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_snake_case , _snake_case ): lowerCAmelCase : List[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension) lowerCAmelCase : Optional[Any] = features["words"] lowerCAmelCase : Union[str, Any] = self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=_snake_case , add_special_tokens=_snake_case , padding=_snake_case , truncation=_snake_case , max_length=_snake_case , stride=_snake_case , pad_to_multiple_of=_snake_case , return_token_type_ids=_snake_case , return_attention_mask=_snake_case , return_overflowing_tokens=_snake_case , return_special_tokens_mask=_snake_case , return_offsets_mapping=_snake_case , return_length=_snake_case , verbose=_snake_case , return_tensors=_snake_case , **_snake_case , ) # add pixel values lowerCAmelCase : Tuple = features.pop('pixel_values' ) if return_overflowing_tokens is True: lowerCAmelCase : Optional[Any] = self.get_overflowing_images(_snake_case , encoded_inputs['overflow_to_sample_mapping'] ) lowerCAmelCase : Optional[Any] = images return encoded_inputs def lowercase__ ( self : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : str ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image lowerCAmelCase : Any = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_snake_case ) != len(_snake_case ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' f" {len(_snake_case )} and {len(_snake_case )}" ) return images_with_overflow def lowercase__ ( self : Any , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Tuple ): return self.tokenizer.batch_decode(*_snake_case , **_snake_case ) def lowercase__ ( self : Optional[int] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Optional[int] ): return self.tokenizer.decode(*_snake_case , **_snake_case ) @property def lowercase__ ( self : str ): return ["input_ids", "bbox", "attention_mask", "image"] @property def lowercase__ ( self : List[Any] ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _snake_case , ) return self.image_processor_class @property def lowercase__ ( self : str ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _snake_case , ) return self.image_processor
351
import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> List[Any]: '''simple docstring''' return x + 2 class __A ( unittest.TestCase ): def lowercase__ ( self : int ): lowerCAmelCase : List[str] = 'x = 3' lowerCAmelCase : Optional[Any] = {} lowerCAmelCase : Tuple = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) assert result == 3 self.assertDictEqual(UpperCAmelCase_ , {'x': 3} ) lowerCAmelCase : Dict = 'x = y' lowerCAmelCase : List[Any] = {'y': 5} lowerCAmelCase : Tuple = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase_ , {'x': 5, 'y': 5} ) def lowercase__ ( self : Optional[Any] ): lowerCAmelCase : Any = 'y = add_two(x)' lowerCAmelCase : int = {'x': 3} lowerCAmelCase : Optional[int] = evaluate(UpperCAmelCase_ , {'add_two': add_two} , state=UpperCAmelCase_ ) assert result == 5 self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'y': 5} ) # Won't work without the tool with CaptureStdout() as out: lowerCAmelCase : Tuple = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) assert result is None assert "tried to execute add_two" in out.out def lowercase__ ( self : Union[str, Any] ): lowerCAmelCase : Tuple = 'x = 3' lowerCAmelCase : List[Any] = {} lowerCAmelCase : Dict = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) assert result == 3 self.assertDictEqual(UpperCAmelCase_ , {'x': 3} ) def lowercase__ ( self : Optional[Any] ): lowerCAmelCase : List[Any] = 'test_dict = {\'x\': x, \'y\': add_two(x)}' lowerCAmelCase : Dict = {'x': 3} lowerCAmelCase : Tuple = evaluate(UpperCAmelCase_ , {'add_two': add_two} , state=UpperCAmelCase_ ) self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'y': 5} ) self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'test_dict': {'x': 3, 'y': 5}} ) def lowercase__ ( self : Any ): lowerCAmelCase : Union[str, Any] = 'x = 3\ny = 5' lowerCAmelCase : str = {} lowerCAmelCase : Optional[int] = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'y': 5} ) def lowercase__ ( self : Union[str, Any] ): lowerCAmelCase : Union[str, Any] = 'text = f\'This is x: {x}.\'' lowerCAmelCase : str = {'x': 3} lowerCAmelCase : int = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'text': 'This is x: 3.'} ) def lowercase__ ( self : Dict ): lowerCAmelCase : Optional[Any] = 'if x <= 3:\n y = 2\nelse:\n y = 5' lowerCAmelCase : Dict = {'x': 3} lowerCAmelCase : int = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'y': 2} ) lowerCAmelCase : Any = {'x': 8} lowerCAmelCase : Optional[int] = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase_ , {'x': 8, 'y': 5} ) def lowercase__ ( self : List[Any] ): lowerCAmelCase : int = 'test_list = [x, add_two(x)]' lowerCAmelCase : Optional[Any] = {'x': 3} lowerCAmelCase : Tuple = evaluate(UpperCAmelCase_ , {'add_two': add_two} , state=UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , [3, 5] ) self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'test_list': [3, 5]} ) def lowercase__ ( self : Optional[Any] ): lowerCAmelCase : int = 'y = x' lowerCAmelCase : Optional[int] = {'x': 3} lowerCAmelCase : Tuple = evaluate(UpperCAmelCase_ , {} , state=UpperCAmelCase_ ) assert result == 3 self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'y': 3} ) def lowercase__ ( self : List[str] ): lowerCAmelCase : Dict = 'test_list = [x, add_two(x)]\ntest_list[1]' lowerCAmelCase : List[str] = {'x': 3} lowerCAmelCase : List[str] = evaluate(UpperCAmelCase_ , {'add_two': add_two} , state=UpperCAmelCase_ ) assert result == 5 self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'test_list': [3, 5]} ) lowerCAmelCase : Optional[Any] = 'test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']' lowerCAmelCase : List[Any] = {'x': 3} lowerCAmelCase : Optional[Any] = evaluate(UpperCAmelCase_ , {'add_two': add_two} , state=UpperCAmelCase_ ) assert result == 5 self.assertDictEqual(UpperCAmelCase_ , {'x': 3, 'test_dict': {'x': 3, 'y': 5}} ) def lowercase__ ( self : int ): lowerCAmelCase : Any = 'x = 0\nfor i in range(3):\n x = i' lowerCAmelCase : str = {} lowerCAmelCase : Dict = evaluate(UpperCAmelCase_ , {'range': range} , state=UpperCAmelCase_ ) assert result == 2 self.assertDictEqual(UpperCAmelCase_ , {'x': 2, 'i': 2} )
323
0
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase_ : Tuple = logging.get_logger(__name__) lowerCAmelCase_ : List[str] = '▁' lowerCAmelCase_ : str = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } lowerCAmelCase_ : Union[str, Any] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } lowerCAmelCase_ : List[str] = { 'facebook/s2t-small-librispeech-asr': 10_24, } lowerCAmelCase_ : Any = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] lowerCAmelCase_ : List[str] = {'mustc': MUSTC_LANGS} class __SCREAMING_SNAKE_CASE (lowerCAmelCase__ ): """simple docstring""" __a =VOCAB_FILES_NAMES __a =PRETRAINED_VOCAB_FILES_MAP __a =MAX_MODEL_INPUT_SIZES __a =['''input_ids''', '''attention_mask'''] __a =[] def __init__( self : Optional[int] , __a : Tuple , __a : str , __a : Union[str, Any]="<s>" , __a : Any="</s>" , __a : Any="<pad>" , __a : List[str]="<unk>" , __a : Dict=False , __a : str=False , __a : Any=None , __a : Any=None , __a : int = None , **__a : str , ): _a = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , pad_token=__lowerCAmelCase , do_upper_case=__lowerCAmelCase , do_lower_case=__lowerCAmelCase , tgt_lang=__lowerCAmelCase , lang_codes=__lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCAmelCase , ) _a = do_upper_case _a = do_lower_case _a = load_json(__lowerCAmelCase ) _a = {v: k for k, v in self.encoder.items()} _a = spm_file _a = load_spm(__lowerCAmelCase , self.sp_model_kwargs ) if lang_codes is not None: _a = lang_codes _a = LANGUAGES[lang_codes] _a = [f'<lang:{lang}>' for lang in self.langs] _a = {lang: self.sp_model.PieceToId(f'<lang:{lang}>' ) for lang in self.langs} _a = self.lang_tokens _a = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: _a = {} @property def UpperCamelCase__ ( self : Tuple ): return len(self.encoder ) @property def UpperCamelCase__ ( self : Optional[int] ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase__ ( self : str , __a : Any ): _a = new_tgt_lang self.set_tgt_lang_special_tokens(__lowerCAmelCase ) def UpperCamelCase__ ( self : Optional[Any] , __a : Union[str, Any] ): _a = self.lang_code_to_id[tgt_lang] _a = [lang_code_id] def UpperCamelCase__ ( self : List[Any] , __a : List[str] ): return self.sp_model.encode(__lowerCAmelCase , out_type=__lowerCAmelCase ) def UpperCamelCase__ ( self : int , __a : Tuple ): return self.encoder.get(__lowerCAmelCase , self.encoder[self.unk_token] ) def UpperCamelCase__ ( self : Optional[Any] , __a : List[Any] ): return self.decoder.get(__lowerCAmelCase , self.unk_token ) def UpperCamelCase__ ( self : Tuple , __a : Union[str, Any] ): _a = [] _a = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: _a = self.sp_model.decode(__lowerCAmelCase ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " _a = [] else: current_sub_tokens.append(__lowerCAmelCase ) _a = self.sp_model.decode(__lowerCAmelCase ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase__ ( self : Dict , __a : Dict , __a : Union[str, Any]=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id] def UpperCamelCase__ ( self : Tuple , __a : int , __a : List[str] = None , __a : str = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCAmelCase , token_ids_a=__lowerCAmelCase , already_has_special_tokens=__lowerCAmelCase ) _a = [1] * len(self.prefix_tokens ) _a = [1] if token_ids_a is None: return prefix_ones + ([0] * len(__lowerCAmelCase )) + suffix_ones return prefix_ones + ([0] * len(__lowerCAmelCase )) + ([0] * len(__lowerCAmelCase )) + suffix_ones def UpperCamelCase__ ( self : int ): _a = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Any ): _a = self.__dict__.copy() _a = None return state def __setstate__( self : List[Any] , __a : Any ): _a = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _a = {} _a = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCamelCase__ ( self : str , __a : List[Any] , __a : List[Any] = None ): _a = Path(__lowerCAmelCase ) assert save_dir.is_dir(), f'{save_directory} should be a directory' _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) _a = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __lowerCAmelCase ) if os.path.abspath(self.spm_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __lowerCAmelCase ) elif not os.path.isfile(self.spm_file ): with open(__lowerCAmelCase , "wb" ) as fi: _a = self.sp_model.serialized_model_proto() fi.write(__lowerCAmelCase ) return (str(__lowerCAmelCase ), str(__lowerCAmelCase )) def _lowerCamelCase ( lowercase : str , lowercase : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: _a = sentencepiece.SentencePieceProcessor(**_A ) spm.Load(str(_A ) ) return spm def _lowerCamelCase ( lowercase : str ) -> Union[Dict, List]: with open(_A , "r" ) as f: return json.load(_A ) def _lowerCamelCase ( lowercase : Dict , lowercase : str ) -> None: with open(_A , "w" ) as f: json.dump(_A , _A , indent=2 )
63
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def snake_case__ ( _A: str ) -> str: '''simple docstring''' if not sentence: return "" lowerCAmelCase = dict(zip(_A , _A ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
272
0
'''simple docstring''' import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __SCREAMING_SNAKE_CASE :Dict = '''▁''' __SCREAMING_SNAKE_CASE :Union[str, Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class A_ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _lowerCamelCase : Tuple = BertGenerationTokenizer _lowerCamelCase : str = False _lowerCamelCase : str = True def lowercase ( self : Union[str, Any] ): super().setUp() _UpperCAmelCase = BertGenerationTokenizer(snake_case_ , keep_accents=snake_case_ ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase ( self : Optional[Any] ): _UpperCAmelCase = "<s>" _UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case_ ) , snake_case_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case_ ) , snake_case_ ) def lowercase ( self : Tuple ): _UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(snake_case_ ) , 1_0_0_2 ) def lowercase ( self : Optional[int] ): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def lowercase ( self : Tuple ): _UpperCAmelCase = BertGenerationTokenizer(snake_case_ , keep_accents=snake_case_ ) _UpperCAmelCase = tokenizer.tokenize("This is a test" ) self.assertListEqual(snake_case_ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case_ ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] , ) _UpperCAmelCase = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( snake_case_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) _UpperCAmelCase = tokenizer.convert_tokens_to_ids(snake_case_ ) self.assertListEqual( snake_case_ , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] , ) _UpperCAmelCase = tokenizer.convert_ids_to_tokens(snake_case_ ) self.assertListEqual( snake_case_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def lowercase ( self : List[str] ): return BertGenerationTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) @slow def lowercase ( self : Any ): _UpperCAmelCase = "Hello World!" _UpperCAmelCase = [1_8_5_3_6, 2_2_6_0, 1_0_1] self.assertListEqual(snake_case_ , self.big_tokenizer.encode(snake_case_ ) ) @slow def lowercase ( self : int ): _UpperCAmelCase = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) _UpperCAmelCase = [ 8_7_1, 4_1_9, 3_5_8, 9_4_6, 9_9_1, 2_5_2_1, 4_5_2, 3_5_8, 1_3_5_7, 3_8_7, 7_7_5_1, 3_5_3_6, 1_1_2, 9_8_5, 4_5_6, 1_2_6, 8_6_5, 9_3_8, 5_4_0_0, 5_7_3_4, 4_5_8, 1_3_6_8, 4_6_7, 7_8_6, 2_4_6_2, 5_2_4_6, 1_1_5_9, 6_3_3, 8_6_5, 4_5_1_9, 4_5_7, 5_8_2, 8_5_2, 2_5_5_7, 4_2_7, 9_1_6, 5_0_8, 4_0_5, 3_4_3_2_4, 4_9_7, 3_9_1, 4_0_8, 1_1_3_4_2, 1_2_4_4, 3_8_5, 1_0_0, 9_3_8, 9_8_5, 4_5_6, 5_7_4, 3_6_2, 1_2_5_9_7, 3_2_0_0, 3_1_2_9, 1_1_7_2, ] self.assertListEqual(snake_case_ , self.big_tokenizer.encode(snake_case_ ) ) @require_torch @slow def lowercase ( self : Union[str, Any] ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence _UpperCAmelCase = list(self.big_tokenizer.get_vocab().keys() )[:1_0] _UpperCAmelCase = " ".join(snake_case_ ) _UpperCAmelCase = self.big_tokenizer.encode_plus(snake_case_ , return_tensors="pt" , return_token_type_ids=snake_case_ ) _UpperCAmelCase = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=snake_case_ ) _UpperCAmelCase = BertGenerationConfig() _UpperCAmelCase = BertGenerationEncoder(snake_case_ ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**snake_case_ ) model(**snake_case_ ) @slow def lowercase ( self : Optional[Any] ): # fmt: off _UpperCAmelCase = {"input_ids": [[3_9_2_8_6, 4_5_8, 3_6_3_3_5, 2_0_0_1, 4_5_6, 1_3_0_7_3, 1_3_2_6_6, 4_5_5, 1_1_3, 7_7_4_6, 1_7_4_1, 1_1_1_5_7, 3_9_1, 1_3_0_7_3, 1_3_2_6_6, 4_5_5, 1_1_3, 3_9_6_7, 3_5_4_1_2, 1_1_3, 4_9_3_6, 1_0_9, 3_8_7_0, 2_3_7_7, 1_1_3, 3_0_0_8_4, 4_5_7_2_0, 4_5_8, 1_3_4, 1_7_4_9_6, 1_1_2, 5_0_3, 1_1_6_7_2, 1_1_3, 1_1_8, 1_1_2, 5_6_6_5, 1_3_3_4_7, 3_8_6_8_7, 1_1_2, 1_4_9_6, 3_1_3_8_9, 1_1_2, 3_2_6_8, 4_7_2_6_4, 1_3_4, 9_6_2, 1_1_2, 1_6_3_7_7, 8_0_3_5, 2_3_1_3_0, 4_3_0, 1_2_1_6_9, 1_5_5_1_8, 2_8_5_9_2, 4_5_8, 1_4_6, 4_1_6_9_7, 1_0_9, 3_9_1, 1_2_1_6_9, 1_5_5_1_8, 1_6_6_8_9, 4_5_8, 1_4_6, 4_1_3_5_8, 1_0_9, 4_5_2, 7_2_6, 4_0_3_4, 1_1_1, 7_6_3, 3_5_4_1_2, 5_0_8_2, 3_8_8, 1_9_0_3, 1_1_1, 9_0_5_1, 3_9_1, 2_8_7_0, 4_8_9_1_8, 1_9_0_0, 1_1_2_3, 5_5_0, 9_9_8, 1_1_2, 9_5_8_6, 1_5_9_8_5, 4_5_5, 3_9_1, 4_1_0, 2_2_9_5_5, 3_7_6_3_6, 1_1_4], [4_4_8, 1_7_4_9_6, 4_1_9, 3_6_6_3, 3_8_5, 7_6_3, 1_1_3, 2_7_5_3_3, 2_8_7_0, 3_2_8_3, 1_3_0_4_3, 1_6_3_9, 2_4_7_1_3, 5_2_3, 6_5_6, 2_4_0_1_3, 1_8_5_5_0, 2_5_2_1, 5_1_7, 2_7_0_1_4, 2_1_2_4_4, 4_2_0, 1_2_1_2, 1_4_6_5, 3_9_1, 9_2_7, 4_8_3_3, 3_8_8, 5_7_8, 1_1_7_8_6, 1_1_4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_8_4, 2_1_6_9, 7_6_8_7, 2_1_9_3_2, 1_8_1_4_6, 7_2_6, 3_6_3, 1_7_0_3_2, 3_3_9_1, 1_1_4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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], [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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case_ , model_name="google/bert_for_seq_generation_L-24_bbc_encoder" , revision="c817d1fd1be2ffa69431227a1fe320544943d4db" , )
358
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE :Dict = {'''vocab_file''': '''spiece.model'''} __SCREAMING_SNAKE_CASE :Any = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } __SCREAMING_SNAKE_CASE :int = { '''AI-Sweden/gpt-sw3-126m''': 2048, '''AI-Sweden/gpt-sw3-350m''': 2048, '''AI-Sweden/gpt-sw3-1.6b''': 2048, '''AI-Sweden/gpt-sw3-6.7b''': 2048, '''AI-Sweden/gpt-sw3-20b''': 2048, } class A_ ( lowerCAmelCase_ ): _lowerCamelCase : Any = VOCAB_FILES_NAMES _lowerCamelCase : Dict = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase : Optional[int] = ["""input_ids""", """attention_mask"""] def __init__( self : List[str] , snake_case_ : Any , snake_case_ : Optional[Any]=False , snake_case_ : int=False , snake_case_ : Any=False , snake_case_ : Optional[Any]=None , snake_case_ : List[Any]=None , snake_case_ : Tuple=None , snake_case_ : Any=None , snake_case_ : Optional[Dict[str, Any]] = None , **snake_case_ : Any , ): _UpperCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs _UpperCAmelCase = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) _UpperCAmelCase = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing _UpperCAmelCase = "<|endoftext|>" if eos_token is None else eos_token _UpperCAmelCase = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: _UpperCAmelCase = unk_token if pad_token is None else pad_token _UpperCAmelCase = eos_token if bos_token is None else bos_token else: _UpperCAmelCase = "<pad>" if pad_token is None else pad_token _UpperCAmelCase = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=snake_case_ , remove_space=snake_case_ , keep_accents=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) _UpperCAmelCase = do_lower_case _UpperCAmelCase = remove_space _UpperCAmelCase = keep_accents _UpperCAmelCase = vocab_file _UpperCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) # Used for whitespace normalization in input texts # fmt : off _UpperCAmelCase = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing _UpperCAmelCase = re.compile( f'[{"".join(map(snake_case_ , list(range(0 , 9 ) ) + list(range(1_1 , 3_2 ) ) + list(range(1_2_7 , 1_6_0 ) ) + [1_6_0, 1_7_3, 8_2_0_3] ) )}]' ) def __getstate__( self : Optional[Any] ): _UpperCAmelCase = self.__dict__.copy() _UpperCAmelCase = None return state def __setstate__( self : Any , snake_case_ : Union[str, Any] ): _UpperCAmelCase = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _UpperCAmelCase = {} _UpperCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def lowercase ( self : Dict ): return len(self.sp_model ) def lowercase ( self : Optional[Any] , snake_case_ : str ): _UpperCAmelCase = self.non_printing_characters_re.sub("" , snake_case_ ) # Normalize whitespaces _UpperCAmelCase = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization _UpperCAmelCase = unicodedata.normalize("NFC" , snake_case_ ) return text def lowercase ( self : List[str] , snake_case_ : str , **snake_case_ : List[str] ): _UpperCAmelCase = self.preprocess_text(snake_case_ ) return self.sp_model.encode(snake_case_ , out_type=snake_case_ ) def lowercase ( self : str , snake_case_ : str ): return self.sp_model.PieceToId(snake_case_ ) def lowercase ( self : int , snake_case_ : int ): return self.sp_model.IdToPiece(snake_case_ ) @staticmethod def lowercase ( snake_case_ : str ): return out_string def lowercase ( self : Any , snake_case_ : List[str] ): _UpperCAmelCase = [] _UpperCAmelCase = "" _UpperCAmelCase = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(snake_case_ ) + token _UpperCAmelCase = True _UpperCAmelCase = [] else: current_sub_tokens.append(snake_case_ ) _UpperCAmelCase = False out_string += self.sp_model.decode(snake_case_ ) return out_string def lowercase ( self : Optional[Any] ): _UpperCAmelCase = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowercase ( self : Optional[int] , snake_case_ : str , snake_case_ : Optional[str] = None ): if not os.path.isdir(snake_case_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return _UpperCAmelCase = os.path.join( snake_case_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , "wb" ) as fi: _UpperCAmelCase = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,) def lowercase ( self : Any , snake_case_ : Union[str, List[str]] , snake_case_ : Union[str, bool] = False ): if isinstance(snake_case_ , snake_case_ ): _UpperCAmelCase = self.preprocess_text(snake_case_ ) _UpperCAmelCase = self.sp_model.encode(snake_case_ ) else: _UpperCAmelCase = [self.preprocess_text(snake_case_ ) for t in text] _UpperCAmelCase = self.sp_model.encode(snake_case_ ) if return_tensors is True or return_tensors == "pt": _UpperCAmelCase = torch.tensor(snake_case_ ) return token_ids def lowercase ( self : Optional[Any] , snake_case_ : Union[int, List[int]] ): return self.sp_model.decode(snake_case_ ) def lowercase ( self : List[str] , snake_case_ : "Conversation" ): _UpperCAmelCase = [f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()] _UpperCAmelCase = ( f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(snake_case_ ) + f'{self.bos_token}Bot:' ) return self.encode(text=snake_case_ )
156
0
"""simple docstring""" import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCamelCase ( _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : Optional[int] = FunnelTokenizer _A : Tuple = FunnelTokenizerFast _A : Any = True _A : str = True def lowerCAmelCase_ ( self: Any ) -> List[Any]: super().setUp() snake_case_ :List[Any] = [ """<unk>""", """<cls>""", """<sep>""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] snake_case_ :List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def lowerCAmelCase_ ( self: Union[str, Any] , **snake_case: Optional[Any] ) -> Union[str, Any]: return FunnelTokenizer.from_pretrained(self.tmpdirname , **snake_case ) def lowerCAmelCase_ ( self: List[str] , **snake_case: int ) -> Optional[Any]: return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **snake_case ) def lowerCAmelCase_ ( self: List[Any] , snake_case: List[str] ) -> List[Any]: snake_case_ :List[str] = """UNwant\u00E9d,running""" snake_case_ :Optional[Any] = """unwanted, running""" return input_text, output_text def lowerCAmelCase_ ( self: Dict ) -> Tuple: snake_case_ :List[Any] = self.tokenizer_class(self.vocab_file ) snake_case_ :str = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(snake_case , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) , [7, 4, 5, 10, 8, 9] ) def lowerCAmelCase_ ( self: List[Any] ) -> Tuple: snake_case_ :Tuple = self.get_tokenizers(do_lower_case=snake_case ) for tokenizer in tokenizers: snake_case_ :List[str] = tokenizer("""UNwant\u00E9d,running""" ) snake_case_ :int = len(inputs["""input_ids"""] ) - 1 self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len ) snake_case_ :int = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" ) self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
66
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowerCamelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : str = StableDiffusionSAGPipeline _A : Optional[Any] = TEXT_TO_IMAGE_PARAMS _A : Any = TEXT_TO_IMAGE_BATCH_PARAMS _A : Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS _A : Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS _A : List[str] = False def lowerCAmelCase_ ( self: Optional[Any] ) -> str: torch.manual_seed(0 ) snake_case_ :Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) snake_case_ :Any = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="""scaled_linear""" , clip_sample=snake_case , set_alpha_to_one=snake_case , ) torch.manual_seed(0 ) snake_case_ :Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case_ :Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) snake_case_ :Tuple = CLIPTextModel(snake_case ) snake_case_ :str = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) snake_case_ :Dict = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowerCAmelCase_ ( self: List[str] , snake_case: Tuple , snake_case: List[str]=0 ) -> str: if str(snake_case ).startswith("""mps""" ): snake_case_ :Tuple = torch.manual_seed(snake_case ) else: snake_case_ :Optional[int] = torch.Generator(device=snake_case ).manual_seed(snake_case ) snake_case_ :Any = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def lowerCAmelCase_ ( self: Optional[int] ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self: int ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase_ ( self: int ) -> List[str]: snake_case_ :Any = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) snake_case_ :int = sag_pipe.to(snake_case ) sag_pipe.set_progress_bar_config(disable=snake_case ) snake_case_ :Union[str, Any] = """.""" snake_case_ :str = torch.manual_seed(0 ) snake_case_ :str = sag_pipe( [prompt] , generator=snake_case , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" ) snake_case_ :List[Any] = output.images snake_case_ :Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) snake_case_ :List[Any] = np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-2 def lowerCAmelCase_ ( self: Dict ) -> str: snake_case_ :Tuple = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) snake_case_ :Optional[int] = sag_pipe.to(snake_case ) sag_pipe.set_progress_bar_config(disable=snake_case ) snake_case_ :Tuple = """.""" snake_case_ :Union[str, Any] = torch.manual_seed(0 ) snake_case_ :Tuple = sag_pipe( [prompt] , generator=snake_case , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" ) snake_case_ :Optional[int] = output.images snake_case_ :Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) snake_case_ :Tuple = np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-2 def lowerCAmelCase_ ( self: List[str] ) -> List[str]: snake_case_ :Optional[int] = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) snake_case_ :int = sag_pipe.to(snake_case ) sag_pipe.set_progress_bar_config(disable=snake_case ) snake_case_ :Tuple = """.""" snake_case_ :Optional[int] = torch.manual_seed(0 ) snake_case_ :List[str] = sag_pipe( [prompt] , width=768 , height=512 , generator=snake_case , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) snake_case_ :Optional[Any] = output.images assert image.shape == (1, 512, 768, 3)
66
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase :List[str] = logging.get_logger(__name__) __UpperCAmelCase :int = { "google/mobilenet_v2_1.4_224": "https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json", "google/mobilenet_v2_1.0_224": "https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json", "google/mobilenet_v2_0.75_160": "https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json", "google/mobilenet_v2_0.35_96": "https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class a ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = "mobilenet_v2" def __init__( self : Optional[int] , snake_case : Tuple=3 , snake_case : List[str]=224 , snake_case : Dict=1.0 , snake_case : Tuple=8 , snake_case : Optional[Any]=8 , snake_case : Optional[Any]=6 , snake_case : List[str]=32 , snake_case : Optional[int]=True , snake_case : Dict=True , snake_case : Union[str, Any]="relu6" , snake_case : Tuple=True , snake_case : Tuple=0.8 , snake_case : Optional[int]=0.02 , snake_case : Any=0.001 , snake_case : int=255 , **snake_case : Any , ) -> int: super().__init__(**snake_case ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) __UpperCAmelCase : List[str] = num_channels __UpperCAmelCase : int = image_size __UpperCAmelCase : Dict = depth_multiplier __UpperCAmelCase : Tuple = depth_divisible_by __UpperCAmelCase : Optional[int] = min_depth __UpperCAmelCase : str = expand_ratio __UpperCAmelCase : Union[str, Any] = output_stride __UpperCAmelCase : Optional[int] = first_layer_is_expansion __UpperCAmelCase : Union[str, Any] = finegrained_output __UpperCAmelCase : Union[str, Any] = hidden_act __UpperCAmelCase : Optional[Any] = tf_padding __UpperCAmelCase : int = classifier_dropout_prob __UpperCAmelCase : Dict = initializer_range __UpperCAmelCase : str = layer_norm_eps __UpperCAmelCase : Union[str, Any] = semantic_loss_ignore_index class a ( _a ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = version.parse("1.11" ) @property def lowerCamelCase__ ( self : str ) -> Mapping[str, Mapping[int, str]]: return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def lowerCamelCase__ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def lowerCamelCase__ ( self : Any ) -> float: return 1E-4
350
'''simple docstring''' import requests __UpperCAmelCase :Union[str, Any] = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( _lowercase : str ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['''articles'''] , 1 ): print(F'{i}.) {article["title"]}' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
240
0
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( 'stable diffusion controlnet', '0.22.0', 'Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.', standard_warn=False, stacklevel=3, )
249
"""simple docstring""" def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : str = [1] __lowercase ,__lowercase ,__lowercase : List[str] = 0, 0, 0 __lowercase : List[str] = ugly_nums[ia] * 2 __lowercase : Any = ugly_nums[ia] * 3 __lowercase : str = ugly_nums[ia] * 5 for _ in range(1 , __UpperCamelCase ): __lowercase : Union[str, Any] = min(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) ugly_nums.append(__UpperCamelCase ) if next_num == next_a: ia += 1 __lowercase : List[str] = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 __lowercase : int = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 __lowercase : Optional[int] = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F"{ugly_numbers(2_0_0) = }")
249
1
'''simple docstring''' def UpperCamelCase_( ): '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def UpperCamelCase_( snake_case : List[Any] ): '''simple docstring''' snake_case_ = 1 snake_case_ = 2 while i * i <= n: snake_case_ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def UpperCamelCase_( ): '''simple docstring''' return next(i for i in triangle_number_generator() if count_divisors(__UpperCAmelCase ) > 5_0_0 ) if __name__ == "__main__": print(solution())
352
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _SCREAMING_SNAKE_CASE : Optional[int] = { "configuration_canine": ["CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP", "CanineConfig"], "tokenization_canine": ["CanineTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE : Dict = [ "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 _SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
92
0
'''simple docstring''' import numpy as np def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: __lowerCamelCase = int(np.ceil((x_end - xa) / h ) ) __lowerCamelCase = np.zeros((n + 1,) ) __lowerCamelCase = ya __lowerCamelCase = xa for k in range(UpperCamelCase__ ): __lowerCamelCase = f(UpperCamelCase__ , y[k] ) __lowerCamelCase = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __lowerCamelCase = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __lowerCamelCase = f(x + h , y[k] + h * ka ) __lowerCamelCase = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
67
'''simple docstring''' import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class UpperCamelCase__ ( tf.keras.layers.Layer ): """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : Dict[str, int] , lowerCamelCase_ : List[str] , lowerCamelCase_ : int = None , lowerCamelCase_ : int = None ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Any = pad_token_id SCREAMING_SNAKE_CASE : List[Any] = max_length SCREAMING_SNAKE_CASE : Optional[int] = vocab SCREAMING_SNAKE_CASE : List[Any] = merges SCREAMING_SNAKE_CASE : Tuple = BytePairTokenizer(lowerCamelCase_ , lowerCamelCase_ , sequence_length=lowerCamelCase_ ) @classmethod def lowerCamelCase_ ( cls : Any , lowerCamelCase_ : GPTaTokenizer , *lowerCamelCase_ : str , **lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [""" """.join(lowerCamelCase_ ) for m in tokenizer.bpe_ranks.keys()] SCREAMING_SNAKE_CASE : List[str] = tokenizer.get_vocab() return cls(lowerCamelCase_ , lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ ) @classmethod def lowerCamelCase_ ( cls : List[Any] , lowerCamelCase_ : Union[str, os.PathLike] , *lowerCamelCase_ : str , **lowerCamelCase_ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = GPTaTokenizer.from_pretrained(lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ ) return cls.from_tokenizer(lowerCamelCase_ , *lowerCamelCase_ , **lowerCamelCase_ ) @classmethod def lowerCamelCase_ ( cls : List[str] , lowerCamelCase_ : Tuple ): '''simple docstring''' return cls(**lowerCamelCase_ ) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : Dict , lowerCamelCase_ : int = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.tf_tokenizer(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tf.ones_like(lowerCamelCase_ ) if self.pad_token_id is not None: # pad the tokens up to max length SCREAMING_SNAKE_CASE : Optional[int] = max_length if max_length is not None else self.max_length if max_length is not None: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = pad_model_inputs( lowerCamelCase_ , max_seq_length=lowerCamelCase_ , pad_value=self.pad_token_id ) return {"attention_mask": attention_mask, "input_ids": input_ids}
323
0
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __A = logging.get_logger(__name__) __A = { "speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class snake_case ( UpperCAmelCase__ ): SCREAMING_SNAKE_CASE_ : Any = 'mctct' def __init__( self : Dict , UpperCamelCase__ : Any=8_0_6_5 , UpperCamelCase__ : Optional[int]=1_5_3_6 , UpperCamelCase__ : Union[str, Any]=3_6 , UpperCamelCase__ : List[Any]=6_1_4_4 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : int=3_8_4 , UpperCamelCase__ : Dict=9_2_0 , UpperCamelCase__ : Tuple=1e-5 , UpperCamelCase__ : Tuple=0.3 , UpperCamelCase__ : int="relu" , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : Dict=0.3 , UpperCamelCase__ : Dict=0.3 , UpperCamelCase__ : Optional[Any]=1 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : int=2 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : Optional[Any]=0.3 , UpperCamelCase__ : Tuple=1 , UpperCamelCase__ : Optional[Any]=(7,) , UpperCamelCase__ : Any=(3,) , UpperCamelCase__ : str=8_0 , UpperCamelCase__ : Tuple=1 , UpperCamelCase__ : int=None , UpperCamelCase__ : List[Any]="sum" , UpperCamelCase__ : int=False , **UpperCamelCase__ : List[str] , )-> Union[str, Any]: '''simple docstring''' super().__init__(**_SCREAMING_SNAKE_CASE , pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE) __lowerCAmelCase: int = vocab_size __lowerCAmelCase: str = hidden_size __lowerCAmelCase: str = num_hidden_layers __lowerCAmelCase: Dict = intermediate_size __lowerCAmelCase: List[str] = num_attention_heads __lowerCAmelCase: List[Any] = attention_head_dim __lowerCAmelCase: Union[str, Any] = max_position_embeddings __lowerCAmelCase: Optional[int] = layer_norm_eps __lowerCAmelCase: int = layerdrop __lowerCAmelCase: Tuple = hidden_act __lowerCAmelCase: Optional[int] = initializer_range __lowerCAmelCase: str = hidden_dropout_prob __lowerCAmelCase: Optional[int] = attention_probs_dropout_prob __lowerCAmelCase: Dict = pad_token_id __lowerCAmelCase: List[Any] = bos_token_id __lowerCAmelCase: List[str] = eos_token_id __lowerCAmelCase: Optional[int] = conv_glu_dim __lowerCAmelCase: Tuple = conv_dropout __lowerCAmelCase: Dict = num_conv_layers __lowerCAmelCase: Tuple = input_feat_per_channel __lowerCAmelCase: int = input_channels __lowerCAmelCase: str = conv_channels __lowerCAmelCase: Any = ctc_loss_reduction __lowerCAmelCase: Tuple = ctc_zero_infinity # prevents config testing fail with exporting to json __lowerCAmelCase: Optional[Any] = list(_SCREAMING_SNAKE_CASE) __lowerCAmelCase: str = list(_SCREAMING_SNAKE_CASE) if len(self.conv_kernel) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` " f"but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, " f"`config.num_conv_layers = {self.num_conv_layers}`.")
360
"""simple docstring""" from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> np.ndarray: __lowerCAmelCase: List[Any] = cva.getAffineTransform(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return cva.warpAffine(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , (rows, cols) ) if __name__ == "__main__": # read original image __A = cva.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value __A = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __A , __A = gray_img.shape # set different points to rotate image __A = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) __A = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) __A = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) __A = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list __A = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations __A = plt.figure(1) __A = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
108
0
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __snake_case = "▁" __snake_case = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class __snake_case ( lowerCAmelCase_ , unittest.TestCase ): __lowerCamelCase : str = BigBirdTokenizer __lowerCamelCase : List[str] = BigBirdTokenizerFast __lowerCamelCase : Any = True __lowerCamelCase : str = True def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' super().setUp() UpperCAmelCase : List[Any] =self.tokenizer_class(_snake_case , keep_accents=_snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase : Union[str, Any] ='''<s>''' UpperCAmelCase : List[str] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_snake_case ) , _snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_snake_case ) , _snake_case ) def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' UpperCAmelCase : List[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''[MASK]''' ) self.assertEqual(len(_snake_case ) , 1004 ) def UpperCAmelCase__ ( self ) -> Any: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' if not self.test_rust_tokenizer: return UpperCAmelCase : Union[str, Any] =self.get_tokenizer() UpperCAmelCase : Optional[Any] =self.get_rust_tokenizer() UpperCAmelCase : Optional[int] ='''I was born in 92000, and this is falsé.''' UpperCAmelCase : str =tokenizer.tokenize(_snake_case ) UpperCAmelCase : List[str] =rust_tokenizer.tokenize(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) UpperCAmelCase : Union[str, Any] =tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) UpperCAmelCase : Tuple =rust_tokenizer.encode(_snake_case , add_special_tokens=_snake_case ) self.assertListEqual(_snake_case , _snake_case ) UpperCAmelCase : List[str] =self.get_rust_tokenizer() UpperCAmelCase : Dict =tokenizer.encode(_snake_case ) UpperCAmelCase : str =rust_tokenizer.encode(_snake_case ) self.assertListEqual(_snake_case , _snake_case ) def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' UpperCAmelCase : Optional[Any] =BigBirdTokenizer(_snake_case , keep_accents=_snake_case ) UpperCAmelCase : List[str] =tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_snake_case , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_snake_case ) , [285, 46, 10, 170, 382] , ) UpperCAmelCase : List[str] =tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _snake_case , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) UpperCAmelCase : List[Any] =tokenizer.convert_tokens_to_ids(_snake_case ) self.assertListEqual( _snake_case , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) UpperCAmelCase : Union[str, Any] =tokenizer.convert_ids_to_tokens(_snake_case ) self.assertListEqual( _snake_case , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def UpperCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' return BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''' ) @slow def UpperCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase : int ='''Hello World!''' UpperCAmelCase : Dict =[65, 1_8536, 2260, 101, 66] self.assertListEqual(_snake_case , self.big_tokenizer.encode(_snake_case ) ) @slow def UpperCAmelCase__ ( self ) -> str: '''simple docstring''' UpperCAmelCase : Dict =( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) # fmt: off UpperCAmelCase : List[Any] =[65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 3_4324, 497, 391, 408, 1_1342, 1244, 385, 100, 938, 985, 456, 574, 362, 1_2597, 3200, 3129, 1172, 66] # noqa: E231 # fmt: on self.assertListEqual(_snake_case , self.big_tokenizer.encode(_snake_case ) ) @require_torch @slow def UpperCAmelCase__ ( self ) -> Dict: '''simple docstring''' import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence UpperCAmelCase : Tuple =list(self.big_tokenizer.get_vocab().keys() )[:10] UpperCAmelCase : str =''' '''.join(_snake_case ) UpperCAmelCase : List[str] =self.big_tokenizer.encode_plus(_snake_case , return_tensors='''pt''' , return_token_type_ids=_snake_case ) UpperCAmelCase : Dict =self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=_snake_case ) UpperCAmelCase : List[Any] =BigBirdConfig(attention_type='''original_full''' ) UpperCAmelCase : int =BigBirdModel(_snake_case ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_snake_case ) model(**_snake_case ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : List[str] =BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''' ) UpperCAmelCase : List[Any] =tokenizer.decode(tokenizer('''Paris is the [MASK].''' ).input_ids ) self.assertTrue(decoded_text == '''[CLS] Paris is the[MASK].[SEP]''' ) @slow def UpperCAmelCase__ ( self ) -> int: '''simple docstring''' UpperCAmelCase : Any ={'''input_ids''': [[65, 3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114, 66], [65, 448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 2_1932, 1_8146, 726, 363, 1_7032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_snake_case , model_name='''google/bigbird-roberta-base''' , revision='''215c99f1600e06f83acce68422f2035b2b5c3510''' , )
348
from ..utils import DummyObject, requires_backends class __lowerCAmelCase ( metaclass=lowerCAmelCase_ ): """simple docstring""" A__ : Tuple = ['''speech'''] def __init__( self : List[Any] , *_snake_case : str , **_snake_case : List[Any] ): requires_backends(self , ['''speech'''] ) class __lowerCAmelCase ( metaclass=lowerCAmelCase_ ): """simple docstring""" A__ : List[Any] = ['''speech'''] def __init__( self : List[str] , *_snake_case : List[Any] , **_snake_case : Dict ): requires_backends(self , ['''speech'''] )
156
0
"""simple docstring""" def __A (_SCREAMING_SNAKE_CASE ) ->bool: """simple docstring""" return str(_SCREAMING_SNAKE_CASE ) == str(_SCREAMING_SNAKE_CASE )[::-1] def __A (_SCREAMING_SNAKE_CASE ) ->int: """simple docstring""" return int(_SCREAMING_SNAKE_CASE ) + int(str(_SCREAMING_SNAKE_CASE )[::-1] ) def __A (_SCREAMING_SNAKE_CASE = 1_0000 ) ->int: """simple docstring""" lowerCAmelCase__ :Optional[Any] = [] for num in range(1 , _SCREAMING_SNAKE_CASE ): lowerCAmelCase__ :Union[str, Any] = 0 lowerCAmelCase__ :Optional[int] = num while iterations < 50: lowerCAmelCase__ :Dict = sum_reverse(_SCREAMING_SNAKE_CASE ) iterations += 1 if is_palindrome(_SCREAMING_SNAKE_CASE ): break else: lychrel_nums.append(_SCREAMING_SNAKE_CASE ) return len(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(F'''{solution() = }''')
254
"""simple docstring""" from pathlib import Path import fire def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" lowerCAmelCase__ :List[str] = Path(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Any = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): lowerCAmelCase__ :Union[str, Any] = [x.rstrip() for x in list(path.open().readlines() )][:n] lowerCAmelCase__ :Tuple = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open('w' ).write('\n'.join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
254
1
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex _lowercase : Any = logging.getLogger(__name__) class lowerCAmelCase__ : def __init__( self ): """simple docstring""" lowercase_ : Any = False def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if not self.initialized: lowercase_ : Union[str, Any] = RagRetriever( __snake_case , question_encoder_tokenizer=__snake_case , generator_tokenizer=__snake_case , index=__snake_case , init_retrieval=__snake_case , ) lowercase_ : int = True def _snake_case ( self ): """simple docstring""" self.retriever.index.init_index() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ , lowercase_ : Union[str, Any] = self.retriever._main_retrieve(__snake_case , __snake_case ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCamelCase_ ): def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): """simple docstring""" if index is not None and index.is_initialized() and len(__snake_case ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( __snake_case , question_encoder_tokenizer=__snake_case , generator_tokenizer=__snake_case , index=__snake_case , init_retrieval=__snake_case , ) lowercase_ : Any = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(__snake_case , __snake_case , __snake_case , __snake_case ) for worker in self.retrieval_workers ] ) def _snake_case ( self ): """simple docstring""" logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. lowercase_ : str = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] lowercase_ , lowercase_ : Optional[Any] = ray.get(random_worker.retrieve.remote(__snake_case , __snake_case ) ) else: lowercase_ , lowercase_ : Optional[Any] = self._main_retrieve(__snake_case , __snake_case ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__snake_case ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return super(__snake_case , cls ).get_tokenizers(__snake_case , __snake_case , **__snake_case ) @classmethod def _snake_case ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = kwargs.pop('''config''' , __snake_case ) or RagConfig.from_pretrained(__snake_case , **__snake_case ) lowercase_ : List[str] = RagTokenizer.from_pretrained(__snake_case , config=__snake_case ) lowercase_ : List[str] = rag_tokenizer.question_encoder lowercase_ : int = rag_tokenizer.generator if indexed_dataset is not None: lowercase_ : int = '''custom''' lowercase_ : str = CustomHFIndex(config.retrieval_vector_size , __snake_case ) else: lowercase_ : Optional[Any] = cls._build_index(__snake_case ) return cls( __snake_case , question_encoder_tokenizer=__snake_case , generator_tokenizer=__snake_case , retrieval_workers=__snake_case , index=__snake_case , )
93
from abc import ABC, abstractmethod from argparse import ArgumentParser class snake_case_ (lowerCamelCase_ ): @staticmethod @abstractmethod def lowerCamelCase__( __snake_case :ArgumentParser ) -> Dict: raise NotImplementedError() @abstractmethod def lowerCamelCase__( self :Union[str, Any] ) -> Dict: raise NotImplementedError()
240
0
from typing import TYPE_CHECKING from ..utils import _LazyModule __lowerCamelCase : List[Any] = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys __lowerCamelCase : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
356
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def SCREAMING_SNAKE_CASE ( snake_case_ : str ): snake_case__ : Optional[Any] = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "_float_tensor", "decoder.output_projection.weight", ] for k in ignore_keys: state_dict.pop(snake_case_ , snake_case_ ) def SCREAMING_SNAKE_CASE ( snake_case_ : int ): snake_case__, snake_case__ : Optional[Any] = emb.weight.shape snake_case__ : Tuple = nn.Linear(snake_case_ , snake_case_ , bias=snake_case_ ) snake_case__ : Optional[int] = emb.weight.data return lin_layer def SCREAMING_SNAKE_CASE ( snake_case_ : List[Any] , snake_case_ : Optional[Any]="facebook/mbart-large-en-ro" , snake_case_ : Optional[int]=False , snake_case_ : List[Any]=False ): snake_case__ : Tuple = torch.load(snake_case_ , map_location="cpu" )["model"] remove_ignore_keys_(snake_case_ ) snake_case__ : Any = state_dict["encoder.embed_tokens.weight"].shape[0] snake_case__ : List[Any] = MBartConfig.from_pretrained(snake_case_ , vocab_size=snake_case_ ) if mbart_aa and finetuned: snake_case__ : int = "relu" snake_case__ : List[str] = state_dict["decoder.embed_tokens.weight"] snake_case__ : Tuple = MBartForConditionalGeneration(snake_case_ ) model.model.load_state_dict(snake_case_ ) if finetuned: snake_case__ : Any = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": __lowerCamelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """fairseq_path""", type=str, help="""bart.large, bart.large.cnn or a path to a model.pt on local filesystem.""" ) parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--hf_config""", default="""facebook/mbart-large-cc25""", type=str, help="""Which huggingface architecture to use: mbart-large""", ) parser.add_argument("""--mbart_50""", action="""store_true""", help="""whether the model is mMART-50 checkpoint""") parser.add_argument("""--finetuned""", action="""store_true""", help="""whether the model is a fine-tuned checkpoint""") __lowerCamelCase : Optional[Any] = parser.parse_args() __lowerCamelCase : str = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
286
0
import sys import turtle def _a ( a :tuple[float, float] , a :tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def _a ( a :tuple[float, float] , a :tuple[float, float] , a :tuple[float, float] , a :int , ) -> None: my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(a , get_mid(a , a ) , get_mid(a , a ) , depth - 1 ) triangle(a , get_mid(a , a ) , get_mid(a , a ) , depth - 1 ) triangle(a , get_mid(a , a ) , get_mid(a , a ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) UpperCAmelCase__ = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") UpperCAmelCase__ = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
0
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
'''simple docstring''' from math import isqrt def A__ ( UpperCAmelCase_ ): return all(number % divisor != 0 for divisor in range(2 , isqrt(UpperCAmelCase_ ) + 1 ) ) def A__ ( UpperCAmelCase_ = 1_0**6 ): _UpperCamelCase : Optional[Any] = 0 _UpperCamelCase : int = 1 _UpperCamelCase : Optional[Any] = 7 while prime_candidate < max_prime: primes_count += is_prime(UpperCAmelCase_ ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"""{solution() = }""")
236
'''simple docstring''' class lowercase__ : def __init__( self : List[str] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Any ): '''simple docstring''' _UpperCamelCase : Dict = None _UpperCamelCase : List[Any] = None _UpperCamelCase : int = graph self._normalize_graph(lowerCamelCase__ ,lowerCamelCase__ ) _UpperCamelCase : List[str] = len(lowerCamelCase__ ) _UpperCamelCase : Tuple = None def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Any ): '''simple docstring''' if sources is int: _UpperCamelCase : Optional[int] = [sources] if sinks is int: _UpperCamelCase : Union[str, Any] = [sinks] if len(lowerCamelCase__ ) == 0 or len(lowerCamelCase__ ) == 0: return _UpperCamelCase : List[str] = sources[0] _UpperCamelCase : str = sinks[0] # make fake vertex if there are more # than one source or sink if len(lowerCamelCase__ ) > 1 or len(lowerCamelCase__ ) > 1: _UpperCamelCase : Dict = 0 for i in sources: max_input_flow += sum(self.graph[i] ) _UpperCamelCase : Tuple = len(self.graph ) + 1 for room in self.graph: room.insert(0 ,0 ) self.graph.insert(0 ,[0] * size ) for i in sources: _UpperCamelCase : List[Any] = max_input_flow _UpperCamelCase : Tuple = 0 _UpperCamelCase : int = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: _UpperCamelCase : Optional[int] = max_input_flow _UpperCamelCase : Optional[int] = size - 1 def UpperCamelCase_ ( self : List[str] ): '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('You need to set maximum flow algorithm before.' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCamelCase_ ( self : Any ,lowerCamelCase__ : Any ): '''simple docstring''' _UpperCamelCase : str = algorithm(self ) class lowercase__ : def __init__( self : List[str] ,lowerCamelCase__ : Optional[int] ): '''simple docstring''' _UpperCamelCase : Optional[Any] = flow_network _UpperCamelCase : List[str] = flow_network.verticesCount _UpperCamelCase : List[str] = flow_network.sourceIndex _UpperCamelCase : Any = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that _UpperCamelCase : List[Any] = flow_network.graph _UpperCamelCase : Any = False def UpperCamelCase_ ( self : str ): '''simple docstring''' if not self.executed: self._algorithm() _UpperCamelCase : Any = True def UpperCamelCase_ ( self : Any ): '''simple docstring''' pass class lowercase__ ( lowercase ): def __init__( self : Union[str, Any] ,lowerCamelCase__ : List[str] ): '''simple docstring''' super().__init__(lowerCamelCase__ ) # use this to save your result _UpperCamelCase : Tuple = -1 def UpperCamelCase_ ( self : Dict ): '''simple docstring''' if not self.executed: raise Exception('You should execute algorithm before using its result!' ) return self.maximum_flow class lowercase__ ( lowercase ): def __init__( self : Optional[Any] ,lowerCamelCase__ : Dict ): '''simple docstring''' super().__init__(lowerCamelCase__ ) _UpperCamelCase : Dict = [[0] * self.verticies_count for i in range(self.verticies_count )] _UpperCamelCase : Optional[Any] = [0] * self.verticies_count _UpperCamelCase : List[str] = [0] * self.verticies_count def UpperCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' _UpperCamelCase : Dict = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule _UpperCamelCase : List[str] = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list _UpperCamelCase : int = 0 while i < len(lowerCamelCase__ ): _UpperCamelCase : List[Any] = vertices_list[i] _UpperCamelCase : str = self.heights[vertex_index] self.process_vertex(lowerCamelCase__ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 ,vertices_list.pop(lowerCamelCase__ ) ) _UpperCamelCase : Dict = 0 else: i += 1 _UpperCamelCase : Optional[Any] = sum(self.preflow[self.source_index] ) def UpperCamelCase_ ( self : Union[str, Any] ,lowerCamelCase__ : Dict ): '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(lowerCamelCase__ ,lowerCamelCase__ ) self.relabel(lowerCamelCase__ ) def UpperCamelCase_ ( self : Tuple ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[str] ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = min( self.excesses[from_index] ,self.graph[from_index][to_index] - self.preflow[from_index][to_index] ,) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCamelCase_ ( self : List[str] ,lowerCamelCase__ : Optional[int] ): '''simple docstring''' _UpperCamelCase : Tuple = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): _UpperCamelCase : List[Any] = self.heights[to_index] if min_height is not None: _UpperCamelCase : Any = min_height + 1 if __name__ == "__main__": snake_case_ : List[str] = [0] snake_case_ : int = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] snake_case_ : int = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network snake_case_ : List[Any] = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate snake_case_ : Tuple = flow_network.find_maximum_flow() print(F"""maximum flow is {maximum_flow}""")
236
1
from scipy.stats import spearmanr import datasets a =""" The Spearman rank-order correlation coefficient is a measure of the relationship between two datasets. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Positive correlations imply that as data in dataset x increases, so does data in dataset y. Negative correlations imply that as x increases, y decreases. Correlations of -1 or +1 imply an exact monotonic relationship. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. """ a =""" Args: predictions (`List[float]`): Predicted labels, as returned by a model. references (`List[float]`): Ground truth labels. return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns only the spearmanr score. Defaults to `False`. Returns: spearmanr (`float`): Spearman correlation coefficient. p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input. Examples: Example 1: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4]) >>> print(results) {'spearmanr': -0.7} Example 2: >>> spearmanr_metric = datasets.load_metric(\"spearmanr\") >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], ... predictions=[10, 9, 2.5, 6, 4], ... return_pvalue=True) >>> print(results['spearmanr']) -0.7 >>> print(round(results['spearmanr_pvalue'], 2)) 0.19 """ a =r"""\ @book{kokoska2000crc, title={CRC standard probability and statistics tables and formulae}, author={Kokoska, Stephen and Zwillinger, Daniel}, year={2000}, publisher={Crc Press} } @article{2020SciPy-NMeth, author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and Haberland, Matt and Reddy, Tyler and Cournapeau, David and Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and Bright, Jonathan and {van der Walt}, St{\'e}fan J. and Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and Kern, Robert and Larson, Eric and Carey, C J and Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and Harris, Charles R. and Archibald, Anne M. and Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and {van Mulbregt}, Paul and {SciPy 1.0 Contributors}}, title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific Computing in Python}}, journal = {Nature Methods}, year = {2020}, volume = {17}, pages = {261--272}, adsurl = {https://rdcu.be/b08Wh}, doi = {10.1038/s41592-019-0686-2}, } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Tuple): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('float'), 'references': datasets.Value('float'), }) ,reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'] ,) def lowerCAmelCase ( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Dict ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False): __lowerCamelCase : Any = spearmanr(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
73
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase__ = { '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
108
0
"""simple docstring""" import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class snake_case__ ( snake_case_ ): def __get__( self , lowerCamelCase , lowerCamelCase=None ): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute" ) __a = "__cached_" + self.fget.__name__ __a = getattr(lowerCamelCase , lowerCamelCase , lowerCamelCase ) if cached is None: __a = self.fget(lowerCamelCase ) setattr(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return cached def _lowerCamelCase( a ): __a = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(F"invalid truth value {val!r}" ) def _lowerCamelCase( a ): if is_torch_fx_proxy(a ): return True if is_torch_available(): import torch if isinstance(a , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(a , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(a , (jnp.ndarray, Tracer) ): return True return isinstance(a , np.ndarray ) def _lowerCamelCase( a ): return isinstance(a , np.ndarray ) def _lowerCamelCase( a ): return _is_numpy(a ) def _lowerCamelCase( a ): import torch return isinstance(a , torch.Tensor ) def _lowerCamelCase( a ): return False if not is_torch_available() else _is_torch(a ) def _lowerCamelCase( a ): import torch return isinstance(a , torch.device ) def _lowerCamelCase( a ): return False if not is_torch_available() else _is_torch_device(a ) def _lowerCamelCase( a ): import torch if isinstance(a , a ): if hasattr(a , a ): __a = getattr(a , a ) else: return False return isinstance(a , torch.dtype ) def _lowerCamelCase( a ): return False if not is_torch_available() else _is_torch_dtype(a ) def _lowerCamelCase( a ): import tensorflow as tf return isinstance(a , tf.Tensor ) def _lowerCamelCase( a ): return False if not is_tf_available() else _is_tensorflow(a ) def _lowerCamelCase( a ): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(a , "is_symbolic_tensor" ): return tf.is_symbolic_tensor(a ) return type(a ) == tf.Tensor def _lowerCamelCase( a ): return False if not is_tf_available() else _is_tf_symbolic_tensor(a ) def _lowerCamelCase( a ): import jax.numpy as jnp # noqa: F811 return isinstance(a , jnp.ndarray ) def _lowerCamelCase( a ): return False if not is_flax_available() else _is_jax(a ) def _lowerCamelCase( a ): if isinstance(a , (dict, UserDict) ): return {k: to_py_obj(a ) for k, v in obj.items()} elif isinstance(a , (list, tuple) ): return [to_py_obj(a ) for o in obj] elif is_tf_tensor(a ): return obj.numpy().tolist() elif is_torch_tensor(a ): return obj.detach().cpu().tolist() elif is_jax_tensor(a ): return np.asarray(a ).tolist() elif isinstance(a , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def _lowerCamelCase( a ): if isinstance(a , (dict, UserDict) ): return {k: to_numpy(a ) for k, v in obj.items()} elif isinstance(a , (list, tuple) ): return np.array(a ) elif is_tf_tensor(a ): return obj.numpy() elif is_torch_tensor(a ): return obj.detach().cpu().numpy() elif is_jax_tensor(a ): return np.asarray(a ) else: return obj class snake_case__ ( snake_case_ ): def a__ ( self ): __a = fields(self ) # Safety and consistency checks if not len(lowerCamelCase ): raise ValueError(F"{self.__class__.__name__} has no fields." ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(F"{self.__class__.__name__} should not have more than one required field." ) __a = getattr(self , class_fields[0].name ) __a = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(lowerCamelCase ): if isinstance(lowerCamelCase , lowerCamelCase ): __a = first_field.items() __a = True else: try: __a = iter(lowerCamelCase ) __a = True except TypeError: __a = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(lowerCamelCase ): if ( not isinstance(lowerCamelCase , (list, tuple) ) or not len(lowerCamelCase ) == 2 or not isinstance(element[0] , lowerCamelCase ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute __a = first_field else: # If we have a mixed iterator, raise an error raise ValueError( F"Cannot set key/value for {element}. It needs to be a tuple (key, value)." ) break setattr(self , element[0] , element[1] ) if element[1] is not None: __a = element[1] elif first_field is not None: __a = first_field else: for field in class_fields: __a = getattr(self , field.name ) if v is not None: __a = v def __delitem__( self , *lowerCamelCase , **lowerCamelCase ): raise Exception(F"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance." ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): raise Exception(F"You cannot use ``setdefault`` on a {self.__class__.__name__} instance." ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): raise Exception(F"You cannot use ``pop`` on a {self.__class__.__name__} instance." ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): raise Exception(F"You cannot use ``update`` on a {self.__class__.__name__} instance." ) def __getitem__( self , lowerCamelCase ): if isinstance(lowerCamelCase , lowerCamelCase ): __a = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self , lowerCamelCase , lowerCamelCase ): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(lowerCamelCase , lowerCamelCase ) super().__setattr__(lowerCamelCase , lowerCamelCase ) def __setitem__( self , lowerCamelCase , lowerCamelCase ): # Will raise a KeyException if needed super().__setitem__(lowerCamelCase , lowerCamelCase ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(lowerCamelCase , lowerCamelCase ) def a__ ( self ): return tuple(self[k] for k in self.keys() ) class snake_case__ ( snake_case_, snake_case_ ): @classmethod def a__ ( cls , lowerCamelCase ): raise ValueError( F"{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}" ) class snake_case__ ( snake_case_ ): _snake_case : Union[str, Any] = """longest""" _snake_case : Dict = """max_length""" _snake_case : Dict = """do_not_pad""" class snake_case__ ( snake_case_ ): _snake_case : Union[str, Any] = """pt""" _snake_case : Union[str, Any] = """tf""" _snake_case : List[str] = """np""" _snake_case : Dict = """jax""" class snake_case__ : def __init__( self , lowerCamelCase ): __a = context_managers __a = ExitStack() def __enter__( self ): for context_manager in self.context_managers: self.stack.enter_context(lowerCamelCase ) def __exit__( self , *lowerCamelCase , **lowerCamelCase ): self.stack.__exit__(*lowerCamelCase , **lowerCamelCase ) def _lowerCamelCase( a ): __a = infer_framework(a ) if framework == "tf": __a = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": __a = inspect.signature(model_class.forward ) # PyTorch models else: __a = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def _lowerCamelCase( a ): __a = model_class.__name__ __a = infer_framework(a ) if framework == "tf": __a = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": __a = inspect.signature(model_class.forward ) # PyTorch models else: __a = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def _lowerCamelCase( a , a = "" , a = "." ): def _flatten_dict(a , a="" , a="." ): for k, v in d.items(): __a = str(a ) + delimiter + str(a ) if parent_key else k if v and isinstance(a , a ): yield from flatten_dict(a , a , delimiter=a ).items() else: yield key, v return dict(_flatten_dict(a , a , a ) ) @contextmanager def _lowerCamelCase( a , a = False ): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def _lowerCamelCase( a , a=None ): if is_numpy_array(a ): return np.transpose(a , axes=a ) elif is_torch_tensor(a ): return array.T if axes is None else array.permute(*a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.transpose(a , perm=a ) elif is_jax_tensor(a ): return jnp.transpose(a , axes=a ) else: raise ValueError(F"Type not supported for transpose: {type(a )}." ) def _lowerCamelCase( a , a ): if is_numpy_array(a ): return np.reshape(a , a ) elif is_torch_tensor(a ): return array.reshape(*a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.reshape(a , a ) elif is_jax_tensor(a ): return jnp.reshape(a , a ) else: raise ValueError(F"Type not supported for reshape: {type(a )}." ) def _lowerCamelCase( a , a=None ): if is_numpy_array(a ): return np.squeeze(a , axis=a ) elif is_torch_tensor(a ): return array.squeeze() if axis is None else array.squeeze(dim=a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.squeeze(a , axis=a ) elif is_jax_tensor(a ): return jnp.squeeze(a , axis=a ) else: raise ValueError(F"Type not supported for squeeze: {type(a )}." ) def _lowerCamelCase( a , a ): if is_numpy_array(a ): return np.expand_dims(a , a ) elif is_torch_tensor(a ): return array.unsqueeze(dim=a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.expand_dims(a , axis=a ) elif is_jax_tensor(a ): return jnp.expand_dims(a , axis=a ) else: raise ValueError(F"Type not supported for expand_dims: {type(a )}." ) def _lowerCamelCase( a ): if is_numpy_array(a ): return np.size(a ) elif is_torch_tensor(a ): return array.numel() elif is_tf_tensor(a ): import tensorflow as tf return tf.size(a ) elif is_jax_tensor(a ): return array.size else: raise ValueError(F"Type not supported for expand_dims: {type(a )}." ) def _lowerCamelCase( a , a ): for key, value in auto_map.items(): if isinstance(a , (tuple, list) ): __a = [F"{repo_id}--{v}" if (v is not None and "--" not in v) else v for v in value] elif value is not None and "--" not in value: __a = F"{repo_id}--{value}" return auto_map def _lowerCamelCase( a ): for base_class in inspect.getmro(a ): __a = base_class.__module__ __a = base_class.__name__ if module.startswith("tensorflow" ) or module.startswith("keras" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch" ) or name == "PreTrainedModel": return "pt" elif module.startswith("flax" ) or module.startswith("jax" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(F"Could not infer framework from class {model_class}." )
268
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( snake_case_ ): _snake_case : UNetaDModel _snake_case : KarrasVeScheduler def __init__( self , lowerCamelCase , lowerCamelCase ): super().__init__() self.register_modules(unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self , lowerCamelCase = 1 , lowerCamelCase = 50 , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , **lowerCamelCase , ): __a = self.unet.config.sample_size __a = (batch_size, 3, img_size, img_size) __a = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) __a = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(lowerCamelCase ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper __a = self.scheduler.schedule[t] __a = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat __a , __a = self.scheduler.add_noise_to_input(lowerCamelCase , lowerCamelCase , generator=lowerCamelCase ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. __a = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev __a = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. __a = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample __a = self.scheduler.step_correct( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , step_output.prev_sample , step_output["derivative"] , ) __a = step_output.prev_sample __a = (sample / 2 + 0.5).clamp(0 , 1 ) __a = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
268
1
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : Union[str, Any] = ["image_processor", "tokenizer"] _SCREAMING_SNAKE_CASE : Tuple = "ViltImageProcessor" _SCREAMING_SNAKE_CASE : List[str] = ("BertTokenizer", "BertTokenizerFast") def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Optional[int] = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __UpperCAmelCase , ) __UpperCAmelCase : Optional[Any] = kwargs.pop("""feature_extractor""" ) __UpperCAmelCase : Tuple = 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__(__UpperCAmelCase , __UpperCAmelCase ) __UpperCAmelCase : str = self.image_processor def __call__( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = True , __UpperCAmelCase = False , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = 0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = False , __UpperCAmelCase = True , __UpperCAmelCase = None , **__UpperCAmelCase , ) -> BatchEncoding: '''simple docstring''' __UpperCAmelCase : Tuple = self.tokenizer( text=__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , max_length=__UpperCAmelCase , stride=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , return_overflowing_tokens=__UpperCAmelCase , return_special_tokens_mask=__UpperCAmelCase , return_offsets_mapping=__UpperCAmelCase , return_length=__UpperCAmelCase , verbose=__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase , ) # add pixel_values + pixel_mask __UpperCAmelCase : Dict = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase ) encoding.update(__UpperCAmelCase ) return encoding def __A ( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Any: '''simple docstring''' return self.tokenizer.batch_decode(*__UpperCAmelCase , **__UpperCAmelCase ) def __A ( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' return self.tokenizer.decode(*__UpperCAmelCase , **__UpperCAmelCase ) @property def __A ( self ) -> List[str]: '''simple docstring''' __UpperCAmelCase : List[str] = self.tokenizer.model_input_names __UpperCAmelCase : Optional[int] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __A ( self ) -> Optional[int]: '''simple docstring''' warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __UpperCAmelCase , ) return self.image_processor_class @property def __A ( self ) -> Dict: '''simple docstring''' warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __UpperCAmelCase , ) return self.image_processor
254
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer _UpperCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _UpperCamelCase = { '''vocab_file''': { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt''', }, '''tokenizer_file''': { '''unc-nlp/lxmert-base-uncased''': ( '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json''' ), }, } _UpperCamelCase = { '''unc-nlp/lxmert-base-uncased''': 512, } _UpperCamelCase = { '''unc-nlp/lxmert-base-uncased''': {'''do_lower_case''': True}, } class _A ( __SCREAMING_SNAKE_CASE ): _SCREAMING_SNAKE_CASE : List[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION _SCREAMING_SNAKE_CASE : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : List[str] = LxmertTokenizer def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=True , __UpperCAmelCase="[UNK]" , __UpperCAmelCase="[SEP]" , __UpperCAmelCase="[PAD]" , __UpperCAmelCase="[CLS]" , __UpperCAmelCase="[MASK]" , __UpperCAmelCase=True , __UpperCAmelCase=None , **__UpperCAmelCase , ) -> Dict: '''simple docstring''' super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) __UpperCAmelCase : Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __UpperCAmelCase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __UpperCAmelCase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __UpperCAmelCase ) != tokenize_chinese_chars ): __UpperCAmelCase : Any = getattr(__UpperCAmelCase , normalizer_state.pop("""type""" ) ) __UpperCAmelCase : Optional[Any] = do_lower_case __UpperCAmelCase : Optional[Any] = strip_accents __UpperCAmelCase : str = tokenize_chinese_chars __UpperCAmelCase : str = normalizer_class(**__UpperCAmelCase ) __UpperCAmelCase : Union[str, Any] = do_lower_case def __A ( self , __UpperCAmelCase , __UpperCAmelCase=None ) -> Any: '''simple docstring''' __UpperCAmelCase : Any = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> List[int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = [self.sep_token_id] __UpperCAmelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __A ( self , __UpperCAmelCase , __UpperCAmelCase = None ) -> Tuple[str]: '''simple docstring''' __UpperCAmelCase : Tuple = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
254
1
def lowerCAmelCase( __lowerCamelCase ): __a = [] __a = set({'(', '[', '{'} ) __a = set({')', ']', '}'} ) __a = {'{': '}', '[': ']', '(': ')'} for i in range(len(__lowerCamelCase ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(__lowerCamelCase ) == 0 or (len(__lowerCamelCase ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(__lowerCamelCase ) == 0 def lowerCAmelCase( ): __a = input('Enter sequence of brackets: ' ) if is_balanced(__lowerCamelCase ): print(__lowerCamelCase , 'is balanced' ) else: print(__lowerCamelCase , 'is not balanced' ) if __name__ == "__main__": main()
197
from ..utils import DummyObject, requires_backends class a__ ( metaclass=__snake_case ): A__ : List[Any] = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> Any: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> Union[str, Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> List[str]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class a__ ( metaclass=__snake_case ): A__ : Union[str, Any] = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> int: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> int: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> Dict: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class a__ ( metaclass=__snake_case ): A__ : Dict = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> Union[str, Any]: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> Any: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> int: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class a__ ( metaclass=__snake_case ): A__ : Union[str, Any] = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> Optional[Any]: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> int: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> Union[str, Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class a__ ( metaclass=__snake_case ): A__ : Dict = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> Optional[int]: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> Any: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> str: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class a__ ( metaclass=__snake_case ): A__ : Tuple = ['torch', 'transformers', 'onnx'] def __init__( self , *UpperCAmelCase , **UpperCAmelCase ) -> int: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> List[str]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls , *UpperCAmelCase , **UpperCAmelCase ) -> Any: requires_backends(cls , ['torch', 'transformers', 'onnx'] )
197
1
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): UpperCamelCase = True from torch.cuda.amp import autocast UpperCamelCase = logging.getLogger(__name__) def lowercase_ ( _lowerCamelCase : Any=None , _lowerCamelCase : Tuple=None): return field(default_factory=lambda: default , metadata=_lowerCamelCase) @dataclass class snake_case_ : __A : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __A : Optional[str] = field( default=__A ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,) __A : Optional[bool] = field( default=__A ,metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) __A : Optional[float] = field( default=0.1 ,metadata={"help": "The dropout ratio for the attention probabilities."} ) __A : Optional[float] = field( default=0.1 ,metadata={"help": "The dropout ratio for activations inside the fully connected layer."} ) __A : Optional[float] = field( default=0.1 ,metadata={ "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler." } ,) __A : Optional[float] = field( default=0.1 ,metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."} ,) __A : Optional[float] = field( default=0.05 ,metadata={ "help": ( "Propability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." ) } ,) __A : Optional[float] = field(default=0.0 ,metadata={"help": "The LayerDrop probability."} ) @dataclass class snake_case_ : __A : Optional[str] = field( default=__A ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __A : Optional[str] = field( default="train+validation" ,metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } ,) __A : bool = field( default=__A ,metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __A : Optional[int] = field( default=__A ,metadata={"help": "The number of processes to use for the preprocessing."} ,) __A : Optional[int] = field( default=__A ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } ,) __A : Optional[int] = field( default=__A ,metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." ) } ,) __A : List[str] = list_field( default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"] ,metadata={"help": "A list of characters to remove from the transcripts."} ,) @dataclass class snake_case_ : __A : WavaVecaProcessor __A : Union[bool, str] = True __A : Optional[int] = None __A : Optional[int] = None __A : Optional[int] = None __A : Optional[int] = None def __call__( self : Tuple , lowercase_ : List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Dict[str, torch.Tensor]: # split inputs and labels since they have to be of different lenghts and need # different padding methods lowercase__ : Union[str, Any] = [{"input_values": feature["input_values"]} for feature in features] lowercase__ : Optional[int] = [{"input_ids": feature["labels"]} for feature in features] lowercase__ : str = self.processor.pad( lowercase_ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) lowercase__ : str = self.processor.pad( labels=lowercase_ , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors="pt" , ) # replace padding with -100 to ignore loss correctly lowercase__ : Tuple = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1 ) , -1_00 ) lowercase__ : str = labels return batch class snake_case_ ( __A ): def __UpperCamelCase ( self : Optional[int] , lowercase_ : nn.Module , lowercase_ : Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor: model.train() lowercase__ : Optional[int] = self._prepare_inputs(lowercase_ ) if self.use_amp: with autocast(): lowercase__ : Optional[Any] = self.compute_loss(lowercase_ , lowercase_ ) else: lowercase__ : int = self.compute_loss(lowercase_ , lowercase_ ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": lowercase__ : Optional[Any] = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": lowercase__ : List[str] = loss.sum() / (inputs["labels"] >= 0).sum() else: raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: lowercase__ : Union[str, Any] = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(lowercase_ ).backward() elif self.use_apex: with amp.scale_loss(lowercase_ , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(lowercase_ ) else: loss.backward() return loss.detach() def lowercase_ ( ): # 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__ : Optional[int] = 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. lowercase__ , lowercase__ , lowercase__ : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: lowercase__ , lowercase__ , lowercase__ : List[str] = parser.parse_args_into_dataclasses() # Detecting last checkpoint. lowercase__ : Optional[int] = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: lowercase__ : 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() logger.info("Training/evaluation parameters %s" , _lowerCamelCase) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: lowercase__ : Any = datasets.load_dataset( "common_voice" , data_args.dataset_config_name , split=data_args.train_split_name) lowercase__ : str = datasets.load_dataset("common_voice" , data_args.dataset_config_name , split="test") # Create and save tokenizer lowercase__ : Optional[Any] = f'''[{"".join(data_args.chars_to_ignore)}]''' def remove_special_characters(_lowerCamelCase : Dict): lowercase__ : str = re.sub(_lowerCamelCase , "" , batch["sentence"]).lower() + " " return batch lowercase__ : Union[str, Any] = train_dataset.map(_lowerCamelCase , remove_columns=["sentence"]) lowercase__ : List[str] = eval_dataset.map(_lowerCamelCase , remove_columns=["sentence"]) def extract_all_chars(_lowerCamelCase : List[str]): lowercase__ : Optional[int] = " ".join(batch["text"]) lowercase__ : Optional[int] = list(set(_lowerCamelCase)) return {"vocab": [vocab], "all_text": [all_text]} lowercase__ : Any = train_dataset.map( _lowerCamelCase , batched=_lowerCamelCase , batch_size=-1 , keep_in_memory=_lowerCamelCase , remove_columns=train_dataset.column_names , ) lowercase__ : Optional[Any] = train_dataset.map( _lowerCamelCase , batched=_lowerCamelCase , batch_size=-1 , keep_in_memory=_lowerCamelCase , remove_columns=eval_dataset.column_names , ) lowercase__ : str = list(set(vocab_train["vocab"][0]) | set(vocab_test["vocab"][0])) lowercase__ : Optional[Any] = {v: k for k, v in enumerate(_lowerCamelCase)} lowercase__ : Optional[int] = vocab_dict[" "] del vocab_dict[" "] lowercase__ : str = len(_lowerCamelCase) lowercase__ : int = len(_lowerCamelCase) with open("vocab.json" , "w") as vocab_file: json.dump(_lowerCamelCase , _lowerCamelCase) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowercase__ : List[str] = WavaVecaCTCTokenizer( "vocab.json" , unk_token="[UNK]" , pad_token="[PAD]" , word_delimiter_token="|" , ) lowercase__ : List[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0.0 , do_normalize=_lowerCamelCase , return_attention_mask=_lowerCamelCase) lowercase__ : Dict = WavaVecaProcessor(feature_extractor=_lowerCamelCase , tokenizer=_lowerCamelCase) lowercase__ : List[str] = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction="mean" , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer) , ) if data_args.max_train_samples is not None: lowercase__ : Union[str, Any] = min(len(_lowerCamelCase) , data_args.max_train_samples) lowercase__ : Union[str, Any] = train_dataset.select(range(_lowerCamelCase)) if data_args.max_val_samples is not None: lowercase__ : List[Any] = eval_dataset.select(range(data_args.max_val_samples)) lowercase__ : Optional[Any] = torchaudio.transforms.Resample(4_8000 , 1_6000) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(_lowerCamelCase : int): lowercase__ , lowercase__ : List[str] = torchaudio.load(batch["path"]) lowercase__ : Optional[Any] = resampler(_lowerCamelCase).squeeze().numpy() lowercase__ : List[Any] = 1_6000 lowercase__ : Optional[int] = batch["text"] return batch lowercase__ : Union[str, Any] = train_dataset.map( _lowerCamelCase , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) lowercase__ : str = eval_dataset.map( _lowerCamelCase , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(_lowerCamelCase : int): # check that all files have the correct sampling rate assert ( len(set(batch["sampling_rate"])) == 1 ), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.''' lowercase__ : Union[str, Any] = processor( audio=batch["speech"] , text=batch["target_text"] , sampling_rate=batch["sampling_rate"][0]) batch.update(_lowerCamelCase) return batch lowercase__ : str = train_dataset.map( _lowerCamelCase , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowerCamelCase , num_proc=data_args.preprocessing_num_workers , ) lowercase__ : Tuple = eval_dataset.map( _lowerCamelCase , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_lowerCamelCase , num_proc=data_args.preprocessing_num_workers , ) # Metric lowercase__ : str = datasets.load_metric("wer") def compute_metrics(_lowerCamelCase : Optional[Any]): lowercase__ : str = pred.predictions lowercase__ : str = np.argmax(_lowerCamelCase , axis=-1) lowercase__ : int = processor.tokenizer.pad_token_id lowercase__ : str = processor.batch_decode(_lowerCamelCase) # we do not want to group tokens when computing the metrics lowercase__ : Optional[Any] = processor.batch_decode(pred.label_ids , group_tokens=_lowerCamelCase) lowercase__ : Tuple = wer_metric.compute(predictions=_lowerCamelCase , references=_lowerCamelCase) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator lowercase__ : List[str] = DataCollatorCTCWithPadding(processor=_lowerCamelCase , padding=_lowerCamelCase) # Initialize our Trainer lowercase__ : Optional[int] = CTCTrainer( model=_lowerCamelCase , data_collator=_lowerCamelCase , args=_lowerCamelCase , compute_metrics=_lowerCamelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: lowercase__ : List[str] = last_checkpoint elif os.path.isdir(model_args.model_name_or_path): lowercase__ : Union[str, Any] = model_args.model_name_or_path else: lowercase__ : Union[str, Any] = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank): processor.save_pretrained(training_args.output_dir) lowercase__ : List[str] = trainer.train(resume_from_checkpoint=_lowerCamelCase) trainer.save_model() lowercase__ : Union[str, Any] = train_result.metrics lowercase__ : int = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCamelCase) ) lowercase__ : int = min(_lowerCamelCase , len(_lowerCamelCase)) trainer.log_metrics("train" , _lowerCamelCase) trainer.save_metrics("train" , _lowerCamelCase) trainer.save_state() # Evaluation lowercase__ : Optional[Any] = {} if training_args.do_eval: logger.info("*** Evaluate ***") lowercase__ : Any = trainer.evaluate() lowercase__ : List[str] = data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowerCamelCase) lowercase__ : Union[str, Any] = min(_lowerCamelCase , len(_lowerCamelCase)) trainer.log_metrics("eval" , _lowerCamelCase) trainer.save_metrics("eval" , _lowerCamelCase) return results if __name__ == "__main__": main()
87
"""simple docstring""" import os # Precomputes a list of the 100 first triangular numbers lowerCamelCase_ : List[str] = [int(0.5 * n * (n + 1)) for n in range(1, 1_01)] def UpperCAmelCase__ ( ): """simple docstring""" A_ : Union[str, Any] = os.path.dirname(os.path.realpath(_UpperCAmelCase ) ) A_ : Tuple = os.path.join(_UpperCAmelCase , 'words.txt' ) A_ : List[Any] = '' with open(_UpperCAmelCase ) as f: A_ : int = f.readline() A_ : Optional[Any] = [word.strip('"' ) for word in words.strip('\r\n' ).split(',' )] A_ : Dict = [ word for word in [sum(ord(_UpperCAmelCase ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(_UpperCAmelCase ) if __name__ == "__main__": print(solution())
286
0
'''simple docstring''' import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class __lowercase ( TensorFormatter[Mapping, "torch.Tensor", Mapping] ): '''simple docstring''' def __init__(self ,_lowerCamelCase=None ,**_lowerCamelCase ) -> int: '''simple docstring''' super().__init__(features=_a ) __lowercase = torch_tensor_kwargs import torch # noqa import torch at initialization def _UpperCAmelCase (self ,_lowerCamelCase ) -> Tuple: '''simple docstring''' import torch if isinstance(_a ,_a ) and column: if all( isinstance(_a ,torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(_a ) return column def _UpperCAmelCase (self ,_lowerCamelCase ) -> Any: '''simple docstring''' import torch 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() __lowercase = {} if isinstance(_a ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.integer ): __lowercase = {"""dtype""": torch.intaa} elif isinstance(_a ,(np.number, np.ndarray) ) and np.issubdtype(value.dtype ,np.floating ): __lowercase = {"""dtype""": torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_a ,PIL.Image.Image ): __lowercase = np.asarray(_a ) return torch.tensor(_a ,**{**default_dtype, **self.torch_tensor_kwargs} ) def _UpperCAmelCase (self ,_lowerCamelCase ) -> Dict: '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(_a ,'''__array__''' ) and not isinstance(_a ,torch.Tensor ): __lowercase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_a ,np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) elif isinstance(_a ,(list, tuple) ): return self._consolidate([self.recursive_tensorize(_a ) for substruct in data_struct] ) return self._tensorize(_a ) def _UpperCAmelCase (self ,_lowerCamelCase ) -> str: '''simple docstring''' return map_nested(self._recursive_tensorize ,_a ,map_list=_a ) def _UpperCAmelCase (self ,_lowerCamelCase ) -> Mapping: '''simple docstring''' __lowercase = self.numpy_arrow_extractor().extract_row(_a ) __lowercase = self.python_features_decoder.decode_row(_a ) return self.recursive_tensorize(_a ) def _UpperCAmelCase (self ,_lowerCamelCase ) -> "torch.Tensor": '''simple docstring''' __lowercase = self.numpy_arrow_extractor().extract_column(_a ) __lowercase = self.python_features_decoder.decode_column(_a ,pa_table.column_names[0] ) __lowercase = self.recursive_tensorize(_a ) __lowercase = self._consolidate(_a ) return column def _UpperCAmelCase (self ,_lowerCamelCase ) -> Mapping: '''simple docstring''' __lowercase = self.numpy_arrow_extractor().extract_batch(_a ) __lowercase = self.python_features_decoder.decode_batch(_a ) __lowercase = self.recursive_tensorize(_a ) for column_name in batch: __lowercase = self._consolidate(batch[column_name] ) return batch
362
'''simple docstring''' import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class __lowercase : '''simple docstring''' def __init__(self ,_lowerCamelCase ,_lowerCamelCase=sys.maxsize ) -> Optional[Any]: '''simple docstring''' __lowercase = '''bilinear''' __lowercase = max_size __lowercase = short_edge_length def __call__(self ,_lowerCamelCase ) -> str: '''simple docstring''' __lowercase = [] for img in imgs: __lowercase , __lowercase = img.shape[:2] # later: provide list and randomly choose index for resize __lowercase = np.random.randint(self.short_edge_length[0] ,self.short_edge_length[1] + 1 ) if size == 0: return img __lowercase = size * 1.0 / min(_lowerCamelCase ,_lowerCamelCase ) if h < w: __lowercase , __lowercase = size, scale * w else: __lowercase , __lowercase = scale * h, size if max(_lowerCamelCase ,_lowerCamelCase ) > self.max_size: __lowercase = self.max_size * 1.0 / max(_lowerCamelCase ,_lowerCamelCase ) __lowercase = newh * scale __lowercase = neww * scale __lowercase = int(neww + 0.5 ) __lowercase = int(newh + 0.5 ) if img.dtype == np.uinta: __lowercase = Image.fromarray(_lowerCamelCase ) __lowercase = pil_image.resize((neww, newh) ,PILImageResampling.BILINEAR ) __lowercase = np.asarray(_lowerCamelCase ) else: __lowercase = img.permute(2 ,0 ,1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw __lowercase = nn.functional.interpolate( _lowerCamelCase ,(newh, neww) ,mode=self.interp_method ,align_corners=_lowerCamelCase ).squeeze(0 ) img_augs.append(_lowerCamelCase ) return img_augs class __lowercase : '''simple docstring''' def __init__(self ,_lowerCamelCase ) -> Union[str, Any]: '''simple docstring''' __lowercase = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] ,cfg.INPUT.MAX_SIZE_TEST ) __lowercase = cfg.INPUT.FORMAT __lowercase = cfg.SIZE_DIVISIBILITY __lowercase = cfg.PAD_VALUE __lowercase = cfg.INPUT.MAX_SIZE_TEST __lowercase = cfg.MODEL.DEVICE __lowercase = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) ,1 ,1 ) __lowercase = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) ,1 ,1 ) __lowercase = lambda _lowerCamelCase : (x - self.pixel_mean) / self.pixel_std def _UpperCAmelCase (self ,_lowerCamelCase ) -> Dict: '''simple docstring''' __lowercase = tuple(max(_lowerCamelCase ) for s in zip(*[img.shape for img in images] ) ) __lowercase = [im.shape[-2:] for im in images] __lowercase = [ nn.functional.pad( _lowerCamelCase ,[0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] ,value=self.pad_value ,) for size, im in zip(_lowerCamelCase ,_lowerCamelCase ) ] return torch.stack(_lowerCamelCase ), torch.tensor(_lowerCamelCase ) def __call__(self ,_lowerCamelCase ,_lowerCamelCase=False ) -> Tuple: '''simple docstring''' with torch.no_grad(): if not isinstance(_lowerCamelCase ,_lowerCamelCase ): __lowercase = [images] if single_image: assert len(_lowerCamelCase ) == 1 for i in range(len(_lowerCamelCase ) ): if isinstance(images[i] ,torch.Tensor ): images.insert(_lowerCamelCase ,images.pop(_lowerCamelCase ).to(self.device ).float() ) elif not isinstance(images[i] ,torch.Tensor ): images.insert( _lowerCamelCase ,torch.as_tensor(img_tensorize(images.pop(_lowerCamelCase ) ,input_format=self.input_format ) ) .to(self.device ) .float() ,) # resize smallest edge __lowercase = torch.tensor([im.shape[:2] for im in images] ) __lowercase = self.aug(_lowerCamelCase ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic __lowercase = [self.normalizer(_lowerCamelCase ) for x in images] # now pad them to do the following operations __lowercase , __lowercase = self.pad(_lowerCamelCase ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad __lowercase = torch.true_divide(_lowerCamelCase ,_lowerCamelCase ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _lowerCAmelCase ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : Tuple ): boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _lowerCAmelCase ( lowerCamelCase_ : str , lowerCamelCase_ : Tuple[int, int] ): assert torch.isfinite(lowerCamelCase_ ).all(), "Box tensor contains infinite or NaN!" __lowercase , __lowercase = box_size tensor[:, 0].clamp_(min=0 , max=lowerCamelCase_ ) tensor[:, 1].clamp_(min=0 , max=lowerCamelCase_ ) tensor[:, 2].clamp_(min=0 , max=lowerCamelCase_ ) tensor[:, 3].clamp_(min=0 , max=lowerCamelCase_ )
217
0
from __future__ import annotations from collections.abc import Callable def UpperCAmelCase__ ( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase = 100, ): lowercase :Optional[Any] = x_start lowercase :List[Any] = fnc(lowerCamelCase ) lowercase :Dict = 0.0 for _ in range(lowerCamelCase ): # Approximates small segments of curve as linear and solve # for trapezoidal area lowercase :str = (x_end - x_start) / steps + xa lowercase :Dict = fnc(lowerCamelCase ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step lowercase :List[Any] = xa lowercase :Union[str, Any] = fxa return area if __name__ == "__main__": def UpperCAmelCase__ ( lowerCamelCase ): 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:") _UpperCAmelCase : int = 10 while i <= 100000: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
236
import os import pytest from attr import dataclass _UpperCAmelCase : List[str] = "us-east-1" # defaults region @dataclass class __lowerCAmelCase : _a = 42 _a = '''arn:aws:iam::558105141721:role/sagemaker_execution_role''' _a = { '''task_name''': '''mnli''', '''per_device_train_batch_size''': 16, '''per_device_eval_batch_size''': 16, '''do_train''': True, '''do_eval''': True, '''do_predict''': True, '''output_dir''': '''/opt/ml/model''', '''overwrite_output_dir''': True, '''max_steps''': 500, '''save_steps''': 5500, } _a = {**hyperparameters, '''max_steps''': 1000} @property def SCREAMING_SNAKE_CASE ( self: str ): if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def SCREAMING_SNAKE_CASE ( self: Dict ): return F"{self.framework}-transfromers-test" @property def SCREAMING_SNAKE_CASE ( self: Any ): return F"./tests/sagemaker/scripts/{self.framework}" @property def SCREAMING_SNAKE_CASE ( self: Optional[int] ): if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ ( lowerCamelCase ): lowercase :Union[str, Any] = SageMakerTestEnvironment(framework=request.cls.framework )
236
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class __magic_name__ ( unittest.TestCase ): """simple docstring""" def __init__( self :List[str] , snake_case :Optional[int] , snake_case :Tuple=7 , snake_case :Union[str, Any]=3 , snake_case :int=30 , snake_case :Optional[int]=400 , snake_case :Tuple=True , snake_case :str=None , snake_case :Tuple=True , snake_case :List[Any]=[0.5, 0.5, 0.5] , snake_case :Tuple=[0.5, 0.5, 0.5] , snake_case :int=True , snake_case :Optional[Any]=1 / 255 , snake_case :Optional[Any]=True , ): '''simple docstring''' A_ : Optional[int] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333} A_ : Optional[Any] = parent A_ : Optional[int] = batch_size A_ : int = num_channels A_ : Optional[int] = min_resolution A_ : List[str] = max_resolution A_ : str = do_resize A_ : str = size A_ : str = do_normalize A_ : List[str] = image_mean A_ : str = image_std A_ : Union[str, Any] = do_rescale A_ : Optional[Any] = rescale_factor A_ : List[str] = do_pad def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE ( self :Dict , snake_case :Union[str, Any] , snake_case :int=False ): '''simple docstring''' if not batched: A_ : Optional[int] = image_inputs[0] if isinstance(snake_case , Image.Image ): A_ , A_ : Dict = image.size else: A_ , A_ : List[str] = image.shape[1], image.shape[2] if w < h: A_ : Dict = int(self.size["shortest_edge"] * h / w ) A_ : int = self.size["shortest_edge"] elif w > h: A_ : Tuple = self.size["shortest_edge"] A_ : Tuple = int(self.size["shortest_edge"] * w / h ) else: A_ : Tuple = self.size["shortest_edge"] A_ : List[Any] = self.size["shortest_edge"] else: A_ : Optional[Any] = [] for image in image_inputs: A_ , A_ : Tuple = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A_ : int = max(snake_case , key=lambda snake_case : item[0] )[0] A_ : int = max(snake_case , key=lambda snake_case : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __magic_name__ ( lowerCamelCase__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = DeformableDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : Tuple = DeformableDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case , "image_mean" ) ) self.assertTrue(hasattr(snake_case , "image_std" ) ) self.assertTrue(hasattr(snake_case , "do_normalize" ) ) self.assertTrue(hasattr(snake_case , "do_resize" ) ) self.assertTrue(hasattr(snake_case , "do_rescale" ) ) self.assertTrue(hasattr(snake_case , "do_pad" ) ) self.assertTrue(hasattr(snake_case , "size" ) ) def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1_333} ) self.assertEqual(image_processor.do_pad , snake_case ) A_ : Any = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=snake_case ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , snake_case ) def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , Image.Image ) # Test not batched input A_ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values A_ , A_ : Dict = self.image_processor_tester.get_expected_values(snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ , A_ : Tuple = self.image_processor_tester.get_expected_values(snake_case , batched=snake_case ) A_ : Tuple = image_processing(snake_case , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A_ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case , numpify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , np.ndarray ) # Test not batched input A_ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values A_ , A_ : Dict = self.image_processor_tester.get_expected_values(snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ : str = image_processing(snake_case , return_tensors="pt" ).pixel_values A_ , A_ : Optional[Any] = self.image_processor_tester.get_expected_values(snake_case , batched=snake_case ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case , torchify=snake_case ) for image in image_inputs: self.assertIsInstance(snake_case , torch.Tensor ) # Test not batched input A_ : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values A_ , A_ : Tuple = self.image_processor_tester.get_expected_values(snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ : Union[str, Any] = image_processing(snake_case , return_tensors="pt" ).pixel_values A_ , A_ : Union[str, Any] = self.image_processor_tester.get_expected_values(snake_case , batched=snake_case ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE ( self :int ): '''simple docstring''' A_ : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: A_ : Optional[int] = json.loads(f.read() ) A_ : Tuple = {"image_id": 39_769, "annotations": target} # encode them A_ : Dict = DeformableDetrImageProcessor() A_ : Optional[int] = image_processing(images=snake_case , annotations=snake_case , return_tensors="pt" ) # verify pixel values A_ : int = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , snake_case ) A_ : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case , atol=1e-4 ) ) # verify area A_ : List[str] = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case ) ) # verify boxes A_ : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case ) A_ : Union[str, Any] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case , atol=1e-3 ) ) # verify image_id A_ : Any = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case ) ) # verify is_crowd A_ : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case ) ) # verify class_labels A_ : int = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case ) ) # verify orig_size A_ : Optional[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case ) ) # verify size A_ : List[str] = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case ) ) @slow def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: A_ : str = json.loads(f.read() ) A_ : Optional[Any] = {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target} A_ : Optional[int] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them A_ : List[Any] = DeformableDetrImageProcessor(format="coco_panoptic" ) A_ : Dict = image_processing(images=snake_case , annotations=snake_case , masks_path=snake_case , return_tensors="pt" ) # verify pixel values A_ : List[Any] = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding["pixel_values"].shape , snake_case ) A_ : Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case , atol=1e-4 ) ) # verify area A_ : Tuple = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case ) ) # verify boxes A_ : Dict = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case ) A_ : List[Any] = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case , atol=1e-3 ) ) # verify image_id A_ : Union[str, Any] = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case ) ) # verify is_crowd A_ : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case ) ) # verify class_labels A_ : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case ) ) # verify masks A_ : Dict = 822_873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , snake_case ) # verify orig_size A_ : List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case ) ) # verify size A_ : str = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case ) )
70
from random import randint from tempfile import TemporaryFile import numpy as np def __snake_case ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : str , _lowerCAmelCase : Optional[int] ) -> Dict: A_ : Optional[Any] = 0 if start < end: A_ : Tuple = randint(_lowerCAmelCase , _lowerCAmelCase ) A_ : str = a[end] A_ : Optional[Any] = a[pivot] A_ : List[str] = temp A_ , A_ : int = _in_place_partition(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) count += _in_place_quick_sort(_lowerCAmelCase , _lowerCAmelCase , p - 1 ) count += _in_place_quick_sort(_lowerCAmelCase , p + 1 , _lowerCAmelCase ) return count def __snake_case ( _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[Any] ) -> str: A_ : Union[str, Any] = 0 A_ : List[str] = randint(_lowerCAmelCase , _lowerCAmelCase ) A_ : str = a[end] A_ : str = a[pivot] A_ : Any = temp A_ : int = start - 1 for index in range(_lowerCAmelCase , _lowerCAmelCase ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value A_ : Union[str, Any] = new_pivot_index + 1 A_ : Union[str, Any] = a[new_pivot_index] A_ : Union[str, Any] = a[index] A_ : Union[str, Any] = temp A_ : Tuple = a[new_pivot_index + 1] A_ : Optional[int] = a[end] A_ : Dict = temp return new_pivot_index + 1, count _lowerCAmelCase : List[str] = TemporaryFile() _lowerCAmelCase : int = 100 # 1000 elements are to be sorted _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = 0, 1 # mean and standard deviation _lowerCAmelCase : int = np.random.normal(mu, sigma, p) np.save(outfile, X) print('''The array is''') print(X) outfile.seek(0) # using the same array _lowerCAmelCase : Optional[Any] = np.load(outfile) _lowerCAmelCase : Optional[int] = len(M) - 1 _lowerCAmelCase : Union[str, Any] = _in_place_quick_sort(M, 0, r) print( '''No of Comparisons for 100 elements selected from a standard normal distribution''' '''is :''' ) print(z)
70
1
"""simple docstring""" from __future__ import annotations class UpperCamelCase_ : def __init__( self : Any , lowerCAmelCase_ : int ) -> None: UpperCAmelCase_ : Any = data UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None def snake_case ( A__ ): # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def snake_case ( A__ ): return 1 + max(depth_of_tree(tree.left ) ,depth_of_tree(tree.right ) ) if tree else 0 def snake_case ( A__ ): if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def snake_case ( ): # Main function for testing. UpperCAmelCase_ : List[str] = Node(1 ) UpperCAmelCase_ : Any = Node(2 ) UpperCAmelCase_ : Optional[Any] = Node(3 ) UpperCAmelCase_ : Union[str, Any] = Node(4 ) UpperCAmelCase_ : int = Node(5 ) UpperCAmelCase_ : Optional[int] = Node(6 ) UpperCAmelCase_ : Any = Node(7 ) UpperCAmelCase_ : List[str] = Node(8 ) UpperCAmelCase_ : List[Any] = Node(9 ) print(is_full_binary_tree(A__ ) ) print(depth_of_tree(A__ ) ) print("Tree is: " ) display(A__ ) if __name__ == "__main__": main()
268
"""simple docstring""" from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def snake_case ( A__ ,A__ ,A__ ): if not arr: return None, None, 0 if low == high: return low, high, arr[low] UpperCAmelCase_ : Dict = (low + high) // 2 UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Any = max_subarray(A__ ,A__ ,A__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = max_subarray(A__ ,mid + 1 ,A__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = max_cross_sum(A__ ,A__ ,A__ ,A__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def snake_case ( A__ ,A__ ,A__ ,A__ ): UpperCAmelCase_ , UpperCAmelCase_ : str = float("-inf" ), -1 UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = float("-inf" ), -1 UpperCAmelCase_ : int | float = 0 for i in range(A__ ,low - 1 ,-1 ): summ += arr[i] if summ > left_sum: UpperCAmelCase_ : str = summ UpperCAmelCase_ : Any = i UpperCAmelCase_ : Dict = 0 for i in range(mid + 1 ,high + 1 ): summ += arr[i] if summ > right_sum: UpperCAmelCase_ : List[Any] = summ UpperCAmelCase_ : Optional[Any] = i return max_left, max_right, (left_sum + right_sum) def snake_case ( A__ ): UpperCAmelCase_ : str = [randint(1 ,A__ ) for _ in range(A__ )] UpperCAmelCase_ : str = time.time() max_subarray(A__ ,0 ,input_size - 1 ) UpperCAmelCase_ : int = time.time() return end - start def snake_case ( ): UpperCAmelCase_ : int = [10, 1_00, 10_00, 1_00_00, 5_00_00, 10_00_00, 20_00_00, 30_00_00, 40_00_00, 50_00_00] UpperCAmelCase_ : List[str] = [time_max_subarray(A__ ) for input_size in input_sizes] print("No of Inputs\t\tTime Taken" ) for input_size, runtime in zip(A__ ,A__ ): print(A__ ,"\t\t" ,A__ ) plt.plot(A__ ,A__ ) plt.xlabel("Number of Inputs" ) plt.ylabel("Time taken in seconds" ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
268
1
"""simple docstring""" def _snake_case ( _snake_case : str ) -> bool: if not all(x.isalpha() for x in string ): raise ValueError('String must only contain alphabetic characters.' ) _A = sorted(string.lower() ) return len(_snake_case ) == len(set(_snake_case ) ) if __name__ == "__main__": a = input('''Enter a string ''').strip() a = is_isogram(input_str) print(F'''{input_str} is {"an" if isogram else "not an"} isogram.''')
362
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a = get_logger(__name__) class lowercase_ ( enum.Enum ): '''simple docstring''' UpperCAmelCase : Optional[int] = '''all_checks''' UpperCAmelCase : List[Any] = '''basic_checks''' UpperCAmelCase : Any = '''no_checks''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' def _snake_case ( _snake_case : Optional[dict] , _snake_case : dict , _snake_case : Dict=None ) -> Dict: '''simple docstring''' if expected_checksums is None: logger.info('Unable to verify checksums.' ) return if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(_snake_case ) - set(_snake_case ) ) ) if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise UnexpectedDownloadedFile(str(set(_snake_case ) - set(_snake_case ) ) ) _A = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] _A = ' for ' + verification_name if verification_name is not None else '' if len(_snake_case ) > 0: raise NonMatchingChecksumError( F'''Checksums didn\'t match{for_verification_name}:\n''' F'''{bad_urls}\n''' 'Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error' ) logger.info('All the checksums matched successfully' + for_verification_name ) class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' def _snake_case ( _snake_case : Optional[dict] , _snake_case : dict ) -> List[str]: '''simple docstring''' if expected_splits is None: logger.info('Unable to verify splits sizes.' ) return if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise ExpectedMoreSplits(str(set(_snake_case ) - set(_snake_case ) ) ) if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise UnexpectedSplits(str(set(_snake_case ) - set(_snake_case ) ) ) _A = [ {'expected': expected_splits[name], 'recorded': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_snake_case ) > 0: raise NonMatchingSplitsSizesError(str(_snake_case ) ) logger.info('All the splits matched successfully.' ) def _snake_case ( _snake_case : str , _snake_case : bool = True ) -> dict: '''simple docstring''' if record_checksum: _A = shaaaa() with open(_snake_case , 'rb' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B'' ): m.update(_snake_case ) _A = m.hexdigest() else: _A = None return {"num_bytes": os.path.getsize(_snake_case ), "checksum": checksum} def _snake_case ( _snake_case : int ) -> int: '''simple docstring''' if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
271
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __lowerCAmelCase : str ={"""configuration_speech_encoder_decoder""": ["""SpeechEncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Tuple =["""SpeechEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[str] =["""FlaxSpeechEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys __lowerCAmelCase : str =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
197
"""simple docstring""" import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def UpperCAmelCase__ ( lowerCAmelCase__ :Any , lowerCAmelCase__ :str , lowerCAmelCase__ :str , lowerCAmelCase__ :Path , lowerCAmelCase__ :str = None , lowerCAmelCase__ :str = None , lowerCAmelCase__ :str = None , ) -> Optional[int]: '''simple docstring''' if config_name_or_path is None: lowercase = """facebook/rag-token-base""" if model_type == """rag_token""" else """facebook/rag-sequence-base""" if generator_tokenizer_name_or_path is None: lowercase = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: lowercase = question_encoder_name_or_path lowercase = RagTokenForGeneration if model_type == """rag_token""" else RagSequenceForGeneration # Save model. lowercase = RagConfig.from_pretrained(lowerCAmelCase__ ) lowercase = AutoConfig.from_pretrained(lowerCAmelCase__ ) lowercase = AutoConfig.from_pretrained(lowerCAmelCase__ ) lowercase = gen_config lowercase = question_encoder_config lowercase = model_class.from_pretrained_question_encoder_generator( lowerCAmelCase__ , lowerCAmelCase__ , config=lowerCAmelCase__ ) rag_model.save_pretrained(lowerCAmelCase__ ) # Sanity check. model_class.from_pretrained(lowerCAmelCase__ ) # Save tokenizers. lowercase = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) gen_tokenizer.save_pretrained(dest_dir / """generator_tokenizer/""" ) lowercase = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) question_encoder_tokenizer.save_pretrained(dest_dir / """question_encoder_tokenizer/""" ) if __name__ == "__main__": __lowerCAmelCase : int =argparse.ArgumentParser() parser.add_argument( """--model_type""", choices=["""rag_sequence""", """rag_token"""], required=True, type=str, help="""RAG model type: rag_sequence, rag_token""", ) parser.add_argument("""--dest""", type=str, required=True, help="""Path to the output checkpoint directory.""") parser.add_argument("""--generator_name_or_path""", type=str, required=True, help="""Generator model identifier""") parser.add_argument( """--question_encoder_name_or_path""", type=str, required=True, help="""Question encoder model identifier""" ) parser.add_argument( """--generator_tokenizer_name_or_path""", type=str, help="""Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``""", ) parser.add_argument( """--question_encoder_tokenizer_name_or_path""", type=str, help="""Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``""", ) parser.add_argument( """--config_name_or_path""", type=str, help=( """Identifier of the model config to use, if not provided, resolves to a base config for a given""" """ ``model_type``""" ), ) __lowerCAmelCase : List[str] =parser.parse_args() __lowerCAmelCase : Dict =Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
197
1
import math def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: return math.sqrt(UpperCamelCase_ ) * math.sqrt(UpperCamelCase_ ) == num def lowerCAmelCase_ ( UpperCamelCase_ ) -> bool: UpperCamelCase_ = 0 UpperCamelCase_ = n while left <= right: UpperCamelCase_ = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: UpperCamelCase_ = mid - 1 else: UpperCamelCase_ = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
328
def lowerCAmelCase_ ( UpperCamelCase_ ) -> list: UpperCamelCase_ = int(UpperCamelCase_ ) if n_element < 1: UpperCamelCase_ = ValueError("a should be a positive number" ) raise my_error UpperCamelCase_ = [1] UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = (0, 0, 0) UpperCamelCase_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": _UpperCAmelCase = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') _UpperCAmelCase = hamming(int(n)) print('-----------------------------------------------------') print(f'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
328
1
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __snake_case ( unittest.TestCase ): @property def lowerCamelCase ( self : Optional[int]): """simple docstring""" torch.manual_seed(0) UpperCAmelCase_ = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = self.dummy_uncond_unet UpperCAmelCase_ = KarrasVeScheduler() UpperCAmelCase_ = KarrasVePipeline(unet=_snake_case , scheduler=_snake_case) pipe.to(_snake_case) pipe.set_progress_bar_config(disable=_snake_case) UpperCAmelCase_ = torch.manual_seed(0) UpperCAmelCase_ = pipe(num_inference_steps=2 , generator=_snake_case , output_type='''numpy''').images UpperCAmelCase_ = torch.manual_seed(0) UpperCAmelCase_ = pipe(num_inference_steps=2 , generator=_snake_case , output_type='''numpy''' , return_dict=_snake_case)[0] UpperCAmelCase_ = image[0, -3:, -3:, -1] UpperCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 @slow @require_torch class __snake_case ( unittest.TestCase ): def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ = '''google/ncsnpp-celebahq-256''' UpperCAmelCase_ = UNetaDModel.from_pretrained(_snake_case) UpperCAmelCase_ = KarrasVeScheduler() UpperCAmelCase_ = KarrasVePipeline(unet=_snake_case , scheduler=_snake_case) pipe.to(_snake_case) pipe.set_progress_bar_config(disable=_snake_case) UpperCAmelCase_ = torch.manual_seed(0) UpperCAmelCase_ = pipe(num_inference_steps=20 , generator=_snake_case , output_type='''numpy''').images UpperCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCAmelCase_ = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
51
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "google/switch-base-8": "https://huggingface.co/google/switch-base-8/blob/main/config.json", } class snake_case ( __snake_case ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = """switch_transformers""" SCREAMING_SNAKE_CASE_ : Tuple = ["""past_key_values"""] SCREAMING_SNAKE_CASE_ : Any = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : List[str] , UpperCamelCase__ : List[str]=3_2_1_2_8 , UpperCamelCase__ : str=7_6_8 , UpperCamelCase__ : Union[str, Any]=6_4 , UpperCamelCase__ : Optional[int]=2_0_4_8 , UpperCamelCase__ : Dict=6_4 , UpperCamelCase__ : List[str]=1_2 , UpperCamelCase__ : Dict=3 , UpperCamelCase__ : Any=1_2 , UpperCamelCase__ : Dict=3 , UpperCamelCase__ : Dict=1_2 , UpperCamelCase__ : List[str]=8 , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=0.01 , UpperCamelCase__ : Optional[int]="float32" , UpperCamelCase__ : Any=False , UpperCamelCase__ : Dict=3_2 , UpperCamelCase__ : Union[str, Any]=1_2_8 , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : Optional[int]=1e-6 , UpperCamelCase__ : Optional[Any]=0.001 , UpperCamelCase__ : Dict=0.001 , UpperCamelCase__ : int=1.0 , UpperCamelCase__ : str="relu" , UpperCamelCase__ : int=True , UpperCamelCase__ : Any=False , UpperCamelCase__ : str=True , UpperCamelCase__ : Tuple=0 , UpperCamelCase__ : str=1 , **UpperCamelCase__ : Tuple , )-> Optional[Any]: '''simple docstring''' __lowerCAmelCase: int = vocab_size __lowerCAmelCase: str = d_model __lowerCAmelCase: str = d_kv __lowerCAmelCase: str = d_ff __lowerCAmelCase: List[str] = num_sparse_encoder_layers __lowerCAmelCase: List[Any] = num_layers __lowerCAmelCase: Optional[Any] = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __lowerCAmelCase: Tuple = num_sparse_decoder_layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_encoder_layers > 0: __lowerCAmelCase: int = self.num_layers // self.num_sparse_encoder_layers else: __lowerCAmelCase: Union[str, Any] = self.num_layers # HACK: this will create 0 sparse layers # This tells us, each how many encoder layer we'll have to set a sparse layer. if self.num_sparse_decoder_layers > 0: __lowerCAmelCase: Dict = self.num_decoder_layers // self.num_sparse_decoder_layers else: __lowerCAmelCase: Any = self.num_decoder_layers # HACK: this will create 0 sparse layers __lowerCAmelCase: Dict = num_heads __lowerCAmelCase: Dict = num_experts __lowerCAmelCase: Any = expert_capacity __lowerCAmelCase: List[Any] = router_bias __lowerCAmelCase: int = router_jitter_noise if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f"`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}") __lowerCAmelCase: Dict = router_dtype __lowerCAmelCase: Optional[Any] = router_ignore_padding_tokens __lowerCAmelCase: Union[str, Any] = relative_attention_num_buckets __lowerCAmelCase: str = relative_attention_max_distance __lowerCAmelCase: Optional[int] = dropout_rate __lowerCAmelCase: Optional[Any] = layer_norm_epsilon __lowerCAmelCase: int = initializer_factor __lowerCAmelCase: Tuple = feed_forward_proj __lowerCAmelCase: int = use_cache __lowerCAmelCase: int = add_router_probs __lowerCAmelCase: Optional[Any] = router_z_loss_coef __lowerCAmelCase: Dict = router_aux_loss_coef __lowerCAmelCase: Union[str, Any] = self.feed_forward_proj.split("-") __lowerCAmelCase: Tuple = act_info[-1] __lowerCAmelCase: str = act_info[0] == "gated" if len(UpperCamelCase__) > 1 and act_info[0] != "gated" or len(UpperCamelCase__) > 2: raise ValueError( f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer." "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'") # for backwards compatibility if feed_forward_proj == "gated-gelu": __lowerCAmelCase: List[str] = "gelu_new" super().__init__( pad_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , **UpperCamelCase__ , )
217
0
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name def A ( _lowerCamelCase ): '''simple docstring''' warnings.warn( "The preprocess method is deprecated and will be removed in a future version. Please" " use VaeImageProcessor.preprocess instead" , _lowerCamelCase , ) if isinstance(_lowerCamelCase , torch.Tensor ): return image elif isinstance(_lowerCamelCase , PIL.Image.Image ): _lowerCAmelCase : List[str] = [image] if isinstance(image[0] , PIL.Image.Image ): _lowerCAmelCase , _lowerCAmelCase : Union[str, Any] = image[0].size _lowerCAmelCase , _lowerCAmelCase : str = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 _lowerCAmelCase : Dict = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] _lowerCAmelCase : Optional[Any] = np.concatenate(_lowerCamelCase , axis=0 ) _lowerCAmelCase : str = np.array(_lowerCamelCase ).astype(np.floataa ) / 2_55.0 _lowerCAmelCase : Any = image.transpose(0 , 3 , 1 , 2 ) _lowerCAmelCase : Any = 2.0 * image - 1.0 _lowerCAmelCase : Optional[Any] = torch.from_numpy(_lowerCamelCase ) elif isinstance(image[0] , torch.Tensor ): _lowerCAmelCase : Optional[int] = torch.cat(_lowerCamelCase , dim=0 ) return image def A ( _lowerCamelCase ): '''simple docstring''' if isinstance(_lowerCamelCase , torch.Tensor ): return mask elif isinstance(_lowerCamelCase , PIL.Image.Image ): _lowerCAmelCase : List[Any] = [mask] if isinstance(mask[0] , PIL.Image.Image ): _lowerCAmelCase , _lowerCAmelCase : Dict = mask[0].size _lowerCAmelCase , _lowerCAmelCase : Any = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 _lowerCAmelCase : int = [np.array(m.convert("L" ).resize((w, h) , resample=PIL_INTERPOLATION["nearest"] ) )[None, :] for m in mask] _lowerCAmelCase : List[Any] = np.concatenate(_lowerCamelCase , axis=0 ) _lowerCAmelCase : str = mask.astype(np.floataa ) / 2_55.0 _lowerCAmelCase : Tuple = 0 _lowerCAmelCase : List[Any] = 1 _lowerCAmelCase : Any = torch.from_numpy(_lowerCamelCase ) elif isinstance(mask[0] , torch.Tensor ): _lowerCAmelCase : Optional[int] = torch.cat(_lowerCamelCase , dim=0 ) return mask class UpperCAmelCase_ ( a): lowerCamelCase__ = 42 lowerCamelCase__ = 42 def __init__( self, __a, __a): '''simple docstring''' super().__init__() self.register_modules(unet=__a, scheduler=__a) @torch.no_grad() def __call__( self, __a, __a, __a = 250, __a = 0.0, __a = 10, __a = 10, __a = None, __a = "pil", __a = True, ): '''simple docstring''' _lowerCAmelCase : List[Any] = image _lowerCAmelCase : Any = _preprocess_image(__a) _lowerCAmelCase : Optional[int] = original_image.to(device=self.device, dtype=self.unet.dtype) _lowerCAmelCase : Tuple = _preprocess_mask(__a) _lowerCAmelCase : str = mask_image.to(device=self.device, dtype=self.unet.dtype) _lowerCAmelCase : Optional[int] = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__a, __a) and len(__a) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(__a)}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators.") _lowerCAmelCase : Dict = original_image.shape _lowerCAmelCase : Union[str, Any] = randn_tensor(__a, generator=__a, device=self.device, dtype=self.unet.dtype) # set step values self.scheduler.set_timesteps(__a, __a, __a, self.device) _lowerCAmelCase : Any = eta _lowerCAmelCase : str = self.scheduler.timesteps[0] + 1 _lowerCAmelCase : Optional[Any] = generator[0] if isinstance(__a, __a) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)): if t < t_last: # predict the noise residual _lowerCAmelCase : Optional[Any] = self.unet(__a, __a).sample # compute previous image: x_t -> x_t-1 _lowerCAmelCase : Dict = self.scheduler.step(__a, __a, __a, __a, __a, __a).prev_sample else: # compute the reverse: x_t-1 -> x_t _lowerCAmelCase : List[str] = self.scheduler.undo_step(__a, __a, __a) _lowerCAmelCase : Tuple = t _lowerCAmelCase : int = (image / 2 + 0.5).clamp(0, 1) _lowerCAmelCase : Optional[Any] = image.cpu().permute(0, 2, 3, 1).numpy() if output_type == "pil": _lowerCAmelCase : str = self.numpy_to_pil(__a) if not return_dict: return (image,) return ImagePipelineOutput(images=__a)
300
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase): @property def snake_case__ ( self): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = ort.SessionOptions() _lowerCAmelCase : int = False return options def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Dict = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo.png") _lowerCAmelCase : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/overture-creations-5sI6fQgYIuo_mask.png") _lowerCAmelCase : List[str] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy") # using the PNDM scheduler by default _lowerCAmelCase : Optional[int] = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="onnx", safety_checker=__a, feature_extractor=__a, provider=self.gpu_provider, sess_options=self.gpu_options, ) pipe.set_progress_bar_config(disable=__a) _lowerCAmelCase : Any = "A red cat sitting on a park bench" _lowerCAmelCase : Optional[Any] = np.random.RandomState(0) _lowerCAmelCase : Any = pipe( prompt=__a, image=__a, mask_image=__a, strength=0.75, guidance_scale=7.5, num_inference_steps=15, generator=__a, output_type="np", ) _lowerCAmelCase : Optional[int] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image).max() < 1E-2
300
1
'''simple docstring''' import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class UpperCAmelCase ( snake_case_ ): def lowercase__ ( self : Dict ) -> Optional[int]: _lowerCAmelCase = tempfile.mkdtemp() _lowerCAmelCase = 5 # Realm tok _lowerCAmelCase = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """test""", """question""", """this""", """is""", """the""", """first""", """second""", """third""", """fourth""", """fifth""", """record""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] _lowerCAmelCase = os.path.join(self.tmpdirname , """realm_tokenizer""" ) os.makedirs(__snake_case , exist_ok=__snake_case ) _lowerCAmelCase = os.path.join(__snake_case , 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] ) ) _lowerCAmelCase = os.path.join(self.tmpdirname , """realm_block_records""" ) os.makedirs(__snake_case , exist_ok=__snake_case ) def lowercase__ ( self : Tuple ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , """realm_tokenizer""" ) ) def lowercase__ ( self : Any ) -> Union[str, Any]: shutil.rmtree(self.tmpdirname ) def lowercase__ ( self : Dict ) -> Optional[Any]: _lowerCAmelCase = RealmConfig(num_block_records=self.num_block_records ) return config def lowercase__ ( self : List[str] ) -> Tuple: _lowerCAmelCase = Dataset.from_dict( { """id""": ["""0""", """1"""], """question""": ["""foo""", """bar"""], """answers""": [["""Foo""", """Bar"""], ["""Bar"""]], } ) return dataset def lowercase__ ( self : Union[str, Any] ) -> int: _lowerCAmelCase = np.array( [ b"""This is the first record""", b"""This is the second record""", b"""This is the third record""", b"""This is the fourth record""", b"""This is the fifth record""", b"""This is a longer longer longer record""", ] , dtype=__snake_case , ) return block_records def lowercase__ ( self : List[str] ) -> Dict: _lowerCAmelCase = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowercase__ ( self : Optional[Any] ) -> int: _lowerCAmelCase = self.get_config() _lowerCAmelCase = self.get_dummy_retriever() _lowerCAmelCase = retriever.tokenizer _lowerCAmelCase = np.array([0, 3] , dtype="""long""" ) _lowerCAmelCase = tokenizer(["""Test question"""] ).input_ids _lowerCAmelCase = tokenizer( ["""the fourth"""] , add_special_tokens=__snake_case , return_token_type_ids=__snake_case , return_attention_mask=__snake_case , ).input_ids _lowerCAmelCase = config.reader_seq_len _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = retriever( __snake_case , __snake_case , answer_ids=__snake_case , max_length=__snake_case , return_tensors="""np""" ) self.assertEqual(len(__snake_case ) , 2 ) self.assertEqual(len(__snake_case ) , 2 ) self.assertEqual(len(__snake_case ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """first""", """record""", """[SEP]"""] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ["""[CLS]""", """test""", """question""", """[SEP]""", """this""", """is""", """the""", """fourth""", """record""", """[SEP]"""] , ) def lowercase__ ( self : List[str] ) -> int: _lowerCAmelCase = self.get_config() _lowerCAmelCase = self.get_dummy_retriever() _lowerCAmelCase = retriever.tokenizer _lowerCAmelCase = np.array([0, 3, 5] , dtype="""long""" ) _lowerCAmelCase = tokenizer(["""Test question"""] ).input_ids _lowerCAmelCase = tokenizer( ["""the fourth""", """longer longer"""] , add_special_tokens=__snake_case , return_token_type_ids=__snake_case , return_attention_mask=__snake_case , ).input_ids _lowerCAmelCase = config.reader_seq_len _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = retriever( __snake_case , __snake_case , answer_ids=__snake_case , max_length=__snake_case , return_tensors="""np""" ) self.assertEqual([False, True, True] , __snake_case ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , __snake_case ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , __snake_case ) def lowercase__ ( self : Any ) -> Optional[Any]: _lowerCAmelCase = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) # Test local path _lowerCAmelCase = retriever.from_pretrained(os.path.join(self.tmpdirname , """realm_block_records""" ) ) self.assertEqual(retriever.block_records[0] , b"""This is the first record""" ) # Test mocked remote path with patch("""transformers.models.realm.retrieval_realm.hf_hub_download""" ) as mock_hf_hub_download: _lowerCAmelCase = os.path.join( os.path.join(self.tmpdirname , """realm_block_records""" ) , _REALM_BLOCK_RECORDS_FILENAME ) _lowerCAmelCase = RealmRetriever.from_pretrained("""google/realm-cc-news-pretrained-openqa""" ) self.assertEqual(retriever.block_records[0] , b"""This is the first record""" )
70
'''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, BatchEncoding, PreTrainedTokenizer from ...utils import logging A__ : Any =logging.get_logger(__name__) A__ : List[Any] ='''▁''' A__ : Optional[int] ={'''vocab_file''': '''sentencepiece.bpe.model'''} A__ : Union[str, Any] ={ '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model''' ), } } A__ : Dict ={ '''facebook/nllb-200-distilled-600M''': 10_24, } # fmt: off A__ : Union[str, Any] =['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn'''] class UpperCAmelCase ( snake_case_ ): _lowercase: int = VOCAB_FILES_NAMES _lowercase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase: Dict = PRETRAINED_VOCAB_FILES_MAP _lowercase: str = ['''input_ids''', '''attention_mask'''] _lowercase: List[int] = [] _lowercase: List[int] = [] def __init__( self : int , __snake_case : Optional[Any] , __snake_case : Dict="<s>" , __snake_case : Optional[int]="</s>" , __snake_case : Dict="</s>" , __snake_case : str="<s>" , __snake_case : Optional[int]="<unk>" , __snake_case : Union[str, Any]="<pad>" , __snake_case : Union[str, Any]="<mask>" , __snake_case : List[Any]=None , __snake_case : Union[str, Any]=None , __snake_case : int=None , __snake_case : Optional[Dict[str, Any]] = None , __snake_case : str=None , __snake_case : str=False , **__snake_case : List[Any] , ) -> List[str]: # Mask token behave like a normal word, i.e. include the space before it _lowerCAmelCase = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else mask_token _lowerCAmelCase = {} if sp_model_kwargs is None else sp_model_kwargs _lowerCAmelCase = legacy_behaviour super().__init__( bos_token=__snake_case , eos_token=__snake_case , unk_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , tokenizer_file=__snake_case , src_lang=__snake_case , tgt_lang=__snake_case , additional_special_tokens=__snake_case , sp_model_kwargs=self.sp_model_kwargs , legacy_behaviour=__snake_case , **__snake_case , ) _lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__snake_case ) ) _lowerCAmelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' # spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s' # Mimic fairseq token-to-id alignment for the first 4 token _lowerCAmelCase = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _lowerCAmelCase = 1 _lowerCAmelCase = len(self.sp_model ) _lowerCAmelCase = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__snake_case ) } _lowerCAmelCase = {v: k for k, v in self.lang_code_to_id.items()} _lowerCAmelCase = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) _lowerCAmelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _lowerCAmelCase = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) _lowerCAmelCase = src_lang if src_lang is not None else """eng_Latn""" _lowerCAmelCase = self.lang_code_to_id[self._src_lang] _lowerCAmelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : List[str] ) -> List[str]: _lowerCAmelCase = self.__dict__.copy() _lowerCAmelCase = None _lowerCAmelCase = self.sp_model.serialized_model_proto() return state def __setstate__( self : Dict , __snake_case : Optional[Any] ) -> Dict: _lowerCAmelCase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _lowerCAmelCase = {} _lowerCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def lowercase__ ( self : List[Any] ) -> Any: return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def lowercase__ ( self : int ) -> str: return self._src_lang @src_lang.setter def lowercase__ ( self : Dict , __snake_case : str ) -> None: _lowerCAmelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def lowercase__ ( self : List[Any] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) _lowerCAmelCase = [1] * len(self.prefix_tokens ) _lowerCAmelCase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__snake_case )) + suffix_ones return prefix_ones + ([0] * len(__snake_case )) + ([0] * len(__snake_case )) + suffix_ones def lowercase__ ( self : Optional[Any] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def lowercase__ ( self : Optional[Any] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ) -> List[int]: _lowerCAmelCase = [self.sep_token_id] _lowerCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase__ ( self : List[str] , __snake_case : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] , __snake_case : Optional[str] , **__snake_case : Optional[int] ) -> Dict: if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) _lowerCAmelCase = src_lang _lowerCAmelCase = self(__snake_case , add_special_tokens=__snake_case , return_tensors=__snake_case , **__snake_case ) _lowerCAmelCase = self.convert_tokens_to_ids(__snake_case ) _lowerCAmelCase = tgt_lang_id return inputs def lowercase__ ( self : List[Any] ) -> Optional[int]: _lowerCAmelCase = {self.convert_ids_to_tokens(__snake_case ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowercase__ ( self : Optional[int] , __snake_case : str ) -> List[str]: return self.sp_model.encode(__snake_case , out_type=__snake_case ) def lowercase__ ( self : Optional[Any] , __snake_case : Union[str, Any] ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _lowerCAmelCase = self.sp_model.PieceToId(__snake_case ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def lowercase__ ( self : List[Any] , __snake_case : Union[str, Any] ) -> Optional[int]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def lowercase__ ( self : Optional[int] , __snake_case : Union[str, Any] ) -> str: _lowerCAmelCase = """""".join(__snake_case ).replace(__snake_case , """ """ ).strip() return out_string def lowercase__ ( self : str , __snake_case : str , __snake_case : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__snake_case ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _lowerCAmelCase = os.path.join( __snake_case , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__snake_case ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __snake_case ) elif not os.path.isfile(self.vocab_file ): with open(__snake_case , """wb""" ) as fi: _lowerCAmelCase = self.sp_model.serialized_model_proto() fi.write(__snake_case ) return (out_vocab_file,) def lowercase__ ( self : Optional[Any] , __snake_case : List[str] , __snake_case : str = "eng_Latn" , __snake_case : Optional[List[str]] = None , __snake_case : str = "fra_Latn" , **__snake_case : Optional[int] , ) -> BatchEncoding: _lowerCAmelCase = src_lang _lowerCAmelCase = tgt_lang return super().prepare_seqaseq_batch(__snake_case , __snake_case , **__snake_case ) def lowercase__ ( self : str ) -> Tuple: return self.set_src_lang_special_tokens(self.src_lang ) def lowercase__ ( self : Dict ) -> Optional[Any]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def lowercase__ ( self : str , __snake_case : int ) -> None: _lowerCAmelCase = self.lang_code_to_id[src_lang] if self.legacy_behaviour: _lowerCAmelCase = [] _lowerCAmelCase = [self.eos_token_id, self.cur_lang_code] else: _lowerCAmelCase = [self.cur_lang_code] _lowerCAmelCase = [self.eos_token_id] def lowercase__ ( self : Any , __snake_case : str ) -> None: _lowerCAmelCase = self.lang_code_to_id[lang] if self.legacy_behaviour: _lowerCAmelCase = [] _lowerCAmelCase = [self.eos_token_id, self.cur_lang_code] else: _lowerCAmelCase = [self.cur_lang_code] _lowerCAmelCase = [self.eos_token_id]
70
1
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) a__ : Tuple = logging.getLogger(__name__) a__ : Any = "Hello world! cécé herlolip" a__ : str = namedtuple( '''BertAbsConfig''', [ '''temp_dir''', '''large''', '''use_bert_emb''', '''finetune_bert''', '''encoder''', '''share_emb''', '''max_pos''', '''enc_layers''', '''enc_hidden_size''', '''enc_heads''', '''enc_ff_size''', '''enc_dropout''', '''dec_layers''', '''dec_hidden_size''', '''dec_heads''', '''dec_ff_size''', '''dec_dropout''', ], ) def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = BertAbsConfig( temp_dir='''.''' , finetune_bert=__lowerCAmelCase , large=__lowerCAmelCase , share_emb=__lowerCAmelCase , use_bert_emb=__lowerCAmelCase , encoder='''bert''' , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2_048 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : int = torch.load(__lowerCAmelCase , lambda a__ , a__ : storage ) SCREAMING_SNAKE_CASE : Dict = AbsSummarizer(__lowerCAmelCase , torch.device('''cpu''' ) , __lowerCAmelCase ) original.eval() SCREAMING_SNAKE_CASE : Optional[Any] = BertAbsSummarizer(__lowerCAmelCase , torch.device('''cpu''' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('''convert the model''' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('''Make sure that the models\' outputs are identical''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = BertTokenizer.from_pretrained('''bert-base-uncased''' ) # prepare the model inputs SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode('''This is sample éàalj\'-.''' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCAmelCase )) ) SCREAMING_SNAKE_CASE : int = torch.tensor(__lowerCAmelCase ).unsqueeze(0 ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''This is sample 3 éàalj\'-.''' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCAmelCase )) ) SCREAMING_SNAKE_CASE : Dict = torch.tensor(__lowerCAmelCase ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE : str = encoder_input_ids SCREAMING_SNAKE_CASE : Dict = decoder_input_ids SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : str = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE : Dict = original(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )[0] SCREAMING_SNAKE_CASE : List[str] = original.generator(__lowerCAmelCase ) SCREAMING_SNAKE_CASE : Dict = new_model( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )[0] SCREAMING_SNAKE_CASE : Optional[Any] = new_model.generator(__lowerCAmelCase ) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('''Maximum absolute difference beween weights: {:.2f}'''.format(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE : List[str] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('''Maximum absolute difference beween weights: {:.2f}'''.format(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.allclose(__lowerCAmelCase , __lowerCAmelCase , atol=1e-3 ) if are_identical: logging.info('''all weights are equal up to 1e-3''' ) else: raise ValueError('''the weights are different. The new model is likely different from the original one.''' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('''saving the model\'s state dictionary''' ) torch.save( new_model.state_dict() , '''./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin''' ) if __name__ == "__main__": a__ : str = argparse.ArgumentParser() parser.add_argument( '''--bertabs_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.''', ) a__ : Any = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
361
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class a_ ( a__ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = DDIMPipeline __SCREAMING_SNAKE_CASE : Tuple = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __SCREAMING_SNAKE_CASE : Tuple = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } __SCREAMING_SNAKE_CASE : str = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE : List[Any] = False def __lowerCAmelCase ( self ) ->int: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler() SCREAMING_SNAKE_CASE : Dict = {'''unet''': unet, '''scheduler''': scheduler} return components def __lowerCAmelCase ( self , _lowerCamelCase , _lowerCamelCase=0 ) ->int: if str(_lowerCamelCase ).startswith('''mps''' ): SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(_lowerCamelCase ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self ) ->Dict: SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[Any] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[str] = pipe(**_lowerCamelCase ).images SCREAMING_SNAKE_CASE : Optional[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) SCREAMING_SNAKE_CASE : int = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) SCREAMING_SNAKE_CASE : str = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def __lowerCAmelCase ( self ) ->Optional[int]: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_save_load_local(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Union[str, Any]: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def __lowerCAmelCase ( self ) ->Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self ) ->List[Any]: SCREAMING_SNAKE_CASE : Optional[int] = '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE : Dict = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : Tuple = DDIMScheduler() SCREAMING_SNAKE_CASE : Optional[int] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self ) ->Optional[int]: SCREAMING_SNAKE_CASE : List[Any] = '''google/ddpm-ema-bedroom-256''' SCREAMING_SNAKE_CASE : List[str] = UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : int = DDIMScheduler.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE : Any = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
19
0
def a_ ( lowerCAmelCase_ : list, lowerCAmelCase_ : list, lowerCAmelCase_ : int ): __lowerCAmelCase = len(__a ) __lowerCAmelCase = [[0] * n for i in range(__a )] for i in range(__a ): __lowerCAmelCase = y_points[i] for i in range(2, __a ): for j in range(__a, __a ): __lowerCAmelCase = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
284
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """linear""": get_linear_schedule_with_warmup, """cosine""": get_cosine_schedule_with_warmup, """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup, """polynomial""": get_polynomial_decay_schedule_with_warmup, """constant""": get_constant_schedule, """constant_w_warmup""": get_constant_schedule_with_warmup, } class UpperCAmelCase__ ( lowercase__ ): """simple docstring""" def __init__( self : Optional[int] ,_a : Optional[Any]=None ,_a : Dict=None ,*_a : int ,**_a : str ): '''simple docstring''' super().__init__(*_a ,**_a ) if config is None: assert isinstance(self.model ,_a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" F""" {self.model.__class__}""" ) _a : List[Any] = self.model.config else: _a : Optional[int] = config _a : List[str] = data_args _a : List[Any] = self.config.tgt_vocab_size if isinstance(self.config ,_a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( F"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" ' padding..' ) if self.args.label_smoothing == 0: _a : List[str] = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss _a : Tuple = label_smoothed_nll_loss def __lowercase ( self : List[str] ,_a : int ): '''simple docstring''' if self.optimizer is None: _a : Union[str, Any] = ['bias', 'LayerNorm.weight'] _a : Tuple = [ { 'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], 'weight_decay': self.args.weight_decay, }, { 'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], 'weight_decay': 0.0, }, ] _a : Optional[int] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: _a : Any = Adafactor _a : Dict = {'scale_parameter': False, 'relative_step': False} else: _a : Union[str, Any] = AdamW _a : str = { 'betas': (self.args.adam_betaa, self.args.adam_betaa), 'eps': self.args.adam_epsilon, } _a : Union[str, Any] = self.args.learning_rate if self.sharded_ddp: _a : str = OSS( params=_a ,optim=_a ,**_a ,) else: _a : Tuple = optimizer_cls(_a ,**_a ) if self.lr_scheduler is None: _a : List[Any] = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.' ) def __lowercase ( self : List[Any] ,_a : List[Any] ): '''simple docstring''' _a : str = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": _a : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": _a : List[str] = schedule_func(self.optimizer ,num_warmup_steps=self.args.warmup_steps ) else: _a : Optional[int] = schedule_func( self.optimizer ,num_warmup_steps=self.args.warmup_steps ,num_training_steps=_a ) return scheduler def __lowercase ( self : Tuple ): '''simple docstring''' if isinstance(self.train_dataset ,torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size ,distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) ,) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __lowercase ( self : Dict ,_a : Dict ,_a : Any ,_a : Dict ): '''simple docstring''' if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Union[str, Any] = self.loss_fn(logits.view(-1 ,logits.shape[-1] ) ,labels.view(-1 ) ) else: # compute usual loss via models _a, _a : Union[str, Any] = model(**_a ,labels=_a ,use_cache=_a )[:2] else: # compute label smoothed loss _a : List[Any] = model(**_a ,use_cache=_a )[0] _a : Any = torch.nn.functional.log_softmax(_a ,dim=-1 ) _a, _a : List[str] = self.loss_fn(_a ,_a ,self.args.label_smoothing ,ignore_index=self.config.pad_token_id ) return loss, logits def __lowercase ( self : Optional[int] ,_a : Union[str, Any] ,_a : List[Any] ): '''simple docstring''' _a : Optional[int] = inputs.pop('labels' ) _a, _a : int = self._compute_loss(_a ,_a ,_a ) return loss def __lowercase ( self : Optional[Any] ,_a : nn.Module ,_a : Dict[str, Union[torch.Tensor, Any]] ,_a : bool ,_a : Optional[List[str]] = None ,): '''simple docstring''' _a : int = self._prepare_inputs(_a ) _a : Any = { 'max_length': self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, 'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: _a : int = self.model.generate( inputs['input_ids'] ,attention_mask=inputs['attention_mask'] ,**_a ,) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: _a : int = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) _a : Union[str, Any] = inputs.pop('labels' ) with torch.no_grad(): # compute loss on predict data _a, _a : Optional[int] = self._compute_loss(_a ,_a ,_a ) _a : Optional[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) _a : Optional[Any] = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: _a : Dict = self._pad_tensors_to_max_len(_a ,gen_kwargs['max_length'] ) return (loss, logits, labels) def __lowercase ( self : str ,_a : Tuple ,_a : Tuple ): '''simple docstring''' _a : List[Any] = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( 'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be' F""" padded to `max_length`={max_length}""" ) _a : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) ,dtype=tensor.dtype ,device=tensor.device ) _a : Union[str, Any] = tensor return padded_tensor
271
0
import os import re import shutil import sys import tempfile import unittest import black _SCREAMING_SNAKE_CASE = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. _SCREAMING_SNAKE_CASE = ''' \""" Output class for the scheduler\'s step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \""" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None ''' class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def UpperCAmelCase_ ( self : List[str] ) -> int: """simple docstring""" snake_case_ : List[str] = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , 'schedulers/' ) ) snake_case_ : Optional[int] = self.diffusers_dir shutil.copy( os.path.join(lowercase_ , 'src/diffusers/schedulers/scheduling_ddpm.py' ) , os.path.join(self.diffusers_dir , 'schedulers/scheduling_ddpm.py' ) , ) def UpperCAmelCase_ ( self : str ) -> List[Any]: """simple docstring""" snake_case_ : Dict = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def UpperCAmelCase_ ( self : str , _A : Tuple , _A : List[Any] , _A : Union[str, Any] , _A : Optional[int]=None ) -> List[str]: """simple docstring""" snake_case_ : Optional[int] = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: snake_case_ : Any = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result snake_case_ : Tuple = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) snake_case_ : Optional[int] = black.format_str(lowercase_ , mode=lowercase_ ) snake_case_ : Optional[Any] = os.path.join(self.diffusers_dir , 'new_code.py' ) with open(lowercase_ , 'w' , newline='\n' ) as f: f.write(lowercase_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(lowercase_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=lowercase_ ) with open(lowercase_ , 'r' ) as f: self.assertTrue(f.read() , lowercase_ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: """simple docstring""" snake_case_ : int = check_copies.find_code_in_diffusers('schedulers.scheduling_ddpm.DDPMSchedulerOutput' ) self.assertEqual(lowercase_ , lowercase_ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: """simple docstring""" self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' , 'DDPMSchedulerOutput' , REFERENCE_CODE + '\n' , ) # With no empty line at the end self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' , 'DDPMSchedulerOutput' , lowercase_ , ) # Copy consistency with rename self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' , 'TestSchedulerOutput' , re.sub('DDPM' , 'Test' , lowercase_ ) , ) # Copy consistency with a really long name snake_case_ : List[Any] = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( F"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , F"""{long_class_name}SchedulerOutput""" , re.sub('Bert' , lowercase_ , lowercase_ ) , ) # Copy consistency with overwrite self.check_copy_consistency( '# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' , 'TestSchedulerOutput' , lowercase_ , overwrite_result=re.sub('DDPM' , 'Test' , lowercase_ ) , )
358
def SCREAMING_SNAKE_CASE__ ( __a , __a ): snake_case_ : Optional[int] = int(__a ) # Initialize Result snake_case_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__a ): # Find denominations while int(__a ) >= int(__a ): total_value -= int(__a ) answer.append(__a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = """0""" if ( input("""Do you want to enter your denominations ? (yY/n): """).strip().lower() == "y" ): _SCREAMING_SNAKE_CASE = int(input("""Enter the number of denominations you want to add: """).strip()) for i in range(0, n): denominations.append(int(input(F'''Denomination {i}: ''').strip())) _SCREAMING_SNAKE_CASE = input("""Enter the change you want to make in Indian Currency: """).strip() else: # All denominations of Indian Currency if user does not enter _SCREAMING_SNAKE_CASE = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] _SCREAMING_SNAKE_CASE = input("""Enter the change you want to make: """).strip() if int(value) == 0 or int(value) < 0: print("""The total value cannot be zero or negative.""") else: print(F'''Following is minimal change for {value}: ''') _SCREAMING_SNAKE_CASE = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=""" """)
88
0
import math def A_ ( snake_case : int ) -> bool: '''simple docstring''' return math.sqrt(snake_case ) * math.sqrt(snake_case ) == num def A_ ( snake_case : int ) -> bool: '''simple docstring''' __UpperCamelCase = 0 __UpperCamelCase = n while left <= right: __UpperCamelCase = (left + right) // 2 if mid**2 == n: return True elif mid**2 > n: __UpperCamelCase = mid - 1 else: __UpperCamelCase = mid + 1 return False if __name__ == "__main__": import doctest doctest.testmod()
328
import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowercase__ : int = logging.get_logger(__name__) lowercase__ : List[str] = ["model.decoder.embed_positions.weights"] def A_ ( snake_case : Any ) -> List[Any]: '''simple docstring''' if "emb" in name: __UpperCamelCase = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: __UpperCamelCase = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: __UpperCamelCase = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: __UpperCamelCase = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: __UpperCamelCase = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: __UpperCamelCase = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: __UpperCamelCase = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: __UpperCamelCase = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: __UpperCamelCase = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: __UpperCamelCase = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: __UpperCamelCase = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def A_ ( snake_case : OrderedDict , snake_case : int ) -> Tuple[Dict, Dict]: '''simple docstring''' __UpperCamelCase = list(state_dict.keys() ) __UpperCamelCase = {} for key in keys: __UpperCamelCase = state_dict.pop(snake_case ) __UpperCamelCase = rename_keys(snake_case ) if "in_proj_weight" in key: # split fused qkv proj __UpperCamelCase = val[:hidden_size, :] __UpperCamelCase = val[hidden_size : 2 * hidden_size, :] __UpperCamelCase = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: __UpperCamelCase = val else: __UpperCamelCase = val return state_dict, enc_dec_proj_state_dict def A_ ( snake_case : str ) -> MusicgenDecoderConfig: '''simple docstring''' if checkpoint == "small": # default config values __UpperCamelCase = 1024 __UpperCamelCase = 24 __UpperCamelCase = 16 elif checkpoint == "medium": __UpperCamelCase = 1536 __UpperCamelCase = 48 __UpperCamelCase = 24 elif checkpoint == "large": __UpperCamelCase = 2048 __UpperCamelCase = 48 __UpperCamelCase = 32 else: raise ValueError(f"Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}." ) __UpperCamelCase = MusicgenDecoderConfig( hidden_size=snake_case , ffn_dim=hidden_size * 4 , num_hidden_layers=snake_case , num_attention_heads=snake_case , ) return config @torch.no_grad() def A_ ( snake_case : Any , snake_case : str=None , snake_case : Any=None , snake_case : Union[str, Any]="cpu" ) -> List[Any]: '''simple docstring''' __UpperCamelCase = MusicGen.get_pretrained(snake_case , device=snake_case ) __UpperCamelCase = decoder_config_from_checkpoint(snake_case ) __UpperCamelCase = fairseq_model.lm.state_dict() __UpperCamelCase , __UpperCamelCase = rename_state_dict( snake_case , hidden_size=decoder_config.hidden_size ) __UpperCamelCase = TaEncoderModel.from_pretrained('''t5-base''' ) __UpperCamelCase = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) __UpperCamelCase = MusicgenForCausalLM(snake_case ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection __UpperCamelCase , __UpperCamelCase = decoder.load_state_dict(snake_case , strict=snake_case ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(snake_case ) if len(snake_case ) > 0: raise ValueError(f"Missing key(s) in state_dict: {missing_keys}" ) if len(snake_case ) > 0: raise ValueError(f"Unexpected key(s) in state_dict: {unexpected_keys}" ) # init the composite model __UpperCamelCase = MusicgenForConditionalGeneration(text_encoder=snake_case , audio_encoder=snake_case , decoder=snake_case ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(snake_case ) # check we can do a forward pass __UpperCamelCase = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) __UpperCamelCase = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): __UpperCamelCase = model(input_ids=snake_case , decoder_input_ids=snake_case ).logits if logits.shape != (8, 1, 2048): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor __UpperCamelCase = AutoTokenizer.from_pretrained('''t5-base''' ) __UpperCamelCase = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) __UpperCamelCase = MusicgenProcessor(feature_extractor=snake_case , tokenizer=snake_case ) # set the appropriate bos/pad token ids __UpperCamelCase = 2048 __UpperCamelCase = 2048 # set other default generation config params __UpperCamelCase = int(30 * audio_encoder.config.frame_rate ) __UpperCamelCase = True __UpperCamelCase = 3.0 if pytorch_dump_folder is not None: Path(snake_case ).mkdir(exist_ok=snake_case ) logger.info(f"Saving model {checkpoint} to {pytorch_dump_folder}" ) model.save_pretrained(snake_case ) processor.save_pretrained(snake_case ) if repo_id: logger.info(f"Pushing model {checkpoint} to {repo_id}" ) model.push_to_hub(snake_case ) processor.push_to_hub(snake_case ) if __name__ == "__main__": lowercase__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowercase__ : Tuple = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
328
1
'''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 __lowerCAmelCase = logging.getLogger(__name__) __lowerCAmelCase = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __lowerCAmelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_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=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(__SCREAMING_SNAKE_CASE )} , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_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=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) __UpperCAmelCase : bool = field( default=__SCREAMING_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=__SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def __lowercase ( self : Any ): '''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 UpperCAmelCase__ : """simple docstring""" __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) __UpperCAmelCase : Optional[str] = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''The input training data file (a text file).'''} ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''} , ) __UpperCAmelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''} , ) __UpperCAmelCase : bool = field( default=__SCREAMING_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=__SCREAMING_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=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) __UpperCAmelCase : float = field( default=0.1_5 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) __UpperCAmelCase : bool = field( default=__SCREAMING_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 __lowercase ( self : Optional[int] ): '''simple docstring''' if self.train_file is not None: _a : int = 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: _a : List[Any] = self.validation_file.split('.' )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def UpperCAmelCase_ (__a : Dict , __a : List[Any] ): """simple docstring""" with open(lowerCAmelCase__ , 'r' , encoding='utf-8' ) as f: _a : List[Any] = [json.loads(lowerCAmelCase__ ) for line in f.read().splitlines() if (len(lowerCAmelCase__ ) > 0 and not line.isspace())] assert len(lowerCAmelCase__ ) == len(lowerCAmelCase__ ) _a : str = {c: dataset[c] for c in dataset.column_names} _a : int = refs return Dataset.from_dict(lowerCAmelCase__ ) def UpperCAmelCase_ (): """simple docstring""" _a : Optional[int] = 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. _a, _a, _a : int = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _a, _a, _a : Any = parser.parse_args_into_dataclasses() # Detecting last checkpoint. _a : str = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _a : Dict = 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' , lowerCAmelCase__ ) # 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. _a : Optional[Any] = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): _a : int = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""train[:{data_args.validation_split_percentage}%]""" , ) _a : Any = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=f"""train[{data_args.validation_split_percentage}%:]""" , ) else: _a : str = {} if data_args.train_file is not None: _a : int = data_args.train_file if data_args.validation_file is not None: _a : Dict = data_args.validation_file _a : List[Any] = data_args.train_file.split('.' )[-1] if extension == "txt": _a : Tuple = 'text' _a : List[Any] = load_dataset(lowerCAmelCase__ , data_files=lowerCAmelCase__ ) # 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. _a : Dict = { '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: _a : Dict = AutoConfig.from_pretrained(model_args.config_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: _a : Optional[int] = AutoConfig.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) else: _a : Union[str, Any] = 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}""" ) _a : Any = { '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: _a : int = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **lowerCAmelCase__ ) elif model_args.model_name_or_path: _a : Optional[int] = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **lowerCAmelCase__ ) 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: _a : Union[str, Any] = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=lowerCAmelCase__ , 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' ) _a : List[str] = AutoModelForMaskedLM.from_config(lowerCAmelCase__ ) model.resize_token_embeddings(len(lowerCAmelCase__ ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: _a : Tuple = datasets['train'].column_names else: _a : List[Any] = datasets['validation'].column_names _a : Union[str, Any] = 'text' if 'text' in column_names else column_names[0] _a : List[Any] = 'max_length' if data_args.pad_to_max_length else False def tokenize_function(__a : Tuple ): # Remove empty lines _a : Dict = [line for line in examples['text'] if len(lowerCAmelCase__ ) > 0 and not line.isspace()] return tokenizer(examples['text'] , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=data_args.max_seq_length ) _a : List[str] = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , 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: _a : Tuple = add_chinese_references(tokenized_datasets['train'] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: _a : List[str] = add_chinese_references( tokenized_datasets['validation'] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer _a : Optional[int] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: _a : List[str] = False # Data collator # This one will take care of randomly masking the tokens. _a : int = DataCollatorForWholeWordMask(tokenizer=lowerCAmelCase__ , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _a : Tuple = Trainer( model=lowerCAmelCase__ , args=lowerCAmelCase__ , 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=lowerCAmelCase__ , data_collator=lowerCAmelCase__ , ) # Training if training_args.do_train: if last_checkpoint is not None: _a : Optional[int] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): _a : Union[str, Any] = model_args.model_name_or_path else: _a : int = None _a : Tuple = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) trainer.save_model() # Saves the tokenizer too for easy upload _a : str = os.path.join(training_args.output_dir , 'train_results.txt' ) if trainer.is_world_process_zero(): with open(lowerCAmelCase__ , '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 _a : Optional[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) _a : Dict = trainer.evaluate() _a : str = math.exp(eval_output['eval_loss'] ) _a : str = perplexity _a : List[str] = os.path.join(training_args.output_dir , 'eval_results_mlm_wwm.txt' ) if trainer.is_world_process_zero(): with open(lowerCAmelCase__ , '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 UpperCAmelCase_ (__a : Optional[int] ): """simple docstring""" main() if __name__ == "__main__": main()
360
'''simple docstring''' def UpperCAmelCase_ (__a : list[int] , __a : list[int] ): """simple docstring""" if not len(__a ) == len(__a ) == 3: raise ValueError('Please enter a valid equation.' ) if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0: raise ValueError('Both a & b of two equations can\'t be zero.' ) # Extract the coefficients _a, _a, _a : Tuple = equationa _a, _a, _a : str = equationa # Calculate the determinants of the matrices _a : Union[str, Any] = aa * ba - aa * ba _a : List[Any] = ca * ba - ca * ba _a : List[Any] = aa * ca - aa * ca # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError('Infinite solutions. (Consistent system)' ) else: raise ValueError('No solution. (Inconsistent system)' ) else: if determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: _a : int = determinant_x / determinant _a : List[str] = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
5
0
_lowerCAmelCase : dict[tuple[int, int, int], int] = {} def __snake_case ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int ) -> int: # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on A_ : int = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one A_ : Union[str, Any] = _calculate(days - 1 , _lowerCAmelCase , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 A_ : Any = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter A_ : int = _calculate(days - 1 , _lowerCAmelCase , 0 ) A_ : Optional[int] = state_late + state_absent + state_ontime A_ : Tuple = prizestrings return prizestrings def __snake_case ( _lowerCAmelCase : int = 30 ) -> int: return _calculate(_lowerCAmelCase , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
300
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __magic_name__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self :List[Any] , snake_case :int , snake_case :int , snake_case :Optional[int] = None , snake_case :int = 50_257 , snake_case :int = 1_024 , snake_case :int = 768 , snake_case :int = 12 , snake_case :int = 12 , snake_case :Optional[int] = None , snake_case :str = "gelu_new" , snake_case :float = 0.1 , snake_case :float = 0.1 , snake_case :float = 0.1 , snake_case :float = 1e-5 , snake_case :float = 0.02 , snake_case :bool = True , snake_case :bool = True , snake_case :bool = False , snake_case :bool = False , ): '''simple docstring''' super().__init__() A_ : Tuple = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and" f" `n_embd`: {n_embd} are not equal." ) A_ : List[Any] = prefix_inner_dim A_ : Union[str, Any] = prefix_hidden_dim A_ : List[str] = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A_ : List[Any] = ( nn.Linear(self.prefix_hidden_dim , snake_case ) if self.prefix_hidden_dim is not None else nn.Identity() ) A_ : List[Any] = GPTaConfig( vocab_size=snake_case , n_positions=snake_case , n_embd=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 , ) A_ : Optional[Any] = GPTaLMHeadModel(snake_case ) def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :torch.Tensor , snake_case :torch.Tensor , snake_case :Optional[torch.Tensor] = None , snake_case :Optional[torch.Tensor] = None , ): '''simple docstring''' A_ : Any = self.transformer.transformer.wte(snake_case ) A_ : str = self.encode_prefix(snake_case ) A_ : Union[str, Any] = self.decode_prefix(snake_case ) A_ : int = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A_ : Dict = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A_ : int = torch.cat((dummy_token, input_ids) , dim=1 ) A_ : Union[str, Any] = self.transformer(inputs_embeds=snake_case , labels=snake_case , attention_mask=snake_case ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE ( self :str , snake_case :int , snake_case :torch.device ): '''simple docstring''' return torch.zeros(snake_case , self.prefix_length , dtype=torch.intaa , device=snake_case ) def SCREAMING_SNAKE_CASE ( self :Optional[int] , snake_case :int ): '''simple docstring''' return self.encode_prefix(snake_case ) @torch.no_grad() def SCREAMING_SNAKE_CASE ( self :List[Any] , snake_case :Dict , snake_case :Optional[int] , snake_case :Any ): '''simple docstring''' A_ : Any = torch.split(snake_case , 1 , dim=0 ) A_ : Optional[int] = [] A_ : Union[str, Any] = [] for feature in features: A_ : Tuple = self.decode_prefix(feature.to(snake_case ) ) # back to the clip feature # Only support beam search for now A_ , A_ : Dict = self.generate_beam( input_embeds=snake_case , device=snake_case , eos_token_id=snake_case ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A_ : int = torch.stack(snake_case ) A_ : int = torch.stack(snake_case ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :int=None , snake_case :str=None , snake_case :int=None , snake_case :int = 5 , snake_case :int = 67 , snake_case :float = 1.0 , snake_case :Optional[int] = None , ): '''simple docstring''' A_ : Optional[Any] = eos_token_id A_ : List[Any] = None A_ : List[Any] = None A_ : str = torch.ones(snake_case , device=snake_case , dtype=torch.int ) A_ : Any = torch.zeros(snake_case , device=snake_case , dtype=torch.bool ) if input_embeds is not None: A_ : Any = input_embeds else: A_ : Optional[Any] = self.transformer.transformer.wte(snake_case ) for i in range(snake_case ): A_ : Optional[Any] = self.transformer(inputs_embeds=snake_case ) A_ : str = outputs.logits A_ : int = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A_ : List[str] = logits.softmax(-1 ).log() if scores is None: A_ , A_ : Union[str, Any] = logits.topk(snake_case , -1 ) A_ : Tuple = generated.expand(snake_case , *generated.shape[1:] ) A_ , A_ : str = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A_ : Union[str, Any] = next_tokens else: A_ : List[str] = tokens.expand(snake_case , *tokens.shape[1:] ) A_ : Union[str, Any] = torch.cat((tokens, next_tokens) , dim=1 ) else: A_ : List[str] = -float(np.inf ) A_ : List[Any] = 0 A_ : Union[str, Any] = scores[:, None] + logits seq_lengths[~is_stopped] += 1 A_ : Optional[Any] = scores_sum / seq_lengths[:, None] A_ , A_ : List[str] = scores_sum_average.view(-1 ).topk(snake_case , -1 ) A_ : str = next_tokens // scores_sum.shape[1] A_ : Union[str, Any] = seq_lengths[next_tokens_source] A_ : Optional[int] = next_tokens % scores_sum.shape[1] A_ : Tuple = next_tokens.unsqueeze(1 ) A_ : Tuple = tokens[next_tokens_source] A_ : Dict = torch.cat((tokens, next_tokens) , dim=1 ) A_ : Dict = generated[next_tokens_source] A_ : Union[str, Any] = scores_sum_average * seq_lengths A_ : Optional[int] = is_stopped[next_tokens_source] A_ : Tuple = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A_ : Union[str, Any] = torch.cat((generated, next_token_embed) , dim=1 ) A_ : Any = is_stopped + next_tokens.eq(snake_case ).squeeze() if is_stopped.all(): break A_ : int = scores / seq_lengths A_ : str = scores.argsort(descending=snake_case ) # tokens tensors are already padded to max_seq_length A_ : Dict = [tokens[i] for i in order] A_ : int = torch.stack(snake_case , dim=0 ) A_ : List[Any] = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
300
1
'''simple docstring''' from __future__ import annotations __lowerCAmelCase : int = tuple[int, int, int] __lowerCAmelCase : str = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __lowerCAmelCase : Any = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # -------------------------- default selection -------------------------- # rotors -------------------------- __lowerCAmelCase : Tuple = "EGZWVONAHDCLFQMSIPJBYUKXTR" __lowerCAmelCase : Union[str, Any] = "FOBHMDKEXQNRAULPGSJVTYICZW" __lowerCAmelCase : Dict = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- __lowerCAmelCase : Dict = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } # -------------------------- extra rotors -------------------------- __lowerCAmelCase : Any = "RMDJXFUWGISLHVTCQNKYPBEZOA" __lowerCAmelCase : Optional[int] = "SGLCPQWZHKXAREONTFBVIYJUDM" __lowerCAmelCase : str = "HVSICLTYKQUBXDWAJZOMFGPREN" __lowerCAmelCase : List[Any] = "RZWQHFMVDBKICJLNTUXAGYPSOE" __lowerCAmelCase : Any = "LFKIJODBEGAMQPXVUHYSTCZRWN" __lowerCAmelCase : Any = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def UpperCamelCase ( _lowerCamelCase : RotorPositionT , _lowerCamelCase : RotorSelectionT , _lowerCamelCase : str ): # Checks if there are 3 unique rotors if (unique_rotsel := len(set(SCREAMING_SNAKE_CASE_ ) )) < 3: A__ = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(SCREAMING_SNAKE_CASE_ ) # Checks if rotor positions are valid A__, A__, A__ = rotpos if not 0 < rotorposa <= len(SCREAMING_SNAKE_CASE_ ): A__ = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(SCREAMING_SNAKE_CASE_ ) if not 0 < rotorposa <= len(SCREAMING_SNAKE_CASE_ ): A__ = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(SCREAMING_SNAKE_CASE_ ) if not 0 < rotorposa <= len(SCREAMING_SNAKE_CASE_ ): A__ = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(SCREAMING_SNAKE_CASE_ ) # Validates string and returns dict A__ = _plugboard(SCREAMING_SNAKE_CASE_ ) return rotpos, rotsel, pbdict def UpperCamelCase ( _lowerCamelCase : str ): # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__ = F"Plugboard setting isn\'t type string ({type(SCREAMING_SNAKE_CASE_ )})" raise TypeError(SCREAMING_SNAKE_CASE_ ) elif len(SCREAMING_SNAKE_CASE_ ) % 2 != 0: A__ = F"Odd number of symbols ({len(SCREAMING_SNAKE_CASE_ )})" raise Exception(SCREAMING_SNAKE_CASE_ ) elif pbstring == "": return {} pbstring.replace(" " , "" ) # Checks if all characters are unique A__ = set() for i in pbstring: if i not in abc: A__ = F"\'{i}\' not in list of symbols" raise Exception(SCREAMING_SNAKE_CASE_ ) elif i in tmppbl: A__ = F"Duplicate symbol ({i})" raise Exception(SCREAMING_SNAKE_CASE_ ) else: tmppbl.add(SCREAMING_SNAKE_CASE_ ) del tmppbl # Created the dictionary A__ = {} for j in range(0 , len(SCREAMING_SNAKE_CASE_ ) - 1 , 2 ): A__ = pbstring[j + 1] A__ = pbstring[j] return pb def UpperCamelCase ( _lowerCamelCase : str , _lowerCamelCase : RotorPositionT , _lowerCamelCase : RotorSelectionT = (rotora, rotora, rotora) , _lowerCamelCase : str = "" , ): A__ = text.upper() A__, A__, A__ = _validator( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , plugb.upper() ) A__, A__, A__ = rotor_position A__, A__, A__ = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 A__ = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: A__ = plugboard[symbol] # rotor ra -------------------------- A__ = abc.index(SCREAMING_SNAKE_CASE_ ) + rotorposa A__ = rotora[index % len(SCREAMING_SNAKE_CASE_ )] # rotor rb -------------------------- A__ = abc.index(SCREAMING_SNAKE_CASE_ ) + rotorposa A__ = rotora[index % len(SCREAMING_SNAKE_CASE_ )] # rotor rc -------------------------- A__ = abc.index(SCREAMING_SNAKE_CASE_ ) + rotorposa A__ = rotora[index % len(SCREAMING_SNAKE_CASE_ )] # reflector -------------------------- # this is the reason you don't need another machine to decipher A__ = reflector[symbol] # 2nd rotors A__ = abc[rotora.index(SCREAMING_SNAKE_CASE_ ) - rotorposa] A__ = abc[rotora.index(SCREAMING_SNAKE_CASE_ ) - rotorposa] A__ = abc[rotora.index(SCREAMING_SNAKE_CASE_ ) - rotorposa] # 2nd plugboard if symbol in plugboard: A__ = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(SCREAMING_SNAKE_CASE_ ): A__ = 0 rotorposa += 1 if rotorposa >= len(SCREAMING_SNAKE_CASE_ ): A__ = 0 rotorposa += 1 if rotorposa >= len(SCREAMING_SNAKE_CASE_ ): A__ = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(SCREAMING_SNAKE_CASE_ ) return "".join(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": __lowerCAmelCase : Any = "This is my Python script that emulates the Enigma machine from WWII." __lowerCAmelCase : Any = (1, 1, 1) __lowerCAmelCase : Dict = "pictures" __lowerCAmelCase : Optional[Any] = (rotora, rotora, rotora) __lowerCAmelCase : Any = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
366
'''simple docstring''' __lowerCAmelCase : Dict ="\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" __lowerCAmelCase : Optional[Any] =[{"type": "code", "content": INSTALL_CONTENT}] __lowerCAmelCase : Tuple ={ "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
123
0
'''simple docstring''' import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "" _lowerCamelCase = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) _lowerCamelCase = None # compression type in fsspec. ex: "gzip" _lowerCamelCase = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self , UpperCamelCase = "" , UpperCamelCase = None , UpperCamelCase = None , **UpperCamelCase ): """simple docstring""" super().__init__(self , **UpperCamelCase ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode lowerCamelCase_ = fsspec.open( UpperCamelCase , mode="rb" , protocol=UpperCamelCase , 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 {}) , ) lowerCamelCase_ = os.path.basename(self.file.path.split("::" )[0] ) lowerCamelCase_ = ( self.compressed_name[: self.compressed_name.rindex("." )] if "." in self.compressed_name else self.compressed_name ) lowerCamelCase_ = None @classmethod def snake_case ( cls , UpperCamelCase ): """simple docstring""" # compressed file paths are always relative to the archive root return super()._strip_protocol(UpperCamelCase ).lstrip("/" ) def snake_case ( self ): """simple docstring""" if self.dir_cache is None: lowerCamelCase_ = {**self.file.fs.info(self.file.path ), "name": self.uncompressed_name} lowerCamelCase_ = {f["name"]: f} def snake_case ( self , UpperCamelCase ): """simple docstring""" return self.file.open().read() def snake_case ( self , UpperCamelCase , UpperCamelCase = "rb" , UpperCamelCase=None , UpperCamelCase=True , UpperCamelCase=None , **UpperCamelCase , ): """simple docstring""" lowerCamelCase_ = self._strip_protocol(UpperCamelCase ) 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 snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "bz2" _lowerCamelCase = "bz2" _lowerCamelCase = ".bz2" class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "gzip" _lowerCamelCase = "gzip" _lowerCamelCase = ".gz" class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "lz4" _lowerCamelCase = "lz4" _lowerCamelCase = ".lz4" class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "xz" _lowerCamelCase = "xz" _lowerCamelCase = ".xz" class snake_case ( lowercase ): """simple docstring""" _lowerCamelCase = "zstd" _lowerCamelCase = "zstd" _lowerCamelCase = ".zst" def __init__( self , UpperCamelCase , UpperCamelCase = "rb" , UpperCamelCase = None , UpperCamelCase = None , UpperCamelCase = DEFAULT_BLOCK_SIZE , **UpperCamelCase , ): """simple docstring""" super().__init__( fo=UpperCamelCase , mode=UpperCamelCase , target_protocol=UpperCamelCase , target_options=UpperCamelCase , block_size=UpperCamelCase , **UpperCamelCase , ) # 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 lowerCamelCase_ = self.file.__enter__ class snake_case : """simple docstring""" def __init__( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = file_ def __enter__( self ): """simple docstring""" self._file.__enter__() return self def __exit__( self , *UpperCamelCase , **UpperCamelCase ): """simple docstring""" self._file.__exit__(*UpperCamelCase , **UpperCamelCase ) def __iter__( self ): """simple docstring""" return iter(self._file ) def snake_case ( self ): """simple docstring""" return next(self._file ) def __getattr__( self , UpperCamelCase ): """simple docstring""" return getattr(self._file , UpperCamelCase ) def fixed_enter(*UpperCamelCase , **UpperCamelCase ): return WrappedFile(_enter(*UpperCamelCase , **UpperCamelCase ) ) lowerCamelCase_ = fixed_enter
55
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A ={'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ '''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXGLMForCausalLM''', '''TFXGLMModel''', '''TFXGLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys __A =_LazyModule(__name__, globals()['''__file__'''], _import_structure)
19
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__ = logging.get_logger(__name__) def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = DPTConfig(embedding_type="hybrid" ) if "large" in checkpoint_url: UpperCAmelCase__ = 1_024 UpperCAmelCase__ = 4_096 UpperCAmelCase__ = 24 UpperCAmelCase__ = 16 UpperCAmelCase__ = [5, 11, 17, 23] UpperCAmelCase__ = [256, 512, 1_024, 1_024] UpperCAmelCase__ = (1, 384, 384) if "nyu" or "midas" in checkpoint_url: UpperCAmelCase__ = 768 UpperCAmelCase__ = [1, 1, 1, 0.5] UpperCAmelCase__ = [256, 512, 768, 768] UpperCAmelCase__ = 150 UpperCAmelCase__ = 16 UpperCAmelCase__ = (1, 384, 384) UpperCAmelCase__ = False UpperCAmelCase__ = "project" if "ade" in checkpoint_url: UpperCAmelCase__ = True UpperCAmelCase__ = 768 UpperCAmelCase__ = [1, 1, 1, 0.5] UpperCAmelCase__ = 150 UpperCAmelCase__ = 16 UpperCAmelCase__ = "huggingface/label-files" UpperCAmelCase__ = "ade20k-id2label.json" UpperCAmelCase__ = json.load(open(cached_download(hf_hub_url(__A, __A, repo_type="dataset" ) ), "r" ) ) UpperCAmelCase__ = {int(__A ): v for k, v in idalabel.items()} UpperCAmelCase__ = idalabel UpperCAmelCase__ = {v: k for k, v in idalabel.items()} UpperCAmelCase__ = [1, 150, 480, 480] return config, expected_shape def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = ["pretrained.model.head.weight", "pretrained.model.head.bias"] for k in ignore_keys: state_dict.pop(__A, __A ) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): UpperCAmelCase__ = name.replace("pretrained.model", "dpt.encoder" ) if "pretrained.model" in name: UpperCAmelCase__ = name.replace("pretrained.model", "dpt.embeddings" ) if "patch_embed" in name: UpperCAmelCase__ = name.replace("patch_embed", "" ) if "pos_embed" in name: UpperCAmelCase__ = name.replace("pos_embed", "position_embeddings" ) if "attn.proj" in name: UpperCAmelCase__ = name.replace("attn.proj", "attention.output.dense" ) if "proj" in name and "project" not in name: UpperCAmelCase__ = name.replace("proj", "projection" ) if "blocks" in name: UpperCAmelCase__ = name.replace("blocks", "layer" ) if "mlp.fc1" in name: UpperCAmelCase__ = name.replace("mlp.fc1", "intermediate.dense" ) if "mlp.fc2" in name: UpperCAmelCase__ = name.replace("mlp.fc2", "output.dense" ) if "norm1" in name and "backbone" not in name: UpperCAmelCase__ = name.replace("norm1", "layernorm_before" ) if "norm2" in name and "backbone" not in name: UpperCAmelCase__ = name.replace("norm2", "layernorm_after" ) if "scratch.output_conv" in name: UpperCAmelCase__ = name.replace("scratch.output_conv", "head" ) if "scratch" in name: UpperCAmelCase__ = name.replace("scratch", "neck" ) if "layer1_rn" in name: UpperCAmelCase__ = name.replace("layer1_rn", "convs.0" ) if "layer2_rn" in name: UpperCAmelCase__ = name.replace("layer2_rn", "convs.1" ) if "layer3_rn" in name: UpperCAmelCase__ = name.replace("layer3_rn", "convs.2" ) if "layer4_rn" in name: UpperCAmelCase__ = name.replace("layer4_rn", "convs.3" ) if "refinenet" in name: UpperCAmelCase__ = int(name[len("neck.refinenet" ) : len("neck.refinenet" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 UpperCAmelCase__ = name.replace(f"""refinenet{layer_idx}""", f"""fusion_stage.layers.{abs(layer_idx-4 )}""" ) if "out_conv" in name: UpperCAmelCase__ = name.replace("out_conv", "projection" ) if "resConfUnit1" in name: UpperCAmelCase__ = name.replace("resConfUnit1", "residual_layer1" ) if "resConfUnit2" in name: UpperCAmelCase__ = name.replace("resConfUnit2", "residual_layer2" ) if "conv1" in name: UpperCAmelCase__ = name.replace("conv1", "convolution1" ) if "conv2" in name: UpperCAmelCase__ = name.replace("conv2", "convolution2" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess1.0.project.0", "neck.reassemble_stage.readout_projects.0.0" ) if "pretrained.act_postprocess2.0.project.0" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess2.0.project.0", "neck.reassemble_stage.readout_projects.1.0" ) if "pretrained.act_postprocess3.0.project.0" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess3.0.project.0", "neck.reassemble_stage.readout_projects.2.0" ) if "pretrained.act_postprocess4.0.project.0" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess4.0.project.0", "neck.reassemble_stage.readout_projects.3.0" ) # resize blocks if "pretrained.act_postprocess1.3" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess1.3", "neck.reassemble_stage.layers.0.projection" ) if "pretrained.act_postprocess1.4" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess1.4", "neck.reassemble_stage.layers.0.resize" ) if "pretrained.act_postprocess2.3" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess2.3", "neck.reassemble_stage.layers.1.projection" ) if "pretrained.act_postprocess2.4" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess2.4", "neck.reassemble_stage.layers.1.resize" ) if "pretrained.act_postprocess3.3" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess3.3", "neck.reassemble_stage.layers.2.projection" ) if "pretrained.act_postprocess4.3" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess4.3", "neck.reassemble_stage.layers.3.projection" ) if "pretrained.act_postprocess4.4" in name: UpperCAmelCase__ = name.replace("pretrained.act_postprocess4.4", "neck.reassemble_stage.layers.3.resize" ) if "pretrained" in name: UpperCAmelCase__ = name.replace("pretrained", "dpt" ) if "bn" in name: UpperCAmelCase__ = name.replace("bn", "batch_norm" ) if "head" in name: UpperCAmelCase__ = name.replace("head", "head.head" ) if "encoder.norm" in name: UpperCAmelCase__ = name.replace("encoder.norm", "layernorm" ) if "auxlayer" in name: UpperCAmelCase__ = name.replace("auxlayer", "auxiliary_head.head" ) if "backbone" in name: UpperCAmelCase__ = name.replace("backbone", "backbone.bit.encoder" ) if ".." in name: UpperCAmelCase__ = name.replace("..", "." ) if "stem.conv" in name: UpperCAmelCase__ = name.replace("stem.conv", "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase__ = name.replace("blocks", "layers" ) if "convolution" in name and "backbone" in name: UpperCAmelCase__ = name.replace("convolution", "conv" ) if "layer" in name and "backbone" in name: UpperCAmelCase__ = name.replace("layer", "layers" ) if "backbone.bit.encoder.bit" in name: UpperCAmelCase__ = name.replace("backbone.bit.encoder.bit", "backbone.bit" ) if "embedder.conv" in name: UpperCAmelCase__ = name.replace("embedder.conv", "embedder.convolution" ) if "backbone.bit.encoder.stem.norm" in name: UpperCAmelCase__ = name.replace("backbone.bit.encoder.stem.norm", "backbone.bit.embedder.norm" ) return name def lowerCAmelCase_ ( __A, __A ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase__ = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.weight""" ) UpperCAmelCase__ = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase__ = in_proj_weight[: config.hidden_size, :] UpperCAmelCase__ = in_proj_bias[: config.hidden_size] UpperCAmelCase__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase__ = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase__ = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase__ = Image.open(requests.get(__A, stream=__A ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( __A, __A, __A, __A, __A ) -> Tuple: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ = get_dpt_config(__A ) # load original state_dict from URL # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") UpperCAmelCase__ = torch.load(__A, map_location="cpu" ) # remove certain keys remove_ignore_keys_(__A ) # rename keys for key in state_dict.copy().keys(): UpperCAmelCase__ = state_dict.pop(__A ) UpperCAmelCase__ = val # read in qkv matrices read_in_q_k_v(__A, __A ) # load HuggingFace model UpperCAmelCase__ = DPTForSemanticSegmentation(__A ) if "ade" in checkpoint_url else DPTForDepthEstimation(__A ) model.load_state_dict(__A ) model.eval() # Check outputs on an image UpperCAmelCase__ = 480 if "ade" in checkpoint_url else 384 UpperCAmelCase__ = DPTImageProcessor(size=__A ) UpperCAmelCase__ = prepare_img() UpperCAmelCase__ = image_processor(__A, return_tensors="pt" ) # forward pass UpperCAmelCase__ = model(**__A ).logits if "ade" in checkpoint_url else model(**__A ).predicted_depth if show_prediction: UpperCAmelCase__ = ( torch.nn.functional.interpolate( outputs.unsqueeze(1 ), size=(image.size[1], image.size[0]), mode="bicubic", align_corners=__A, ) .squeeze() .cpu() .numpy() ) Image.fromarray((prediction / prediction.max()) * 255 ).show() if pytorch_dump_folder_path is not None: Path(__A ).mkdir(exist_ok=__A ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(__A ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__A ) if push_to_hub: model.push_to_hub("ybelkada/dpt-hybrid-midas" ) image_processor.push_to_hub("ybelkada/dpt-hybrid-midas" ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt', type=str, help='URL of the original DPT checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=False, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', action='store_true', ) parser.add_argument( '--model_name', default='dpt-large', type=str, help='Name of the model, in case you\'re pushing to the hub.', ) parser.add_argument( '--show_prediction', action='store_true', ) UpperCamelCase__ = parser.parse_args() convert_dpt_checkpoint( args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction )
143
# Lint as: python3 import itertools import os import re UpperCamelCase__ = re.compile(R'([A-Z]+)([A-Z][a-z])') UpperCamelCase__ = re.compile(R'([a-z\d])([A-Z])') UpperCamelCase__ = re.compile(R'(?<!_)_(?!_)') UpperCamelCase__ = re.compile(R'(_{2,})') UpperCamelCase__ = R'^\w+(\.\w+)*$' UpperCamelCase__ = R'<>:/\|?*' def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = _uppercase_uppercase_re.sub(r"\1_\2", __A ) UpperCAmelCase__ = _lowercase_uppercase_re.sub(r"\1_\2", __A ) return name.lower() def lowerCAmelCase_ ( __A ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase__ = _single_underscore_re.split(__A ) UpperCAmelCase__ = [_multiple_underscores_re.split(__A ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(__A ) if n != "" ) def lowerCAmelCase_ ( __A ) -> List[str]: '''simple docstring''' if os.path.basename(__A ) != name: raise ValueError(f"""Should be a dataset name, not a path: {name}""" ) return camelcase_to_snakecase(__A ) def lowerCAmelCase_ ( __A, __A ) -> Optional[int]: '''simple docstring''' if os.path.basename(__A ) != name: raise ValueError(f"""Should be a dataset name, not a path: {name}""" ) if not re.match(_split_re, __A ): raise ValueError(f"""Split name should match '{_split_re}'' but got '{split}'.""" ) return f"""{filename_prefix_for_name(__A )}-{split}""" def lowerCAmelCase_ ( __A, __A, __A, __A=None ) -> str: '''simple docstring''' UpperCAmelCase__ = filename_prefix_for_split(__A, __A ) if filetype_suffix: prefix += f""".{filetype_suffix}""" UpperCAmelCase__ = os.path.join(__A, __A ) return f"""{filepath}*""" def lowerCAmelCase_ ( __A, __A, __A, __A=None, __A=None ) -> Any: '''simple docstring''' UpperCAmelCase__ = filename_prefix_for_split(__A, __A ) UpperCAmelCase__ = os.path.join(__A, __A ) if shard_lengths: UpperCAmelCase__ = len(__A ) UpperCAmelCase__ = [f"""{prefix}-{shard_id:05d}-of-{num_shards:05d}""" for shard_id in range(__A )] if filetype_suffix: UpperCAmelCase__ = [filename + f""".{filetype_suffix}""" for filename in filenames] return filenames else: UpperCAmelCase__ = prefix if filetype_suffix: filename += f""".{filetype_suffix}""" return [filename]
143
1
"""simple docstring""" from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } lowerCAmelCase__ = { '''vocab_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json''' }, '''merges_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt''' }, '''tokenizer_config_file''': { '''facebook/blenderbot_small-90M''': ( '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json''' ) }, } lowerCAmelCase__ = { '''facebook/blenderbot_small-90M''': 512, } class __snake_case ( _lowercase): snake_case__ : List[str] = VOCAB_FILES_NAMES snake_case__ : int = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : List[Any] = BlenderbotSmallTokenizer def __init__( self : List[str] , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Any=None , __lowerCAmelCase : str="<|endoftext|>" , __lowerCAmelCase : List[Any]="<|endoftext|>" , __lowerCAmelCase : Optional[Any]="<|endoftext|>" , __lowerCAmelCase : Tuple=False , __lowerCAmelCase : str=True , **__lowerCAmelCase : List[str] , ): """simple docstring""" super().__init__( ByteLevelBPETokenizer( vocab=__lowerCAmelCase , merges=__lowerCAmelCase , add_prefix_space=__lowerCAmelCase , trim_offsets=__lowerCAmelCase , ) , bos_token=__lowerCAmelCase , eos_token=__lowerCAmelCase , unk_token=__lowerCAmelCase , **__lowerCAmelCase , ) _lowerCamelCase : List[Any] = add_prefix_space def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Any , __lowerCAmelCase : List[str]=None ): """simple docstring""" _lowerCamelCase : Union[str, Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : List[int] , __lowerCAmelCase : Optional[List[int]] = None ): """simple docstring""" _lowerCamelCase : str = [self.sep_token_id] _lowerCamelCase : List[Any] = [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]
72
from __future__ import annotations from collections.abc import Iterator class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Dict , UpperCamelCase__ : int ) -> None: """simple docstring""" __magic_name__ = value __magic_name__ = None __magic_name__ = None class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCamelCase__ : Node ) -> None: """simple docstring""" __magic_name__ = tree def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Node | None ) -> int: """simple docstring""" if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : int ) -> Iterator[int]: """simple docstring""" yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
88
0
'''simple docstring''' import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('''>=''', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType A : List[Any] = get_logger(__name__) def lowerCAmelCase__ ( lowerCamelCase : Union[str, Any] ,lowerCamelCase : str ,lowerCamelCase : List[str] ,lowerCamelCase : Tuple ,lowerCamelCase : Tuple=0 ): os.makedirs(lowerCamelCase ,exist_ok=lowerCamelCase ) with FSDP.state_dict_type( lowerCamelCase ,fsdp_plugin.state_dict_type ,fsdp_plugin.state_dict_config ,fsdp_plugin.optim_state_dict_config ): _A : Optional[Any] = model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: _A : Any = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' _A : List[str] = os.path.join(lowerCamelCase ,lowerCamelCase ) if accelerator.process_index == 0: logger.info(F'Saving model to {output_model_file}' ) torch.save(lowerCamelCase ,lowerCamelCase ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: _A : int = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) _A : List[Any] = os.path.join(lowerCamelCase ,lowerCamelCase ) logger.info(F'Saving model to {output_model_file}' ) torch.save(lowerCamelCase ,lowerCamelCase ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: _A : List[Any] = os.path.join(lowerCamelCase ,F'{MODEL_NAME}_{model_index}' ) os.makedirs(lowerCamelCase ,exist_ok=lowerCamelCase ) logger.info(F'Saving model to {ckpt_dir}' ) _A : List[str] = {'model': state_dict} dist_cp.save_state_dict( state_dict=lowerCamelCase ,storage_writer=dist_cp.FileSystemWriter(lowerCamelCase ) ,planner=DefaultSavePlanner() ,) logger.info(F'Model saved to {ckpt_dir}' ) def lowerCAmelCase__ ( lowerCamelCase : Tuple ,lowerCamelCase : Optional[Any] ,lowerCamelCase : Optional[int] ,lowerCamelCase : Any ,lowerCamelCase : str=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( lowerCamelCase ,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(lowerCamelCase ) != 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 _A : Optional[Any] = F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' _A : Any = os.path.join(lowerCamelCase ,lowerCamelCase ) logger.info(F'Loading model from {input_model_file}' ) _A : Dict = torch.load(lowerCamelCase ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: _A : Dict = ( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) _A : int = os.path.join(lowerCamelCase ,lowerCamelCase ) logger.info(F'Loading model from {input_model_file}' ) _A : Union[str, Any] = torch.load(lowerCamelCase ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: _A : int = ( os.path.join(lowerCamelCase ,F'{MODEL_NAME}_{model_index}' ) if F'{MODEL_NAME}' not in input_dir else input_dir ) logger.info(F'Loading model from {ckpt_dir}' ) _A : Dict = {'model': model.state_dict()} dist_cp.load_state_dict( state_dict=lowerCamelCase ,storage_reader=dist_cp.FileSystemReader(lowerCamelCase ) ,planner=DefaultLoadPlanner() ,) _A : List[str] = state_dict['model'] logger.info(F'Model loaded from {ckpt_dir}' ) model.load_state_dict(lowerCamelCase ) def lowerCAmelCase__ ( lowerCamelCase : Any ,lowerCamelCase : List[Any] ,lowerCamelCase : int ,lowerCamelCase : Tuple ,lowerCamelCase : Union[str, Any] ,lowerCamelCase : Optional[int]=0 ): os.makedirs(lowerCamelCase ,exist_ok=lowerCamelCase ) with FSDP.state_dict_type( lowerCamelCase ,fsdp_plugin.state_dict_type ,fsdp_plugin.state_dict_config ,fsdp_plugin.optim_state_dict_config ): _A : List[str] = FSDP.optim_state_dict(lowerCamelCase ,lowerCamelCase ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: _A : Tuple = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) _A : Optional[int] = os.path.join(lowerCamelCase ,lowerCamelCase ) logger.info(F'Saving Optimizer state to {output_optimizer_file}' ) torch.save(lowerCamelCase ,lowerCamelCase ) logger.info(F'Optimizer state saved in {output_optimizer_file}' ) else: _A : Dict = os.path.join(lowerCamelCase ,F'{OPTIMIZER_NAME}_{optimizer_index}' ) os.makedirs(lowerCamelCase ,exist_ok=lowerCamelCase ) logger.info(F'Saving Optimizer state to {ckpt_dir}' ) dist_cp.save_state_dict( state_dict={'optimizer': optim_state} ,storage_writer=dist_cp.FileSystemWriter(lowerCamelCase ) ,planner=DefaultSavePlanner() ,) logger.info(F'Optimizer state saved in {ckpt_dir}' ) def lowerCAmelCase__ ( lowerCamelCase : List[str] ,lowerCamelCase : List[str] ,lowerCamelCase : List[str] ,lowerCamelCase : Optional[int] ,lowerCamelCase : Union[str, Any] ,lowerCamelCase : int=0 ): accelerator.wait_for_everyone() with FSDP.state_dict_type( lowerCamelCase ,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: _A : Any = 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: _A : int = ( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) _A : int = os.path.join(lowerCamelCase ,lowerCamelCase ) logger.info(F'Loading Optimizer state from {input_optimizer_file}' ) _A : Any = torch.load(lowerCamelCase ) logger.info(F'Optimizer state loaded from {input_optimizer_file}' ) else: _A : List[str] = ( os.path.join(lowerCamelCase ,F'{OPTIMIZER_NAME}_{optimizer_index}' ) if F'{OPTIMIZER_NAME}' not in input_dir else input_dir ) logger.info(F'Loading Optimizer from {ckpt_dir}' ) _A : Union[str, Any] = load_sharded_optimizer_state_dict( model_state_dict=model.state_dict() ,optimizer_key='optimizer' ,storage_reader=dist_cp.FileSystemReader(lowerCamelCase ) ,) _A : Optional[int] = optim_state['optimizer'] logger.info(F'Optimizer loaded from {ckpt_dir}' ) _A : str = FSDP.optim_state_dict_to_load(lowerCamelCase ,lowerCamelCase ,lowerCamelCase ) optimizer.load_state_dict(lowerCamelCase )
350
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional @dataclass class __lowerCamelCase : """simple docstring""" a = field( default="codeparrot/codeparrot" , metadata={"help": "Model name or path of model to be trained."} ) a = field( default="./" , metadata={"help": "Save dir where model repo is cloned and models updates are saved to."} ) a = field( default="codeparrot/codeparrot-clean-train" , metadata={"help": "Name or path of training dataset."} ) a = field( default="codeparrot/codeparrot-clean-valid" , metadata={"help": "Name or path of validation dataset."} ) a = field(default=2 , metadata={"help": "Batch size for training."} ) a = field(default=2 , metadata={"help": "Batch size for evaluation."} ) a = field(default=0.1 , metadata={"help": "Value of weight decay."} ) a = field( default=1_0000 , metadata={"help": "Size of buffer used to shuffle streaming dataset."} ) a = field(default=2E-4 , metadata={"help": "Learning rate fo training."} ) a = field(default="cosine" , metadata={"help": "Learning rate."} ) a = field( default=750 , metadata={"help": "Number of warmup steps in the learning rate schedule."} ) a = field( default=16 , metadata={"help": "Number of gradient accumulation steps."} ) a = field( default=a_ , metadata={"help": "Use gradient checkpointing to reduce memory footprint."} ) a = field(default=5_0000 , metadata={"help": "Maximum number of training steps."} ) a = field( default=-1 , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."} ) a = field(default=1024 , metadata={"help": "Sequence lengths used for training."} ) a = field(default=1 , metadata={"help": "Training seed."} ) a = field( default=1024 , metadata={"help": "Interval to save checkpoints. Measured as number of forward passes not training steps."} , ) a = field( default=a_ , metadata={"help": "States path if the training should continue from a checkpoint folder."} ) a = field(default=a_ , metadata={"help": "If True the data is pretokenized."} ) @dataclass class __lowerCamelCase : """simple docstring""" a = field( default="codeparrot/codeparrot" , metadata={"help": "Model name or path of model to be evaluated."} ) a = field( default="codeparrot/codeparrot-clean-valid" , metadata={"help": "Name or path of validation dataset."} ) a = field(default=2 , metadata={"help": "Batch size used for evaluation."} ) a = field( default=-1 , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."} ) a = field(default=1024 , metadata={"help": "Length of sequences to be evaluated."} ) a = field(default=1 , metadata={"help": "Random seed used for evaluation."} ) @dataclass class __lowerCamelCase : """simple docstring""" a = field( default="codeparrot/codeparrot" , metadata={"help": "Model name or path of model to be evaluated."} ) a = field(default=a_ , metadata={"help": "Number of workers used for code evaluation."} ) a = field( default=a_ , metadata={"help": "The number of human-eval tasks to run. If not included all tasks are evaluated."} , ) a = field( default=a_ , metadata={"help": "Sample from the language model's output distribution."} ) a = field(default=0.2 , metadata={"help": "Sampling temperature used for generation."} ) a = field(default=256 , metadata={"help": "Maximum number of newly generated tokens."} ) a = field(default=0 , metadata={"help": "Top-k parameter used for generation."} ) a = field(default=0.95 , metadata={"help": "Top-p parameter used for nucleus sampling."} ) a = field(default=10 , metadata={"help": "Number of generations to run in parallel."} ) a = field( default=200 , metadata={"help": "Number of completions to generate for each sample."} ) a = field(default=1 , metadata={"help": "Random seed used for evaluation."} ) a = field( default="eval_results.json" , metadata={"help": "Random seed used for evaluation."} ) a = field( default="0" , metadata={"help": "Allow `code_eval` to execute Python code on machine"} ) a = field( default=-1 , metadata={ "help": ( "Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive" " number corresponds to which GPU device id to run on." ) } , ) @dataclass class __lowerCamelCase : """simple docstring""" a = field( default=a_ , metadata={ "help": "The number of CPU cores to use for parallel preprocessing. Default uses the maximum available." } , ) a = field( default="transformersbook/codeparrot" , metadata={"help": "Folder or name of dataset to process."} ) a = field( default="codeparrot-clean" , metadata={"help": "Folder to save processed processed dataset."} ) a = field( default=10_0000 , metadata={"help": "Number of files to save per JSON output file."} ) a = field(default="content" , metadata={"help": "Column containing text data to process."} ) a = field( default=1000 , metadata={"help": "Maximum line length in file, otherwise file is filtered."} ) a = field( default=100 , metadata={"help": "Maximum mean line length in file, otherwise file is filtered."} ) a = field( default=0.25 , metadata={"help": "Maximum fraction of non-alphanumeric characters, otherwise file is filtered."} ) a = field( default=1.5 , metadata={"help": "Minimum character token ratio for the file, otherwise file is filtered."} ) a = field( default=0.7 , metadata={"help": "Probability for filtering config, test and uncommon files."} ) a = field( default="codeparrot/codeparrot" , metadata={"help": "Name or path to the tokenizer."} , ) a = field( default=a_ , metadata={"help": "If True, near-duplicate samples are removed."} ) a = field( default=0.85 , metadata={"help": "Jaccard threshold for near-duplicate samples."} ) @dataclass class __lowerCamelCase : """simple docstring""" a = field( default="gpt2" , metadata={"help": "Base tokenizer to build new tokenizer from."} ) a = field( default="transformersbook/codeparrot-train" , metadata={"help": "Dataset to train tokenizer on."} ) a = field(default="content" , metadata={"help": "Column containing text data to process."} ) a = field(default=20_0000 , metadata={"help": "Number of examples to train tokenizer on."} ) a = field( default=3_2768 , metadata={"help": "Number of examples to train the tokenizer on."} ) a = field(default="codeparrot" , metadata={"help": "Name of new tokenizer."} ) a = field(default=a_ , metadata={"help": "Push saved tokenizer to the hub."} ) @dataclass class __lowerCamelCase : """simple docstring""" a = field( default="codeparrot/codeparrot" , metadata={"help": "Name or path to the tokenizer."} ) a = field( default="codeparrot/codeparrot-clean-train" , metadata={"help": "Name or path to the dataset to pretokenize."} ) a = field( default="tokenized-codeparrot-train" , metadata={"help": "Repo name of the pretokenized data."} ) a = field(default=a_ , metadata={"help": "Number of workers used for code evaluation."} ) @dataclass class __lowerCamelCase : """simple docstring""" a = field( default="gpt2-large" , metadata={"help": "Configuration to use for model initialization."} ) a = field( default="codeparrot/codeparrot" , metadata={"help": "Tokenizer attached to model."} ) a = field(default="codeparrot" , metadata={"help": "Name of the created model."} ) a = field(default=a_ , metadata={"help": "Push saved tokenizer to the hub."} )
227
0
def _UpperCAmelCase (UpperCamelCase__ : int ): _A : Tuple = len(UpperCamelCase__ ) _A : List[str] = sum(UpperCamelCase__ ) _A : Tuple = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): _A : int = True for i in range(1 , s + 1 ): _A : Dict = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): _A : Optional[int] = dp[i][j - 1] if arr[i - 1] <= j: _A : Any = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: _A : Optional[int] = s - 2 * j break return diff
11
from __future__ import annotations from collections.abc import Callable UpperCAmelCase__ = list[list[float | int]] def UpperCAmelCase_ ( __snake_case , __snake_case ) -> Matrix: """simple docstring""" _lowercase =len(__snake_case ) _lowercase =[[0 for _ in range(size + 1 )] for _ in range(__snake_case )] _lowercase =42 _lowercase =42 _lowercase =42 _lowercase =42 _lowercase =42 _lowercase =42 for row in range(__snake_case ): for col in range(__snake_case ): _lowercase =matrix[row][col] _lowercase =vector[row][0] _lowercase =0 _lowercase =0 while row < size and col < size: # pivoting _lowercase =max((abs(augmented[rowa][col] ), rowa) for rowa in range(__snake_case , __snake_case ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: _lowercase , _lowercase =augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __snake_case ): _lowercase =augmented[rowa][col] / augmented[row][col] _lowercase =0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __snake_case ): for row in range(__snake_case ): _lowercase =augmented[row][col] / augmented[col][col] for cola in range(__snake_case , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__snake_case ) ] def UpperCAmelCase_ ( __snake_case ) -> Callable[[int], int]: """simple docstring""" _lowercase =len(__snake_case ) _lowercase =[[0 for _ in range(__snake_case )] for _ in range(__snake_case )] _lowercase =[[0] for _ in range(__snake_case )] _lowercase =42 _lowercase =42 _lowercase =42 _lowercase =42 for x_val, y_val in enumerate(__snake_case ): for col in range(__snake_case ): _lowercase =(x_val + 1) ** (size - col - 1) _lowercase =y_val _lowercase =solve(__snake_case , __snake_case ) def interpolated_func(__snake_case ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__snake_case ) ) return interpolated_func def UpperCAmelCase_ ( __snake_case ) -> int: """simple docstring""" return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def UpperCAmelCase_ ( __snake_case = question_function , __snake_case = 10 ) -> int: """simple docstring""" _lowercase =[func(__snake_case ) for x_val in range(1 , order + 1 )] _lowercase =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] _lowercase =0 _lowercase =42 _lowercase =42 for poly in polynomials: _lowercase =1 while func(__snake_case ) == poly(__snake_case ): x_val += 1 ret += poly(__snake_case ) return ret if __name__ == "__main__": print(f'''{solution() = }''')
5
0
"""simple docstring""" import os from collections.abc import Iterator def _a ( _SCREAMING_SNAKE_CASE = "." ) -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(_SCREAMING_SNAKE_CASE ): snake_case_ = [d for d in dir_names if d != '''scripts''' and d[0] not in '''._'''] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(_SCREAMING_SNAKE_CASE )[1] in (".py", ".ipynb"): yield os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).lstrip("""./""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: return f"""{i * " "}*""" if i else "\n##" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(_SCREAMING_SNAKE_CASE ) or old_parts[i] != new_part) and new_part: print(f"""{md_prefix(_SCREAMING_SNAKE_CASE )} {new_part.replace("_" , " " ).title()}""" ) return new_path def _a ( _SCREAMING_SNAKE_CASE = "." ) -> None: snake_case_ = '''''' for filepath in sorted(good_file_paths(_SCREAMING_SNAKE_CASE ) ): snake_case_ = os.path.split(_SCREAMING_SNAKE_CASE ) if filepath != old_path: snake_case_ = print_path(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = (filepath.count(os.sep ) + 1) if filepath else 0 snake_case_ = f"""{filepath}/{filename}""".replace(""" """ , """%20""" ) snake_case_ = os.path.splitext(filename.replace("""_""" , """ """ ).title() )[0] print(f"""{md_prefix(_SCREAMING_SNAKE_CASE )} [{filename}]({url})""" ) if __name__ == "__main__": print_directory_md('.')
361
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = { 'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json', # See all CANINE models at https://huggingface.co/models?filter=canine } class __A (snake_case__): '''simple docstring''' __lowercase: List[str] = """canine""" def __init__( self : Union[str, Any] , UpperCAmelCase_ : str=768 , UpperCAmelCase_ : Union[str, Any]=12 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Optional[Any]=3_072 , UpperCAmelCase_ : List[Any]="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Any=0.1 , UpperCAmelCase_ : List[str]=16_384 , UpperCAmelCase_ : Tuple=16 , UpperCAmelCase_ : int=0.02 , UpperCAmelCase_ : Tuple=1E-12 , UpperCAmelCase_ : str=0 , UpperCAmelCase_ : int=0XE000 , UpperCAmelCase_ : Optional[int]=0XE001 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : List[Any]=4 , UpperCAmelCase_ : List[Any]=8 , UpperCAmelCase_ : Dict=16_384 , UpperCAmelCase_ : Optional[int]=128 , **UpperCAmelCase_ : Any , ) ->int: """simple docstring""" super().__init__(pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps # Character config: snake_case_ = downsampling_rate snake_case_ = upsampling_kernel_size snake_case_ = num_hash_functions snake_case_ = num_hash_buckets snake_case_ = local_transformer_stride
233
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = { "bigcode/gpt_bigcode-santacoder": "https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json", } class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = "gpt_bigcode" lowercase = ["past_key_values"] lowercase = { "hidden_size": "n_embd", "max_position_embeddings": "n_positions", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[str] , snake_case_ : str=50_257 , snake_case_ : Tuple=1_024 , snake_case_ : Union[str, Any]=768 , snake_case_ : List[Any]=12 , snake_case_ : Optional[int]=12 , snake_case_ : Dict=None , snake_case_ : Optional[Any]="gelu_pytorch_tanh" , snake_case_ : Dict=0.1 , snake_case_ : int=0.1 , snake_case_ : Optional[Any]=0.1 , snake_case_ : Dict=1E-5 , snake_case_ : Optional[int]=0.02 , snake_case_ : Dict=True , snake_case_ : List[str]=True , snake_case_ : Optional[Any]=50_256 , snake_case_ : Any=50_256 , snake_case_ : List[str]=True , snake_case_ : Optional[Any]=True , snake_case_ : Any=True , **snake_case_ : int , ): snake_case__ : Optional[Any] = vocab_size snake_case__ : Tuple = n_positions snake_case__ : Any = n_embd snake_case__ : List[str] = n_layer snake_case__ : Union[str, Any] = n_head snake_case__ : Optional[int] = n_inner snake_case__ : Any = activation_function snake_case__ : List[Any] = resid_pdrop snake_case__ : Tuple = embd_pdrop snake_case__ : Tuple = attn_pdrop snake_case__ : Optional[int] = layer_norm_epsilon snake_case__ : Dict = initializer_range snake_case__ : Dict = scale_attn_weights snake_case__ : Optional[Any] = use_cache snake_case__ : str = attention_softmax_in_fpaa snake_case__ : List[Any] = scale_attention_softmax_in_fpaa snake_case__ : Tuple = multi_query snake_case__ : Optional[int] = bos_token_id snake_case__ : int = eos_token_id super().__init__(bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ )
35
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) _snake_case : Any = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation="relu") ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation="relu")) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation="relu")) classifier.add(layers.Dense(units=1, activation="sigmoid")) # Compiling the CNN classifier.compile( optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') _snake_case : int = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) _snake_case : Optional[Any] = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) _snake_case : List[str] = train_datagen.flow_from_directory( "dataset/training_set", target_size=(64, 64), batch_size=32, class_mode="binary" ) _snake_case : Any = test_datagen.flow_from_directory( "dataset/test_set", target_size=(64, 64), batch_size=32, class_mode="binary" ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save("cnn.h5") # Part 3 - Making new predictions _snake_case : Optional[Any] = tf.keras.preprocessing.image.load_img( "dataset/single_prediction/image.png", target_size=(64, 64) ) _snake_case : int = tf.keras.preprocessing.image.img_to_array(test_image) _snake_case : Tuple = np.expand_dims(test_image, axis=0) _snake_case : Any = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: _snake_case : Any = "Normal" if result[0][0] == 1: _snake_case : List[str] = "Abnormality detected"
123
0
'''simple docstring''' import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase_ : List[Any] = logging.get_logger(__name__) UpperCamelCase_ : int = [ ['''attention''', '''attn'''], ['''encoder_attention''', '''encoder_attn'''], ['''q_lin''', '''q_proj'''], ['''k_lin''', '''k_proj'''], ['''v_lin''', '''v_proj'''], ['''out_lin''', '''out_proj'''], ['''norm_embeddings''', '''layernorm_embedding'''], ['''position_embeddings''', '''embed_positions'''], ['''embeddings''', '''embed_tokens'''], ['''ffn.lin''', '''fc'''], ] def __a ( _UpperCamelCase: List[str] ) -> Optional[int]: """simple docstring""" if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: _snake_case = k.replace(_lowerCAmelCase , _lowerCAmelCase ) if k.startswith("encoder" ): _snake_case = k.replace(".attn" , ".self_attn" ) _snake_case = k.replace("norm1" , "self_attn_layer_norm" ) _snake_case = k.replace("norm2" , "final_layer_norm" ) elif k.startswith("decoder" ): _snake_case = k.replace("norm1" , "self_attn_layer_norm" ) _snake_case = k.replace("norm2" , "encoder_attn_layer_norm" ) _snake_case = k.replace("norm3" , "final_layer_norm" ) return k def __a ( _UpperCamelCase: Optional[int] ) -> int: """simple docstring""" _snake_case = [ "model.encoder.layernorm_embedding.weight", "model.encoder.layernorm_embedding.bias", "model.decoder.layernorm_embedding.weight", "model.decoder.layernorm_embedding.bias", ] for k in keys: _snake_case = sd.pop(_lowerCAmelCase ) _snake_case = k.replace("layernorm_embedding" , "layer_norm" ) assert new_k not in sd _snake_case = v UpperCamelCase_ : List[Any] = ['''START'''] @torch.no_grad() def __a ( _UpperCamelCase: Optional[Any] , _UpperCamelCase: Any , _UpperCamelCase: Optional[int] ) -> List[str]: """simple docstring""" _snake_case = torch.load(_lowerCAmelCase , map_location="cpu" ) _snake_case = model["model"] _snake_case = BlenderbotConfig.from_json_file(_lowerCAmelCase ) _snake_case = BlenderbotForConditionalGeneration(_lowerCAmelCase ) _snake_case = m.model.state_dict().keys() _snake_case = [] _snake_case = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue _snake_case = rename_state_dict_key(_lowerCAmelCase ) if new_k not in valid_keys: failures.append([k, new_k] ) else: _snake_case = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(_lowerCAmelCase ) m.model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) m.half() m.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": UpperCamelCase_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument('''--src_path''', type=str, help='''like blenderbot-model.bin''') parser.add_argument('''--save_dir''', default='''hf_blenderbot''', type=str, help='''Where to save converted model.''') parser.add_argument( '''--hf_config_json''', default='''blenderbot-3b-config.json''', type=str, help='''Path to config to use''' ) UpperCamelCase_ : List[Any] = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
354
'''simple docstring''' # Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_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_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) UpperCamelCase_ : int = '''pytorch_model.bin''' UpperCamelCase_ : str = '''pytorch_model.bin.index.json''' UpperCamelCase_ : int = '''adapter_config.json''' UpperCamelCase_ : str = '''adapter_model.bin''' UpperCamelCase_ : str = '''adapter_model.safetensors''' UpperCamelCase_ : List[Any] = '''tf_model.h5''' UpperCamelCase_ : Union[str, Any] = '''tf_model.h5.index.json''' UpperCamelCase_ : Tuple = '''model.ckpt''' UpperCamelCase_ : Union[str, Any] = '''flax_model.msgpack''' UpperCamelCase_ : Union[str, Any] = '''flax_model.msgpack.index.json''' UpperCamelCase_ : Dict = '''model.safetensors''' UpperCamelCase_ : List[Any] = '''model.safetensors.index.json''' UpperCamelCase_ : Tuple = '''config.json''' UpperCamelCase_ : List[str] = '''preprocessor_config.json''' UpperCamelCase_ : List[Any] = FEATURE_EXTRACTOR_NAME UpperCamelCase_ : Union[str, Any] = '''generation_config.json''' UpperCamelCase_ : str = '''modelcard.json''' UpperCamelCase_ : List[Any] = '''▁''' UpperCamelCase_ : Tuple = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility UpperCamelCase_ : Any = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. UpperCamelCase_ : Tuple = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] UpperCamelCase_ : str = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def __a ( _UpperCamelCase: Optional[Any] ) -> int: """simple docstring""" if version.parse(_UpperCamelCase ) < version.parse(_UpperCamelCase ): if "dev" in min_version: _snake_case = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: _snake_case = F"""This example requires a minimum version of {min_version},""" error_message += F""" but the version found is {__version__}.\n""" raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
142
0
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( '''pipelines_utils''', '''0.22.0''', '''Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.''', standard_warn=False, stacklevel=3, )
143
import random from .binary_exp_mod import bin_exp_mod def UpperCamelCase__ ( A__ , A__=1000 ) -> Optional[int]: if n < 2: return False if n % 2 == 0: return n == 2 # this means n is odd snake_case__ : List[Any] = n - 1 snake_case__ : Optional[int] = 0 while d % 2 == 0: d /= 2 exp += 1 # n - 1=d*(2**exp) snake_case__ : Union[str, Any] = 0 while count < prec: snake_case__ : Dict = random.randint(2 , n - 1 ) snake_case__ : Dict = bin_exp_mod(A__ , A__ , A__ ) if b != 1: snake_case__ : Tuple = True for _ in range(A__ ): if b == n - 1: snake_case__ : List[str] = False break snake_case__ : Dict = b * b b %= n if flag: return False count += 1 return True if __name__ == "__main__": lowerCAmelCase__ : str = abs(int(input('''Enter bound : ''').strip())) print('''Here\'s the list of primes:''') print(''', '''.join(str(i) for i in range(n + 1) if is_prime_big(i)))
143
1
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path _lowerCAmelCase : Tuple = '''src/transformers''' # Matches is_xxx_available() _lowerCAmelCase : str = re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowerCAmelCase : Tuple = re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowerCAmelCase : Union[str, Any] = re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowerCAmelCase : Optional[int] = re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowerCAmelCase : Any = re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowerCAmelCase : Any = re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowerCAmelCase : List[str] = re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowerCAmelCase : List[str] = re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowerCAmelCase : Union[str, Any] = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowerCAmelCase : List[Any] = re.compile(R'''^\s*try:''') # Catches a line with else: _lowerCAmelCase : int = re.compile(R'''^\s*else:''') def lowerCamelCase_( _lowerCamelCase ) -> Dict: '''simple docstring''' if _re_test_backend.search(_lowerCamelCase ) is None: return None _lowerCamelCase : Dict = [b[0] for b in _re_backend.findall(_lowerCamelCase )] backends.sort() return "_and_".join(_lowerCamelCase ) def lowerCamelCase_( _lowerCamelCase ) -> List[Any]: '''simple docstring''' with open(_lowerCamelCase , "r" , encoding="utf-8" , newline="\n" ) as f: _lowerCamelCase : str = f.readlines() _lowerCamelCase : int = 0 while line_index < len(_lowerCamelCase ) and not lines[line_index].startswith("_import_structure = {" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(_lowerCamelCase ): return None # First grab the objects without a specific backend in _import_structure _lowerCamelCase : List[Any] = [] while not lines[line_index].startswith("if TYPE_CHECKING" ) and find_backend(lines[line_index] ) is None: _lowerCamelCase : str = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(_lowerCamelCase ): _lowerCamelCase : List[Any] = _re_one_line_import_struct.search(_lowerCamelCase ).groups()[0] _lowerCamelCase : Optional[Any] = re.findall("\[([^\]]+)\]" , _lowerCamelCase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", " )] ) line_index += 1 continue _lowerCamelCase : Optional[int] = _re_import_struct_key_value.search(_lowerCamelCase ) if single_line_import_search is not None: _lowerCamelCase : List[Any] = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", " ) if len(_lowerCamelCase ) > 0] objects.extend(_lowerCamelCase ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) line_index += 1 _lowerCamelCase : Any = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING" ): # If the line is an if not is_backend_available, we grab all objects associated. _lowerCamelCase : Tuple = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _lowerCamelCase : Any = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _lowerCamelCase : List[str] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 4 ): _lowerCamelCase : Dict = lines[line_index] if _re_import_struct_add_one.search(_lowerCamelCase ) is not None: objects.append(_re_import_struct_add_one.search(_lowerCamelCase ).groups()[0] ) elif _re_import_struct_add_many.search(_lowerCamelCase ) is not None: _lowerCamelCase : Optional[int] = _re_import_struct_add_many.search(_lowerCamelCase ).groups()[0].split(", " ) _lowerCamelCase : List[Any] = [obj[1:-1] for obj in imports if len(_lowerCamelCase ) > 0] objects.extend(_lowerCamelCase ) elif _re_between_brackets.search(_lowerCamelCase ) is not None: _lowerCamelCase : List[str] = _re_between_brackets.search(_lowerCamelCase ).groups()[0].split(", " ) _lowerCamelCase : List[Any] = [obj[1:-1] for obj in imports if len(_lowerCamelCase ) > 0] objects.extend(_lowerCamelCase ) elif _re_quote_object.search(_lowerCamelCase ) is not None: objects.append(_re_quote_object.search(_lowerCamelCase ).groups()[0] ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) elif line.startswith(" " * 12 + "\"" ): objects.append(line[13:-3] ) line_index += 1 _lowerCamelCase : Any = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend _lowerCamelCase : str = [] while ( line_index < len(_lowerCamelCase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("else" ) ): _lowerCamelCase : Tuple = lines[line_index] _lowerCamelCase : Tuple = _re_import.search(_lowerCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 _lowerCamelCase : Optional[int] = {"none": objects} # Let's continue with backend-specific objects while line_index < len(_lowerCamelCase ): # If the line is an if is_backend_available, we grab all objects associated. _lowerCamelCase : List[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _lowerCamelCase : Optional[Any] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _lowerCamelCase : List[str] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 8 ): _lowerCamelCase : Optional[Any] = lines[line_index] _lowerCamelCase : List[str] = _re_import.search(_lowerCamelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 12 ): objects.append(line[12:-2] ) line_index += 1 _lowerCamelCase : int = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowerCamelCase_( _lowerCamelCase , _lowerCamelCase ) -> Tuple: '''simple docstring''' def find_duplicates(_lowerCamelCase ): return [k for k, v in collections.Counter(_lowerCamelCase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] _lowerCamelCase : Dict = [] for key in import_dict_objects.keys(): _lowerCamelCase : Union[str, Any] = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F"""Duplicate _import_structure definitions for: {duplicate_imports}""" ) _lowerCamelCase : List[str] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}""" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): _lowerCamelCase : int = "base imports" if key == "none" else F"""{key} backend""" errors.append(F"""Differences for {name}:""" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F""" {a} in TYPE_HINT but not in _import_structure.""" ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F""" {a} in _import_structure but not in TYPE_HINT.""" ) return errors def lowerCamelCase_( ) -> Optional[Any]: '''simple docstring''' _lowerCamelCase : Tuple = [] for root, _, files in os.walk(_lowerCamelCase ): if "__init__.py" in files: _lowerCamelCase : List[Any] = os.path.join(_lowerCamelCase , "__init__.py" ) _lowerCamelCase : List[Any] = parse_init(_lowerCamelCase ) if objects is not None: _lowerCamelCase : Union[str, Any] = analyze_results(*_lowerCamelCase ) if len(_lowerCamelCase ) > 0: _lowerCamelCase : str = F"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}""" failures.append("\n".join(_lowerCamelCase ) ) if len(_lowerCamelCase ) > 0: raise ValueError("\n\n".join(_lowerCamelCase ) ) def lowerCamelCase_( ) -> Union[str, Any]: '''simple docstring''' _lowerCamelCase : Dict = [] for path, directories, files in os.walk(_lowerCamelCase ): for folder in directories: # Ignore private modules if folder.startswith("_" ): directories.remove(_lowerCamelCase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(_lowerCamelCase ) / folder).glob("*.py" ) ) ) == 0: continue _lowerCamelCase : Optional[Any] = str((Path(_lowerCamelCase ) / folder).relative_to(_lowerCamelCase ) ) _lowerCamelCase : List[Any] = short_path.replace(os.path.sep , "." ) submodules.append(_lowerCamelCase ) for fname in files: if fname == "__init__.py": continue _lowerCamelCase : Any = str((Path(_lowerCamelCase ) / fname).relative_to(_lowerCamelCase ) ) _lowerCamelCase : Tuple = short_path.replace(".py" , "" ).replace(os.path.sep , "." ) if len(submodule.split("." ) ) == 1: submodules.append(_lowerCamelCase ) return submodules _lowerCAmelCase : Optional[int] = [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def lowerCamelCase_( ) -> Optional[int]: '''simple docstring''' _lowerCamelCase : Tuple = importlib.util.spec_from_file_location( "transformers" , os.path.join(_lowerCamelCase , "__init__.py" ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) _lowerCamelCase : List[str] = spec.loader.load_module() _lowerCamelCase : Tuple = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(_lowerCamelCase ) > 0: _lowerCamelCase : List[str] = "\n".join(F"""- {module}""" for module in module_not_registered ) raise ValueError( "The following submodules are not properly registered in the main init of Transformers:\n" F"""{list_of_modules}\n""" "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": check_all_inits() check_submodules()
365
"""simple docstring""" import logging from transformers.configuration_utils import PretrainedConfig _lowerCAmelCase : Optional[Any] = logging.getLogger(__name__) class A_ ( _a ): lowerCAmelCase__ = 'masked_bert' def __init__( self: Union[str, Any] ,__lowerCAmelCase: Dict=30_522 ,__lowerCAmelCase: Optional[int]=768 ,__lowerCAmelCase: Dict=12 ,__lowerCAmelCase: List[Any]=12 ,__lowerCAmelCase: List[Any]=3_072 ,__lowerCAmelCase: List[Any]="gelu" ,__lowerCAmelCase: Union[str, Any]=0.1 ,__lowerCAmelCase: List[str]=0.1 ,__lowerCAmelCase: Tuple=512 ,__lowerCAmelCase: str=2 ,__lowerCAmelCase: Tuple=0.02 ,__lowerCAmelCase: Union[str, Any]=1e-12 ,__lowerCAmelCase: Union[str, Any]=0 ,__lowerCAmelCase: List[Any]="topK" ,__lowerCAmelCase: Optional[Any]="constant" ,__lowerCAmelCase: Optional[Any]=0.0 ,**__lowerCAmelCase: str ,): '''simple docstring''' super().__init__(pad_token_id=__lowerCAmelCase ,**__lowerCAmelCase ) _lowerCamelCase : List[Any] = vocab_size _lowerCamelCase : Optional[Any] = hidden_size _lowerCamelCase : Tuple = num_hidden_layers _lowerCamelCase : Tuple = num_attention_heads _lowerCamelCase : Optional[Any] = hidden_act _lowerCamelCase : Optional[Any] = intermediate_size _lowerCamelCase : str = hidden_dropout_prob _lowerCamelCase : Union[str, Any] = attention_probs_dropout_prob _lowerCamelCase : str = max_position_embeddings _lowerCamelCase : List[str] = type_vocab_size _lowerCamelCase : Optional[int] = initializer_range _lowerCamelCase : List[Any] = layer_norm_eps _lowerCamelCase : int = pruning_method _lowerCamelCase : str = mask_init _lowerCamelCase : List[Any] = mask_scale
340
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch a : Dict = logging.get_logger(__name__) @dataclass class __UpperCamelCase : def __init__( self , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=6.0 , lowerCAmelCase__=None , lowerCAmelCase__=False , lowerCAmelCase__=False , lowerCAmelCase__=None , lowerCAmelCase__="fp4" , lowerCAmelCase__=False , **lowerCAmelCase__ , ) -> Any: a : Tuple = load_in_abit a : Optional[int] = load_in_abit a : List[str] = llm_inta_threshold a : List[Any] = llm_inta_skip_modules a : Union[str, Any] = llm_inta_enable_fpaa_cpu_offload a : Optional[int] = llm_inta_has_fpaa_weight a : Optional[Any] = bnb_abit_quant_type a : Union[str, Any] = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: a : str = torch.floataa elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): a : Optional[int] = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) elif isinstance(lowerCAmelCase__ , torch.dtype ): a : List[Any] = bnb_abit_compute_dtype else: raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype" ) self.post_init() def __a ( self ) -> int: if not isinstance(self.llm_inta_threshold , lowerCAmelCase__ ): raise ValueError("llm_int8_threshold must be a float" ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , lowerCAmelCase__ ): raise ValueError("llm_int8_skip_modules must be a list of strings" ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , lowerCAmelCase__ ): raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean" ) if not isinstance(self.llm_inta_has_fpaa_weight , lowerCAmelCase__ ): raise ValueError("llm_int8_has_fp16_weight must be a boolean" ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError("bnb_4bit_compute_dtype must be torch.dtype" ) if not isinstance(self.bnb_abit_quant_type , lowerCAmelCase__ ): raise ValueError("bnb_4bit_quant_type must be a string" ) if not isinstance(self.bnb_abit_use_double_quant , lowerCAmelCase__ ): raise ValueError("bnb_4bit_use_double_quant must be a boolean" ) if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes" ) ) >= version.parse( "0.39.0" ): raise ValueError( "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version" ) def __a ( self ) -> Tuple: return self.load_in_abit or self.load_in_abit def __a ( self ) -> Any: if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def __a ( cls , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) -> str: a : List[Any] = cls(**lowerCAmelCase__ ) a : Optional[int] = [] for key, value in kwargs.items(): if hasattr(lowerCAmelCase__ , lowerCAmelCase__ ): setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) to_remove.append(lowerCAmelCase__ ) for key in to_remove: kwargs.pop(lowerCAmelCase__ , lowerCAmelCase__ ) if return_unused_kwargs: return config, kwargs else: return config def __a ( self , lowerCAmelCase__ ) -> int: with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as writer: a : List[str] = self.to_dict() a : Tuple = json.dumps(lowerCAmelCase__ , indent=2 , sort_keys=lowerCAmelCase__ ) + "\n" writer.write(lowerCAmelCase__ ) def __a ( self ) -> Dict[str, Any]: a : Tuple = copy.deepcopy(self.__dict__ ) a : Dict = str(output["bnb_4bit_compute_dtype"] ).split("." )[1] return output def __repr__( self ) -> List[str]: return f"""{self.__class__.__name__} {self.to_json_string()}""" def __a ( self , lowerCAmelCase__ = True ) -> str: if use_diff is True: a : List[Any] = self.to_diff_dict() else: a : Dict = self.to_dict() return json.dumps(lowerCAmelCase__ , indent=2 , sort_keys=lowerCAmelCase__ ) + "\n" def __a ( self ) -> Dict[str, Any]: a : str = self.to_dict() # get the default config dict a : Tuple = BitsAndBytesConfig().to_dict() a : List[Any] = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: a : Any = value return serializable_config_dict
105
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class _lowercase ( lowerCAmelCase ): """simple docstring""" __A = 42 __A = None def a( A : Optional[Any] , A : Any=0.999 , A : Dict="cosine" , ) -> Optional[int]: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(A : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(A : Any ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) a = [] for i in range(A ): a = i / num_diffusion_timesteps a = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(A ) / alpha_bar_fn(A ) , A ) ) return torch.tensor(A , dtype=torch.floataa ) class _lowercase ( lowerCAmelCase, lowerCAmelCase ): """simple docstring""" __A = 1 @register_to_config def __init__(self , lowerCamelCase_ = 1000 , lowerCamelCase_ = 0.0001 , lowerCamelCase_ = 0.02 , lowerCamelCase_ = "linear" , lowerCamelCase_ = None , lowerCamelCase_ = True , lowerCamelCase_ = True , lowerCamelCase_ = 0 , lowerCamelCase_ = "epsilon" , lowerCamelCase_ = 1.0 , **lowerCamelCase_ , ): """simple docstring""" if kwargs.get("set_alpha_to_one" , lowerCamelCase_ ) is not None: a = ( "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead." ) deprecate("set_alpha_to_one" , "1.0.0" , lowerCamelCase_ , standard_warn=lowerCamelCase_ ) a = kwargs["set_alpha_to_one"] if trained_betas is not None: a = torch.tensor(lowerCamelCase_ , dtype=torch.floataa ) elif beta_schedule == "linear": a = torch.linspace(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. a = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCamelCase_ , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule a = betas_for_alpha_bar(lowerCamelCase_ ) else: raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}''' ) a = 1.0 - self.betas a = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. a = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution a = 1.0 # setable values a = None a = torch.from_numpy(np.arange(0 , lowerCamelCase_ ).copy().astype(np.intaa ) ) def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ = None ): """simple docstring""" return sample def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ = None ): """simple docstring""" if num_inference_steps > self.config.num_train_timesteps: raise ValueError( F'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' F''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' F''' maximal {self.config.num_train_timesteps} timesteps.''' ) a = num_inference_steps a = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 a = (np.arange(0 , lowerCamelCase_ ) * step_ratio).round().copy().astype(np.intaa ) a = torch.from_numpy(lowerCamelCase_ ).to(lowerCamelCase_ ) self.timesteps += self.config.steps_offset def UpperCamelCase_ (self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 0.0 , lowerCamelCase_ = False , lowerCamelCase_ = None , lowerCamelCase_ = True , ): """simple docstring""" a = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process a = self.alphas_cumprod[timestep] a = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) a = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 a = model_output elif self.config.prediction_type == "sample": a = model_output a = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": a = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output a = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' " `v_prediction`" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: a = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=lowerCamelCase_ , pred_original_sample=lowerCamelCase_ ) def __len__(self ): """simple docstring""" return self.config.num_train_timesteps
227
0
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def lowerCAmelCase_ ( ) -> Any: raise RuntimeError('''CUDA out of memory.''' ) class lowercase__ ( nn.Module ): '''simple docstring''' def __init__( self ) -> Union[str, Any]: """simple docstring""" super().__init__() UpperCamelCase__ : Optional[int] = nn.Linear(3, 4 ) UpperCamelCase__ : int = nn.BatchNormad(4 ) UpperCamelCase__ : str = nn.Linear(4, 5 ) def UpperCamelCase__ ( self, __magic_name__ ) -> Tuple: """simple docstring""" return self.lineara(self.batchnorm(self.lineara(__magic_name__ ) ) ) class lowercase__ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" UpperCamelCase__ : Optional[Any] = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__magic_name__ ): nonlocal batch_sizes batch_sizes.append(__magic_name__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(__magic_name__, [128, 64, 32, 16, 8] ) def UpperCamelCase__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase__ : List[Any] = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__magic_name__, __magic_name__ ): nonlocal batch_sizes batch_sizes.append(__magic_name__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga UpperCamelCase__ ,UpperCamelCase__ : int = mock_training_loop_function('''hello''' ) self.assertListEqual(__magic_name__, [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga], [8, '''hello'''] ) def UpperCamelCase__ ( self ) -> Tuple: """simple docstring""" @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(__magic_name__ ): pass with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''', cm.exception.args[0] ) def UpperCamelCase__ ( self ) -> str: """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(__magic_name__ ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''', cm.exception.args[0] ) def UpperCamelCase__ ( self ) -> Optional[int]: """simple docstring""" @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__magic_name__, __magic_name__, __magic_name__ ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function(128, '''hello''', '''world''' ) self.assertIn('''Batch size was passed into `f`''', cm.exception.args[0] ) self.assertIn('''`f(arg1=\'hello\', arg2=\'world\')''', cm.exception.args[0] ) def UpperCamelCase__ ( self ) -> Dict: """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(__magic_name__ ): raise ValueError('''Oops, we had an error!''' ) with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function() self.assertIn('''Oops, we had an error!''', cm.exception.args[0] ) @require_cuda def UpperCamelCase__ ( self ) -> Union[str, Any]: """simple docstring""" UpperCamelCase__ : Any = torch.cuda.memory_allocated() UpperCamelCase__ : Union[str, Any] = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated(), __magic_name__ ) UpperCamelCase__ : Tuple = release_memory(__magic_name__ ) self.assertEqual(torch.cuda.memory_allocated(), __magic_name__ )
247
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer UpperCAmelCase_ = logging.getLogger(__name__) def lowerCAmelCase_ ( ) -> Any: UpperCamelCase__ : Dict = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=__UpperCAmelCase , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=__UpperCAmelCase , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=__UpperCAmelCase , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=__UpperCAmelCase , default=1000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=__UpperCAmelCase , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=__UpperCAmelCase , type=__UpperCAmelCase , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=__UpperCAmelCase , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=__UpperCAmelCase , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) UpperCamelCase__ : Any = parser.parse_args() return args def lowerCAmelCase_ ( __UpperCAmelCase: Tuple ) -> Any: def fn(__UpperCAmelCase: Dict ): return tokenizer(examples['''text'''] ) return fn def lowerCAmelCase_ ( __UpperCAmelCase: int ) -> Dict: UpperCamelCase__ : Optional[int] = [] for i in range(len(tokenized_data['''input_ids'''] ) ): UpperCamelCase__ : Dict = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } UpperCamelCase__ : int = tf.train.Features(feature=__UpperCAmelCase ) UpperCamelCase__ : Tuple = tf.train.Example(features=__UpperCAmelCase ) UpperCamelCase__ : List[Any] = example.SerializeToString() records.append(__UpperCAmelCase ) return records def lowerCAmelCase_ ( __UpperCAmelCase: Tuple ) -> int: UpperCamelCase__ : str = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: UpperCamelCase__ : int = min(len(__UpperCAmelCase ) , args.limit ) UpperCamelCase__ : Optional[int] = dataset.select(range(__UpperCAmelCase ) ) print(f"Limiting the dataset to {args.limit} entries." ) UpperCamelCase__ : Tuple = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) UpperCamelCase__ : Dict = os.path.join(args.output_dir , args.split ) if not os.path.exists(__UpperCAmelCase ): os.makedirs(__UpperCAmelCase ) else: UpperCamelCase__ : Tuple = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. UpperCamelCase__ : Optional[int] = tokenize_function(__UpperCAmelCase ) UpperCamelCase__ : Optional[int] = dataset.map(__UpperCAmelCase , batched=__UpperCAmelCase , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__UpperCAmelCase: Optional[Any] ): # Concatenate all texts. UpperCamelCase__ : int = {k: sum(examples[k] , [] ) for k in examples.keys()} UpperCamelCase__ : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 UpperCamelCase__ : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. UpperCamelCase__ : Dict = { k: [t[i : i + args.max_length] for i in range(0 , __UpperCAmelCase , args.max_length )] for k, t in concatenated_examples.items() } return result UpperCamelCase__ : Optional[Any] = dataset_tokenized.map(__UpperCAmelCase , batched=__UpperCAmelCase , batch_size=1000 , num_proc=4 ) UpperCamelCase__ : Optional[int] = 0 UpperCamelCase__ : Optional[Any] = 0 for shard in range(0 , len(__UpperCAmelCase ) , args.shard_size ): UpperCamelCase__ : Optional[int] = grouped_dataset[shard : shard + args.shard_size] UpperCamelCase__ : Any = len(dataset_snapshot['''input_ids'''] ) UpperCamelCase__ : Optional[int] = os.path.join(__UpperCAmelCase , f"dataset-{shard_count}-{records_containing}.tfrecord" ) UpperCamelCase__ : List[str] = get_serialized_examples(__UpperCAmelCase ) with tf.io.TFRecordWriter(__UpperCAmelCase ) as out_file: for i in range(len(__UpperCAmelCase ) ): UpperCamelCase__ : str = serialized_examples[i] out_file.write(__UpperCAmelCase ) print('''Wrote file {} containing {} records'''.format(__UpperCAmelCase , __UpperCAmelCase ) ) shard_count += 1 total_records += records_containing with open(f"split-{args.split}-records-count.txt" , '''w''' ) as f: print(f"Total {args.split} records: {total_records}" , file=__UpperCAmelCase ) if __name__ == "__main__": UpperCAmelCase_ = parse_args() main(args)
247
1
'''simple docstring''' def snake_case_ ( __SCREAMING_SNAKE_CASE : int = 1000 ): """simple docstring""" lowercase_ , lowercase_ : Optional[int] = 1, 1 lowercase_ : int = 2 while True: lowercase_ : List[Any] = 0 lowercase_ : int = fa + fa lowercase_ , lowercase_ : Tuple = fa, f index += 1 for _ in str(__SCREAMING_SNAKE_CASE ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
93
from __future__ import annotations import math lowerCamelCase : List[Any] = '''2020.9.26''' lowerCamelCase : str = '''xcodz-dot, cclaus, dhruvmanila''' def snake_case_ ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float ): if not all(isinstance(lowerCAmelCase_ , (float, int) ) for val in locals().values() ): __lowercase : str = F"Input values must either be float or int: {list(locals().values() )}" raise TypeError(lowerCAmelCase_ ) __lowercase : List[Any] = ((x * distance) / (z + distance)) * scale __lowercase : Tuple = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def snake_case_ ( lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : float , lowerCAmelCase_ : str , lowerCAmelCase_ : float ): if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("""Axis must be a str""" ) __lowercase : Optional[int] = locals() del input_variables["axis"] if not all(isinstance(lowerCAmelCase_ , (float, int) ) for val in input_variables.values() ): __lowercase : List[str] = ( """Input values except axis must either be float or int: """ F"{list(input_variables.values() )}" ) raise TypeError(lowerCAmelCase_ ) __lowercase : Tuple = (angle % 360) / 450 * 180 / math.pi if axis == "z": __lowercase : int = x * math.cos(lowerCAmelCase_ ) - y * math.sin(lowerCAmelCase_ ) __lowercase : Tuple = y * math.cos(lowerCAmelCase_ ) + x * math.sin(lowerCAmelCase_ ) __lowercase : Union[str, Any] = z elif axis == "x": __lowercase : str = y * math.cos(lowerCAmelCase_ ) - z * math.sin(lowerCAmelCase_ ) __lowercase : Dict = z * math.cos(lowerCAmelCase_ ) + y * math.sin(lowerCAmelCase_ ) __lowercase : List[str] = x elif axis == "y": __lowercase : List[str] = x * math.cos(lowerCAmelCase_ ) - z * math.sin(lowerCAmelCase_ ) __lowercase : List[str] = z * math.cos(lowerCAmelCase_ ) + x * math.sin(lowerCAmelCase_ ) __lowercase : List[Any] = y else: raise ValueError("""not a valid axis, choose one of 'x', 'y', 'z'""" ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(f'''{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }''') print(f'''{rotate(1.0, 2.0, 3.0, "y", 90.0) = }''')
233
0
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case ( UpperCAmelCase ): __magic_name__ = 42 __magic_name__ = 42 def __init__( self : str , A : UNetaDModel , A : KarrasVeScheduler ): '''simple docstring''' super().__init__() self.register_modules(unet=A , scheduler=A ) @torch.no_grad() def __call__( self : Dict , A : int = 1 , A : int = 5_0 , A : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A : Optional[str] = "pil" , A : bool = True , **A : str , ): '''simple docstring''' a : Any = self.unet.config.sample_size a : Dict = (batch_size, 3, img_size, img_size) a : Optional[Any] = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) a : Any = randn_tensor(A , generator=A , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(A ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper a : List[str] = self.scheduler.schedule[t] a : Tuple = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat a : int = self.scheduler.add_noise_to_input(A , A , generator=A ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. a : Optional[int] = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev a : Dict = self.scheduler.step(A , A , A , A ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. a : List[Any] = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample a : Union[str, Any] = self.scheduler.step_correct( A , A , A , A , step_output.prev_sample , step_output['derivative'] , ) a : Any = step_output.prev_sample a : Union[str, Any] = (sample / 2 + 0.5).clamp(0 , 1 ) a : str = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : Dict = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
367
"""simple docstring""" import argparse from collections import defaultdict import yaml _UpperCamelCase : int = 'docs/source/en/_toctree.yml' def snake_case (A_ :Optional[Any] ): '''simple docstring''' a : List[Any] = defaultdict(A_ ) for doc in model_doc: counts[doc["local"]] += 1 a : Optional[Any] = [key for key, value in counts.items() if value > 1] a : List[str] = [] for duplicate_key in duplicates: a : int = list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key} ) if len(A_ ) > 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(A_ , key=lambda A_ : s["title"].lower() ) def snake_case (A_ :List[str]=False ): '''simple docstring''' with open(A_ , encoding='utf-8' ) as f: a : Dict = yaml.safe_load(f.read() ) # Get to the API doc a : Optional[Any] = 0 while content[api_idx]["title"] != "API": api_idx += 1 a : List[str] = content[api_idx]['sections'] # Then to the model doc a : Optional[int] = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 a : Optional[Any] = api_doc[model_idx]['sections'] a : Dict = [(idx, section) for idx, section in enumerate(A_ ) if 'sections' in section] a : List[str] = False for idx, modality_doc in modalities_docs: a : str = modality_doc['sections'] a : str = clean_model_doc_toc(A_ ) if old_modality_doc != new_modality_doc: a : str = True if overwrite: a : Any = new_modality_doc if diff: if overwrite: a : Any = model_doc a : str = api_doc with open(A_ , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(A_ , allow_unicode=A_ ) ) 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__": _UpperCamelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') _UpperCamelCase : Any = parser.parse_args() check_model_doc(args.fix_and_overwrite)
186
0
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> str: if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError('''iterations must be defined as integers''' ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ) or not number >= 1: raise ValueError( '''starting number must be and integer and be more than 0''' ) if not iterations >= 1: raise ValueError('''Iterations must be done more than 0 times to play FizzBuzz''' ) __lowerCamelCase = '''''' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(UpperCamelCase__ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
67
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 __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Dict , A : int , A : int , A : int , A : Union[str, Any]=0.0 , A : Optional[int] = None , A : str = "geglu" , A : Optional[int] = None , A : bool = False , A : bool = False , A : bool = False , A : bool = False , A : bool = True , A : str = "layer_norm" , A : bool = False , ) ->Any: super().__init__() lowerCamelCase__ : int = only_cross_attention lowerCamelCase__ : Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero''' lowerCamelCase__ : Union[str, 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: lowerCamelCase__ : Optional[Any] = AdaLayerNorm(A , A ) elif self.use_ada_layer_norm_zero: lowerCamelCase__ : int = AdaLayerNormZero(A , A ) else: lowerCamelCase__ : Dict = nn.LayerNorm(A , elementwise_affine=A ) lowerCamelCase__ : 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. lowerCamelCase__ : Tuple = ( AdaLayerNorm(A , A ) if self.use_ada_layer_norm else nn.LayerNorm(A , elementwise_affine=A ) ) lowerCamelCase__ : int = 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: lowerCamelCase__ : Dict = None lowerCamelCase__ : Tuple = None # 3. Feed-forward lowerCamelCase__ : Optional[int] = nn.LayerNorm(A , elementwise_affine=A ) lowerCamelCase__ : Union[str, Any] = FeedForward(A , dropout=A , activation_fn=A , final_dropout=A ) # let chunk size default to None lowerCamelCase__ : str = None lowerCamelCase__ : Tuple = 0 def __lowerCamelCase ( self : Any , A : Optional[int] , A : int ) ->List[str]: # Sets chunk feed-forward lowerCamelCase__ : List[Any] = chunk_size lowerCamelCase__ : List[str] = dim def __lowerCamelCase ( self : str , A : torch.FloatTensor , A : Optional[torch.FloatTensor] = None , A : Optional[torch.FloatTensor] = None , A : Optional[torch.FloatTensor] = None , A : Optional[torch.LongTensor] = None , A : Dict[str, Any] = None , A : Optional[torch.LongTensor] = None , ) ->Tuple: # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: lowerCamelCase__ : Union[str, Any] = self.norma(A , A ) elif self.use_ada_layer_norm_zero: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = self.norma( A , A , A , hidden_dtype=hidden_states.dtype ) else: lowerCamelCase__ : List[str] = self.norma(A ) lowerCamelCase__ : str = cross_attention_kwargs if cross_attention_kwargs is not None else {} lowerCamelCase__ : 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: lowerCamelCase__ : Any = gate_msa.unsqueeze(1 ) * attn_output lowerCamelCase__ : Optional[int] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: lowerCamelCase__ : int = ( self.norma(A , A ) if self.use_ada_layer_norm else self.norma(A ) ) lowerCamelCase__ : int = self.attna( A , encoder_hidden_states=A , attention_mask=A , **A , ) lowerCamelCase__ : Any = attn_output + hidden_states # 3. Feed-forward lowerCamelCase__ : Union[str, Any] = self.norma(A ) if self.use_ada_layer_norm_zero: lowerCamelCase__ : Optional[int] = 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`." ) lowerCamelCase__ : Optional[int] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size lowerCamelCase__ : Optional[int] = torch.cat( [self.ff(A ) for hid_slice in norm_hidden_states.chunk(A , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: lowerCamelCase__ : Optional[int] = self.ff(A ) if self.use_ada_layer_norm_zero: lowerCamelCase__ : Optional[Any] = gate_mlp.unsqueeze(1 ) * ff_output lowerCamelCase__ : List[Any] = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , A : int , A : Optional[int] = None , A : int = 4 , A : float = 0.0 , A : str = "geglu" , A : bool = False , ) ->int: super().__init__() lowerCamelCase__ : List[Any] = int(dim * mult ) lowerCamelCase__ : List[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": lowerCamelCase__ : int = GELU(A , A ) if activation_fn == "gelu-approximate": lowerCamelCase__ : Optional[int] = GELU(A , A , approximate='''tanh''' ) elif activation_fn == "geglu": lowerCamelCase__ : Any = GEGLU(A , A ) elif activation_fn == "geglu-approximate": lowerCamelCase__ : int = ApproximateGELU(A , A ) lowerCamelCase__ : Union[str, Any] = 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 __lowerCamelCase ( self : Dict , A : List[Any] ) ->Optional[Any]: for module in self.net: lowerCamelCase__ : int = module(A ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Tuple , A : int , A : int , A : str = "none" ) ->Optional[Any]: super().__init__() lowerCamelCase__ : List[Any] = nn.Linear(A , A ) lowerCamelCase__ : Any = approximate def __lowerCamelCase ( self : List[str] , A : Tuple ) ->str: 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 __lowerCamelCase ( self : List[str] , A : str ) ->Optional[int]: lowerCamelCase__ : List[str] = self.proj(A ) lowerCamelCase__ : Optional[int] = self.gelu(A ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Tuple , A : int , A : int ) ->Dict: super().__init__() lowerCamelCase__ : Optional[Any] = nn.Linear(A , dim_out * 2 ) def __lowerCamelCase ( self : List[Any] , A : List[Any] ) ->Tuple: 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 __lowerCamelCase ( self : Any , A : Union[str, Any] ) ->Any: lowerCamelCase__ , lowerCamelCase__ : List[Any] = self.proj(A ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(A ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , A : int , A : int ) ->str: super().__init__() lowerCamelCase__ : Optional[int] = nn.Linear(A , A ) def __lowerCamelCase ( self : Union[str, Any] , A : Dict ) ->Optional[Any]: lowerCamelCase__ : List[str] = self.proj(A ) return x * torch.sigmoid(1.7_02 * x ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , A : Dict , A : Optional[Any] ) ->str: super().__init__() lowerCamelCase__ : List[str] = nn.Embedding(A , A ) lowerCamelCase__ : str = nn.SiLU() lowerCamelCase__ : int = nn.Linear(A , embedding_dim * 2 ) lowerCamelCase__ : Optional[Any] = nn.LayerNorm(A , elementwise_affine=A ) def __lowerCamelCase ( self : int , A : Union[str, Any] , A : Union[str, Any] ) ->Union[str, Any]: lowerCamelCase__ : Union[str, Any] = self.linear(self.silu(self.emb(A ) ) ) lowerCamelCase__ , lowerCamelCase__ : List[str] = torch.chunk(A , 2 ) lowerCamelCase__ : Any = self.norm(A ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : str , A : Optional[Any] , A : int ) ->str: super().__init__() lowerCamelCase__ : Union[str, Any] = CombinedTimestepLabelEmbeddings(A , A ) lowerCamelCase__ : int = nn.SiLU() lowerCamelCase__ : List[str] = nn.Linear(A , 6 * embedding_dim , bias=A ) lowerCamelCase__ : str = nn.LayerNorm(A , elementwise_affine=A , eps=1e-6 ) def __lowerCamelCase ( self : List[str] , A : Any , A : List[Any] , A : Tuple , A : Dict=None ) ->Union[str, Any]: lowerCamelCase__ : List[Any] = self.linear(self.silu(self.emb(A , A , hidden_dtype=A ) ) ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : int = emb.chunk(6 , dim=1 ) lowerCamelCase__ : List[Any] = self.norm(A ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , A : int , A : int , A : int , A : Optional[str] = None , A : float = 1e-5 ) ->Any: super().__init__() lowerCamelCase__ : int = num_groups lowerCamelCase__ : List[str] = eps if act_fn is None: lowerCamelCase__ : Tuple = None else: lowerCamelCase__ : Dict = get_activation(A ) lowerCamelCase__ : Any = nn.Linear(A , out_dim * 2 ) def __lowerCamelCase ( self : List[str] , A : Optional[int] , A : str ) ->Tuple: if self.act: lowerCamelCase__ : Union[str, Any] = self.act(A ) lowerCamelCase__ : Optional[Any] = self.linear(A ) lowerCamelCase__ : Optional[Any] = emb[:, :, None, None] lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = emb.chunk(2 , dim=1 ) lowerCamelCase__ : str = F.group_norm(A , self.num_groups , eps=self.eps ) lowerCamelCase__ : Dict = x * (1 + scale) + shift return x
142
0
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class a__ ( lowerCamelCase_ ): def __init__( self ): """simple docstring""" self.test() def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Dict = 0 _lowercase : Dict = False while not completed: if counter == 1: self.reset() _lowercase : List[str] = self.advance() if not self.does_advance(_UpperCamelCase ): raise Exception( "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true." ) _lowercase : Any = self.update(_UpperCamelCase ) counter += 1 if counter > 10000: raise Exception("update() does not fulfill the constraint." ) if self.remaining() != 0: raise Exception("Custom Constraint is not defined correctly." ) @abstractmethod def _lowerCamelCase ( self ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _lowerCamelCase ( self ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _lowerCamelCase ( self ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def _lowerCamelCase ( self , _UpperCamelCase=False ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class a__ ( lowerCamelCase_ ): def __init__( self , _UpperCamelCase ): """simple docstring""" super(_UpperCamelCase , self ).__init__() if not isinstance(_UpperCamelCase , _UpperCamelCase ) or len(_UpperCamelCase ) == 0: raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(_UpperCamelCase , _UpperCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) _lowercase : Optional[Any] = token_ids _lowercase : Optional[Any] = len(self.token_ids ) _lowercase : Union[str, Any] = -1 # the index of the currently fulfilled step _lowercase : int = False def _lowerCamelCase ( self ): """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) _lowercase : Union[str, Any] = False _lowercase : str = False _lowercase : List[Any] = False if self.does_advance(_UpperCamelCase ): self.fulfilled_idx += 1 _lowercase : Optional[int] = True if self.fulfilled_idx == (self.seqlen - 1): _lowercase : Union[str, Any] = True _lowercase : Dict = completed else: # failed to make progress. _lowercase : List[Any] = True self.reset() return stepped, completed, reset def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Optional[Any] = False _lowercase : Any = 0 def _lowerCamelCase ( self ): """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def _lowerCamelCase ( self , _UpperCamelCase=False ): """simple docstring""" _lowercase : Optional[int] = PhrasalConstraint(self.token_ids ) if stateful: _lowercase : Any = self.seqlen _lowercase : Optional[int] = self.fulfilled_idx _lowercase : str = self.completed return new_constraint class a__ : def __init__( self , _UpperCamelCase , _UpperCamelCase=True ): """simple docstring""" _lowercase : Tuple = max([len(_UpperCamelCase ) for one in nested_token_ids] ) _lowercase : List[str] = {} for token_ids in nested_token_ids: _lowercase : List[str] = root for tidx, token_id in enumerate(_UpperCamelCase ): if token_id not in level: _lowercase : List[Any] = {} _lowercase : Any = level[token_id] if no_subsets and self.has_subsets(_UpperCamelCase , _UpperCamelCase ): raise ValueError( "Each list in `nested_token_ids` can't be a complete subset of another list, but is" f''' {nested_token_ids}.''' ) _lowercase : Tuple = root def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : List[str] = self.trie for current_token in current_seq: _lowercase : List[str] = start[current_token] _lowercase : List[str] = list(start.keys() ) return next_tokens def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Optional[int] = self.next_tokens(_UpperCamelCase ) return len(_UpperCamelCase ) == 0 def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Optional[int] = list(root.values() ) if len(_UpperCamelCase ) == 0: return 1 else: return sum([self.count_leaves(_UpperCamelCase ) for nn in next_nodes] ) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase ): """simple docstring""" _lowercase : Optional[Any] = self.count_leaves(_UpperCamelCase ) return len(_UpperCamelCase ) != leaf_count class a__ ( lowerCamelCase_ ): def __init__( self , _UpperCamelCase ): """simple docstring""" super(_UpperCamelCase , self ).__init__() if not isinstance(_UpperCamelCase , _UpperCamelCase ) or len(_UpperCamelCase ) == 0: raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(_UpperCamelCase , _UpperCamelCase ) for token_ids in nested_token_ids ): raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(_UpperCamelCase , _UpperCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) _lowercase : Optional[Any] = DisjunctiveTrie(_UpperCamelCase ) _lowercase : List[str] = nested_token_ids _lowercase : str = self.trie.max_height _lowercase : Union[str, Any] = [] _lowercase : Optional[int] = False def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Tuple = self.trie.next_tokens(self.current_seq ) if len(_UpperCamelCase ) == 0: return None else: return token_list def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) _lowercase : List[Any] = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(_UpperCamelCase )}''' ) _lowercase : Any = False _lowercase : Any = False _lowercase : Optional[int] = False if self.does_advance(_UpperCamelCase ): self.current_seq.append(_UpperCamelCase ) _lowercase : Union[str, Any] = True else: _lowercase : Tuple = True self.reset() _lowercase : Dict = self.trie.reached_leaf(self.current_seq ) _lowercase : str = completed return stepped, completed, reset def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Dict = False _lowercase : int = [] def _lowerCamelCase ( self ): """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def _lowerCamelCase ( self , _UpperCamelCase=False ): """simple docstring""" _lowercase : Dict = DisjunctiveConstraint(self.token_ids ) if stateful: _lowercase : Dict = self.seqlen _lowercase : Union[str, Any] = self.current_seq _lowercase : Optional[int] = self.completed return new_constraint class a__ : def __init__( self , _UpperCamelCase ): """simple docstring""" _lowercase : Union[str, Any] = constraints # max # of steps required to fulfill a given constraint _lowercase : List[Any] = max([c.seqlen for c in constraints] ) _lowercase : str = len(_UpperCamelCase ) _lowercase : Union[str, Any] = False self.init_state() def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Tuple = [] _lowercase : Union[str, Any] = None _lowercase : List[Any] = [constraint.copy(stateful=_UpperCamelCase ) for constraint in self.constraints] def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Dict = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Dict = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" _lowercase : Tuple = constraint.advance() if isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.append(_UpperCamelCase ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.extend(_UpperCamelCase ) else: _lowercase : str = self.inprogress_constraint.advance() if isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.append(_UpperCamelCase ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): token_list.extend(_UpperCamelCase ) if len(_UpperCamelCase ) == 0: return None else: return token_list def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint _lowercase : Optional[int] = self.add(_UpperCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" if not isinstance(_UpperCamelCase , _UpperCamelCase ): raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.''' ) _lowercase : str = False, False if self.completed: _lowercase : Tuple = True _lowercase : int = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state _lowercase : Tuple = self.inprogress_constraint.update(_UpperCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=_UpperCamelCase ) ) _lowercase : Tuple = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) _lowercase : Dict = None if len(self.pending_constraints ) == 0: # we're done! _lowercase : str = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(_UpperCamelCase ): _lowercase : List[Any] = pending_constraint.update(_UpperCamelCase ) if not stepped: raise Exception( "`constraint.update(token_id)` is not yielding incremental progress, " "even though `constraint.does_advance(token_id)` is true." ) if complete: self.complete_constraints.append(_UpperCamelCase ) _lowercase : List[str] = None if not complete and stepped: _lowercase : Any = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". _lowercase : Union[str, Any] = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. _lowercase : Dict = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def _lowerCamelCase ( self , _UpperCamelCase=True ): """simple docstring""" _lowercase : List[str] = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: _lowercase : int = [ constraint.copy(stateful=_UpperCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: _lowercase : Optional[Any] = self.inprogress_constraint.copy(stateful=_UpperCamelCase ) _lowercase : Optional[int] = [constraint.copy() for constraint in self.pending_constraints] return new_state
350
'''simple docstring''' import os import re 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 _snake_case = logging.get_logger(__name__) _snake_case = {'vocab_file': 'spiece.model'} _snake_case = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } _snake_case = { 'google/bigbird-roberta-base': 4_096, 'google/bigbird-roberta-large': 4_096, 'google/bigbird-base-trivia-itc': 4_096, } class a__ ( lowerCamelCase_ ): _SCREAMING_SNAKE_CASE : List[Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE : Any = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE : Optional[int] = ['input_ids', 'attention_mask'] _SCREAMING_SNAKE_CASE : List[int] = [] def __init__( self , _UpperCamelCase , _UpperCamelCase="<unk>" , _UpperCamelCase="<s>" , _UpperCamelCase="</s>" , _UpperCamelCase="<pad>" , _UpperCamelCase="[SEP]" , _UpperCamelCase="[MASK]" , _UpperCamelCase="[CLS]" , _UpperCamelCase = None , **_UpperCamelCase , ): """simple docstring""" _lowercase : Optional[int] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else bos_token _lowercase : Optional[int] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else eos_token _lowercase : Optional[Any] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else unk_token _lowercase : Union[str, Any] = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else pad_token _lowercase : Any = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else cls_token _lowercase : str = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else sep_token # Mask token behave like a normal word, i.e. include the space before it _lowercase : Any = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else mask_token _lowercase : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , sep_token=_UpperCamelCase , mask_token=_UpperCamelCase , cls_token=_UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_UpperCamelCase , ) _lowercase : str = vocab_file _lowercase : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_UpperCamelCase ) @property def _lowerCamelCase ( self ): """simple docstring""" return self.sp_model.get_piece_size() def _lowerCamelCase ( self ): """simple docstring""" _lowercase : Dict = {self.convert_ids_to_tokens(_UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" _lowercase : str = self.__dict__.copy() _lowercase : Union[str, Any] = None return state def __setstate__( self , _UpperCamelCase ): """simple docstring""" _lowercase : Dict = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): _lowercase : Optional[Any] = {} _lowercase : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" return self.sp_model.encode(_UpperCamelCase , out_type=_UpperCamelCase ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" return self.sp_model.piece_to_id(_UpperCamelCase ) def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : List[Any] = self.sp_model.IdToPiece(_UpperCamelCase ) return token def _lowerCamelCase ( self , _UpperCamelCase ): """simple docstring""" _lowercase : Optional[int] = [] _lowercase : int = "" _lowercase : Tuple = 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(_UpperCamelCase ) + token _lowercase : Union[str, Any] = True _lowercase : Optional[int] = [] else: current_sub_tokens.append(_UpperCamelCase ) _lowercase : str = False out_string += self.sp_model.decode(_UpperCamelCase ) return out_string.strip() def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = False , _UpperCamelCase = None , _UpperCamelCase = True , **_UpperCamelCase , ): """simple docstring""" _lowercase : Any = kwargs.pop("use_source_tokenizer" , _UpperCamelCase ) _lowercase : Dict = self.convert_ids_to_tokens(_UpperCamelCase , skip_special_tokens=_UpperCamelCase ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 _lowercase : Dict = [] _lowercase : Any = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_UpperCamelCase ) ) _lowercase : Optional[Any] = [] sub_texts.append(_UpperCamelCase ) else: current_sub_text.append(_UpperCamelCase ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(_UpperCamelCase ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: _lowercase : List[str] = re.sub(R" (\[(MASK|SEP)\])" , R"\1" , " ".join(_UpperCamelCase ) ) else: _lowercase : List[Any] = "".join(_UpperCamelCase ) _lowercase : Optional[int] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: _lowercase : Tuple = self.clean_up_tokenization(_UpperCamelCase ) return clean_text else: return text def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None ): """simple docstring""" if not os.path.isdir(_UpperCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return _lowercase : Optional[Any] = os.path.join( _UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_UpperCamelCase , "wb" ) as fi: _lowercase : List[str] = self.sp_model.serialized_model_proto() fi.write(_UpperCamelCase ) return (out_vocab_file,) def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _lowercase : str = [self.cls_token_id] _lowercase : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None , _UpperCamelCase = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCamelCase )) + [1] return [1] + ([0] * len(_UpperCamelCase )) + [1] + ([0] * len(_UpperCamelCase )) + [1] def _lowerCamelCase ( self , _UpperCamelCase , _UpperCamelCase = None ): """simple docstring""" _lowercase : str = [self.sep_token_id] _lowercase : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
199
0
"""simple docstring""" _UpperCAmelCase = { """km/h""": 1.0, """m/s""": 3.6, """mph""": 1.6_0_9_3_4_4, """knot""": 1.8_5_2, } _UpperCAmelCase = { """km/h""": 1.0, """m/s""": 0.2_7_7_7_7_7_7_7_8, """mph""": 0.6_2_1_3_7_1_1_9_2, """knot""": 0.5_3_9_9_5_6_8_0_3, } def __magic_name__ ( lowercase , lowercase , lowercase ): if unit_to not in speed_chart or unit_from not in speed_chart_inverse: SCREAMING_SNAKE_CASE_: List[Any] =( f'''Incorrect \'from_type\' or \'to_type\' value: {unit_from!r}, {unit_to!r}\n''' f'''Valid values are: {", ".join(UpperCamelCase_ )}''' ) raise ValueError(UpperCamelCase_ ) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to] , 3 ) if __name__ == "__main__": import doctest doctest.testmod()
173
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass a_ = (3, 9, -11, 0, 7, 5, 1, -1) a_ = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class lowercase__ : a_ =42 a_ =42 class lowercase__ : def __init__( self , __UpperCAmelCase )-> None: '''simple docstring''' lowerCAmelCase__ = None for i in sorted(__UpperCAmelCase , reverse=__UpperCAmelCase ): lowerCAmelCase__ = Node(__UpperCAmelCase , self.head ) def __iter__( self )-> Iterator[int]: '''simple docstring''' lowerCAmelCase__ = self.head while node: yield node.data lowerCAmelCase__ = node.next_node def __len__( self )-> int: '''simple docstring''' return sum(1 for _ in self ) def __str__( self )-> str: '''simple docstring''' return " -> ".join([str(__UpperCAmelCase ) for node in self] ) def _a ( UpperCamelCase_ : SortedLinkedList , UpperCamelCase_ : SortedLinkedList ) -> SortedLinkedList: """simple docstring""" return SortedLinkedList(list(UpperCamelCase_ ) + list(UpperCamelCase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() a_ = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
340
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class __lowerCAmelCase : # setable values _lowercase : Optional[int] = None _lowercase : Optional[jnp.ndarray] = None _lowercase : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def _lowercase ( cls ) -> List[str]: '''simple docstring''' return cls() @dataclass class __lowerCAmelCase ( UpperCamelCase__): _lowercase : jnp.ndarray _lowercase : jnp.ndarray _lowercase : KarrasVeSchedulerState class __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__): @property def _lowercase ( self ) -> Optional[int]: '''simple docstring''' return True @register_to_config def __init__( self , lowerCAmelCase__ = 0.02 , lowerCAmelCase__ = 1_0_0 , lowerCAmelCase__ = 1.0_07 , lowerCAmelCase__ = 8_0 , lowerCAmelCase__ = 0.05 , lowerCAmelCase__ = 5_0 , ) -> List[Any]: '''simple docstring''' pass def _lowercase ( self ) -> List[Any]: '''simple docstring''' return KarrasVeSchedulerState.create() def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = () ) -> KarrasVeSchedulerState: '''simple docstring''' a__ : Dict =jnp.arange(0 , lowerCAmelCase__ )[::-1].copy() a__ : Tuple =[ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=lowerCAmelCase__ , schedule=jnp.array(lowerCAmelCase__ , dtype=jnp.floataa ) , timesteps=lowerCAmelCase__ , ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Tuple[jnp.ndarray, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: a__ : Optional[Any] =min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: a__ : Optional[int] =0 # sample eps ~ N(0, S_noise^2 * I) a__ : Union[str, Any] =random.split(lowerCAmelCase__ , num=1 ) a__ : Dict =self.config.s_noise * random.normal(key=lowerCAmelCase__ , shape=sample.shape ) a__ : Any =sigma + gamma * sigma a__ : List[str] =sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: '''simple docstring''' a__ : Optional[int] =sample_hat + sigma_hat * model_output a__ : Optional[Any] =(sample_hat - pred_original_sample) / sigma_hat a__ : Union[str, Any] =sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=lowerCAmelCase__ , derivative=lowerCAmelCase__ , state=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: '''simple docstring''' a__ : Dict =sample_prev + sigma_prev * model_output a__ : Any =(sample_prev - pred_original_sample) / sigma_prev a__ : Dict =sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=lowerCAmelCase__ , derivative=lowerCAmelCase__ , state=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError()
148
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def _A ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : List[Any] ={ "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] a__ : List[Any] ={ "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } a__ : Optional[int] =f'''{src_lang}-{tgt_lang}''' a__ : Any =f''' --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = "facebook/wmt19-{src_lang}-{tgt_lang}" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = "{texts[src_lang]}" input_ids = tokenizer.encode(input, return_tensors="pt") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR\'s WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) ''' os.makedirs(SCREAMING_SNAKE_CASE , exist_ok=SCREAMING_SNAKE_CASE ) a__ : Tuple =os.path.join(SCREAMING_SNAKE_CASE , "README.md" ) print(f'''Generating {path}''' ) with open(SCREAMING_SNAKE_CASE , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE ) # make sure we are under the root of the project UpperCAmelCase : str = Path(__file__).resolve().parent.parent.parent UpperCAmelCase : Dict = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : List[str] = model_name.split("""-""") UpperCAmelCase : Tuple = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
148
1
"""simple docstring""" from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class UpperCAmelCase_ ( A_ ): lowercase__ = '''umt5''' lowercase__ = ['''past_key_values'''] def __init__( self : List[str] , snake_case_ : Dict=250_112 , snake_case_ : Tuple=512 , snake_case_ : int=64 , snake_case_ : List[str]=1_024 , snake_case_ : List[Any]=8 , snake_case_ : List[str]=None , snake_case_ : List[Any]=6 , snake_case_ : str=32 , snake_case_ : Any=128 , snake_case_ : Any=0.1 , snake_case_ : Optional[int]=1e-6 , snake_case_ : Optional[int]=1.0 , snake_case_ : Any="gated-gelu" , snake_case_ : Union[str, Any]=True , snake_case_ : Optional[Any]=True , snake_case_ : int="T5Tokenizer" , snake_case_ : List[Any]=True , snake_case_ : int=0 , snake_case_ : Any=1 , snake_case_ : Dict=0 , **snake_case_ : Tuple , ) -> int: '''simple docstring''' super().__init__( is_encoder_decoder=snake_case_ , tokenizer_class=snake_case_ , tie_word_embeddings=snake_case_ , pad_token_id=snake_case_ , eos_token_id=snake_case_ , decoder_start_token_id=snake_case_ , **snake_case_ , ) A__ = vocab_size A__ = d_model A__ = d_kv A__ = d_ff A__ = num_layers A__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry A__ = num_heads A__ = relative_attention_num_buckets A__ = relative_attention_max_distance A__ = dropout_rate A__ = layer_norm_epsilon A__ = initializer_factor A__ = feed_forward_proj A__ = use_cache A__ = self.feed_forward_proj.split("-" ) A__ = act_info[-1] A__ = act_info[0] == "gated" if len(snake_case_ ) > 1 and act_info[0] != "gated" or len(snake_case_ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": A__ = "gelu_new" @property def __magic_name__ ( self : Dict ) -> Optional[int]: '''simple docstring''' return self.d_model @property def __magic_name__ ( self : Tuple ) -> Any: '''simple docstring''' return self.num_heads @property def __magic_name__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return self.num_layers class UpperCAmelCase_ ( A_ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __magic_name__ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' A__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: A__ = "past_encoder_sequence + sequence" A__ = {0: "batch"} A__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: A__ = {0: "batch", 1: "decoder_sequence"} A__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(snake_case_ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __magic_name__ ( self : Any ) -> int: '''simple docstring''' return 13 @property def __magic_name__ ( self : List[str] ) -> float: '''simple docstring''' return 5e-4
247
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) SCREAMING_SNAKE_CASE = [ "cross_validation.py", "gradient_accumulation.py", "local_sgd.py", "multi_process_metrics.py", "memory.py", "automatic_gradient_accumulation.py", "fsdp_with_peak_mem_tracking.py", "deepspeed_with_config_support.py", "megatron_lm_gpt_pretraining.py", ] class UpperCAmelCase_ ( unittest.TestCase ): def __magic_name__ ( self : List[Any] , snake_case_ : str , snake_case_ : bool , snake_case_ : str = None , snake_case_ : list = None ) -> Tuple: '''simple docstring''' A__ = None A__ = os.path.abspath(os.path.join("examples" , "by_feature" ) ) A__ = os.path.abspath("examples" ) for item in os.listdir(snake_case_ ): if item not in EXCLUDE_EXAMPLES: A__ = os.path.join(snake_case_ , snake_case_ ) if os.path.isfile(snake_case_ ) and ".py" in item_path: with self.subTest( tested_script=snake_case_ , feature_script=snake_case_ , tested_section="main()" if parser_only else "training_function()" , ): A__ = compare_against_test( os.path.join(snake_case_ , snake_case_ ) , snake_case_ , snake_case_ , snake_case_ ) A__ = "\n".join(snake_case_ ) if special_strings is not None: for string in special_strings: A__ = diff.replace(snake_case_ , "" ) self.assertEqual(snake_case_ , "" ) def __magic_name__ ( self : List[str] ) -> str: '''simple docstring''' self.one_complete_example("complete_nlp_example.py" , snake_case_ ) self.one_complete_example("complete_nlp_example.py" , snake_case_ ) def __magic_name__ ( self : str ) -> Union[str, Any]: '''simple docstring''' A__ = os.path.abspath(os.path.join("examples" , "cv_example.py" ) ) A__ = [ " " * 16 + "{\n\n", " " * 20 + "\"accuracy\": eval_metric[\"accuracy\"],\n\n", " " * 20 + "\"f1\": eval_metric[\"f1\"],\n\n", " " * 20 + "\"train_loss\": total_loss.item() / len(train_dataloader),\n\n", " " * 20 + "\"epoch\": epoch,\n\n", " " * 16 + "},\n\n", " " * 16 + "step=epoch,\n", " " * 12, " " * 8 + "for step, batch in enumerate(active_dataloader):\n", ] self.one_complete_example("complete_cv_example.py" , snake_case_ , snake_case_ , snake_case_ ) self.one_complete_example("complete_cv_example.py" , snake_case_ , snake_case_ , snake_case_ ) @mock.patch.dict(os.environ, {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class UpperCAmelCase_ ( A_ ): lowercase__ = False @classmethod def __magic_name__ ( cls : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' super().setUpClass() A__ = tempfile.mkdtemp() A__ = os.path.join(cls._tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) A__ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def __magic_name__ ( cls : Dict ) -> str: '''simple docstring''' super().tearDownClass() shutil.rmtree(cls._tmpdir ) def __magic_name__ ( self : Dict ) -> List[Any]: '''simple docstring''' A__ = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "epoch_0" ) ) ) def __magic_name__ ( self : Any ) -> Any: '''simple docstring''' A__ = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() A__ = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "step_2" ) ) ) def __magic_name__ ( self : int ) -> Union[str, Any]: '''simple docstring''' A__ = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )} """.split() A__ = run_command(self._launch_args + testargs , return_stdout=snake_case_ ) self.assertNotIn("epoch 0:" , snake_case_ ) self.assertIn("epoch 1:" , snake_case_ ) def __magic_name__ ( self : List[str] ) -> Optional[int]: '''simple docstring''' A__ = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )} """.split() A__ = run_command(self._launch_args + testargs , return_stdout=snake_case_ ) if torch.cuda.is_available(): A__ = torch.cuda.device_count() else: A__ = 1 if num_processes > 1: self.assertNotIn("epoch 0:" , snake_case_ ) self.assertIn("epoch 1:" , snake_case_ ) else: self.assertIn("epoch 0:" , snake_case_ ) self.assertIn("epoch 1:" , snake_case_ ) @slow def __magic_name__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' A__ = "\n examples/by_feature/cross_validation.py\n --num_folds 2\n ".split() with mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "0"} ): A__ = run_command(self._launch_args + testargs , return_stdout=snake_case_ ) A__ = re.findall("({.+})" , snake_case_ ) A__ = [r for r in results if "accuracy" in r][-1] A__ = ast.literal_eval(snake_case_ ) self.assertGreaterEqual(results["accuracy"] , 0.75 ) def __magic_name__ ( self : List[Any] ) -> Tuple: '''simple docstring''' A__ = ["examples/by_feature/multi_process_metrics.py"] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def __magic_name__ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: A__ = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(snake_case_ , "tracking" ) ) ) def __magic_name__ ( self : List[Any] ) -> int: '''simple docstring''' A__ = ["examples/by_feature/gradient_accumulation.py"] run_command(self._launch_args + testargs ) def __magic_name__ ( self : List[str] ) -> List[Any]: '''simple docstring''' A__ = ["examples/by_feature/local_sgd.py"] run_command(self._launch_args + testargs )
247
1
"""simple docstring""" 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 UpperCAmelCase_ : def __init__( self : Dict , snake_case_ : Union[str, Any] , snake_case_ : List[str]=13 , snake_case_ : List[Any]=30 , snake_case_ : Dict=2 , snake_case_ : int=3 , snake_case_ : Dict=True , snake_case_ : Any=True , snake_case_ : Any=32 , snake_case_ : Optional[Any]=5 , snake_case_ : List[Any]=4 , snake_case_ : int=37 , snake_case_ : Any="gelu" , snake_case_ : Union[str, Any]=0.1 , snake_case_ : int=0.1 , snake_case_ : Tuple=10 , snake_case_ : Optional[int]=0.02 , snake_case_ : Dict=3 , snake_case_ : Union[str, Any]=None , snake_case_ : int=2 , ) -> Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = image_size A__ = patch_size A__ = num_channels A__ = is_training A__ = use_labels A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = type_sequence_label_size A__ = initializer_range A__ = scope A__ = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) A__ = (image_size // patch_size) ** 2 A__ = num_patches + 2 def __magic_name__ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ = self.get_config() return config, pixel_values, labels def __magic_name__ ( self : Tuple ) -> str: '''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=snake_case_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __magic_name__ ( self : Union[str, Any] , snake_case_ : Optional[Any] , snake_case_ : Dict , snake_case_ : Dict ) -> Any: '''simple docstring''' A__ = DeiTModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() A__ = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : Optional[int] , snake_case_ : int , snake_case_ : Dict , snake_case_ : str ) -> Tuple: '''simple docstring''' A__ = DeiTForMaskedImageModeling(config=snake_case_ ) model.to(snake_case_ ) model.eval() A__ = model(snake_case_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A__ = 1 A__ = DeiTForMaskedImageModeling(snake_case_ ) model.to(snake_case_ ) model.eval() A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(snake_case_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __magic_name__ ( self : Any , snake_case_ : Optional[Any] , snake_case_ : List[Any] , snake_case_ : Optional[Any] ) -> Dict: '''simple docstring''' A__ = self.type_sequence_label_size A__ = DeiTForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() A__ = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images A__ = 1 A__ = DeiTForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __magic_name__ ( self : Dict ) -> int: '''simple docstring''' A__ = self.prepare_config_and_inputs() ( ( A__ ), ( A__ ), ( A__ ), ) = config_and_inputs A__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( A_, A_, unittest.TestCase ): lowercase__ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase__ = ( { '''feature-extraction''': DeiTModel, '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase__ = False lowercase__ = False lowercase__ = False def __magic_name__ ( self : str ) -> Tuple: '''simple docstring''' A__ = DeiTModelTester(self ) A__ = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ , hidden_size=37 ) def __magic_name__ ( self : Any ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def __magic_name__ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' pass def __magic_name__ ( self : Dict ) -> Dict: '''simple docstring''' A__, A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(snake_case_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case_ , nn.Linear ) ) def __magic_name__ ( self : Tuple ) -> List[Any]: '''simple docstring''' A__, A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(snake_case_ ) A__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ = [*signature.parameters.keys()] A__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , snake_case_ ) def __magic_name__ ( self : Any ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def __magic_name__ ( self : List[str] ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_ ) def __magic_name__ ( self : Dict ) -> List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) def __magic_name__ ( self : Optional[Any] , snake_case_ : Any , snake_case_ : int , snake_case_ : str=False ) -> Dict: '''simple docstring''' A__ = super()._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __magic_name__ ( self : str ) -> Tuple: '''simple docstring''' if not self.model_tester.is_training: return A__, A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(snake_case_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue A__ = model_class(snake_case_ ) model.to(snake_case_ ) model.train() A__ = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) A__ = model(**snake_case_ ).loss loss.backward() def __magic_name__ ( self : Any ) -> str: '''simple docstring''' A__, A__ = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return A__ = False A__ = True for model_class in self.all_model_classes: if model_class in get_values(snake_case_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue A__ = model_class(snake_case_ ) model.gradient_checkpointing_enable() model.to(snake_case_ ) model.train() A__ = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) A__ = model(**snake_case_ ).loss loss.backward() def __magic_name__ ( self : str ) -> Optional[int]: '''simple docstring''' A__, A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = [ {"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(snake_case_ ), *get_values(snake_case_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"""Testing {model_class} with {problem_type["title"]}""" ): A__ = problem_type["title"] A__ = problem_type["num_labels"] A__ = model_class(snake_case_ ) model.to(snake_case_ ) model.train() A__ = self._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) if problem_type["num_labels"] > 1: A__ = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] ) A__ = 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=snake_case_ ) as warning_list: A__ = model(**snake_case_ ).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 __magic_name__ ( self : Tuple ) -> str: '''simple docstring''' for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = DeiTModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def _SCREAMING_SNAKE_CASE ( ) -> Tuple: A__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @cached_property def __magic_name__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def __magic_name__ ( self : List[str] ) -> str: '''simple docstring''' A__ = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to( snake_case_ ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=snake_case_ , return_tensors="pt" ).to(snake_case_ ) # forward pass with torch.no_grad(): A__ = model(**snake_case_ ) # verify the logits A__ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , snake_case_ ) A__ = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __magic_name__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' A__ = DeiTModel.from_pretrained( "facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=snake_case_ , return_tensors="pt" ) A__ = inputs.pixel_values.to(snake_case_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): A__ = model(snake_case_ )
230
"""simple docstring""" import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def _SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: return x + 2 class UpperCAmelCase_ ( unittest.TestCase ): def __magic_name__ ( self : Any ) -> Any: '''simple docstring''' A__ = "x = 3" A__ = {} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"x": 3} ) A__ = "x = y" A__ = {"y": 5} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"x": 5, "y": 5} ) def __magic_name__ ( self : Optional[Any] ) -> Any: '''simple docstring''' A__ = "y = add_two(x)" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result is None assert "tried to execute add_two" in out.out def __magic_name__ ( self : Dict ) -> List[str]: '''simple docstring''' A__ = "x = 3" A__ = {} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"x": 3} ) def __magic_name__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' A__ = "test_dict = {'x': x, 'y': add_two(x)}" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) self.assertDictEqual(snake_case_ , {"x": 3, "y": 5} ) self.assertDictEqual(snake_case_ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def __magic_name__ ( self : int ) -> str: '''simple docstring''' A__ = "x = 3\ny = 5" A__ = {} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "y": 5} ) def __magic_name__ ( self : Any ) -> List[Any]: '''simple docstring''' A__ = "text = f'This is x: {x}.'" A__ = {"x": 3} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(snake_case_ , {"x": 3, "text": "This is x: 3."} ) def __magic_name__ ( self : str ) -> Optional[int]: '''simple docstring''' A__ = "if x <= 3:\n y = 2\nelse:\n y = 5" A__ = {"x": 3} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(snake_case_ , {"x": 3, "y": 2} ) A__ = {"x": 8} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(snake_case_ , {"x": 8, "y": 5} ) def __magic_name__ ( self : List[str] ) -> Tuple: '''simple docstring''' A__ = "test_list = [x, add_two(x)]" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) self.assertListEqual(snake_case_ , [3, 5] ) self.assertDictEqual(snake_case_ , {"x": 3, "test_list": [3, 5]} ) def __magic_name__ ( self : Tuple ) -> int: '''simple docstring''' A__ = "y = x" A__ = {"x": 3} A__ = evaluate(snake_case_ , {} , state=snake_case_ ) assert result == 3 self.assertDictEqual(snake_case_ , {"x": 3, "y": 3} ) def __magic_name__ ( self : str ) -> Dict: '''simple docstring''' A__ = "test_list = [x, add_two(x)]\ntest_list[1]" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "test_list": [3, 5]} ) A__ = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" A__ = {"x": 3} A__ = evaluate(snake_case_ , {"add_two": add_two} , state=snake_case_ ) assert result == 5 self.assertDictEqual(snake_case_ , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def __magic_name__ ( self : Optional[int] ) -> Tuple: '''simple docstring''' A__ = "x = 0\nfor i in range(3):\n x = i" A__ = {} A__ = evaluate(snake_case_ , {"range": range} , state=snake_case_ ) assert result == 2 self.assertDictEqual(snake_case_ , {"x": 2, "i": 2} )
230
1
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [] if isinstance(__lowerCamelCase, __lowerCamelCase ): for v in tree.values(): shapes.extend(_fetch_dims(__lowerCamelCase ) ) elif isinstance(__lowerCamelCase, (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(__lowerCamelCase ) ) elif isinstance(__lowerCamelCase, torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('''Not supported''' ) return shapes @torch.jit.ignore def A__ ( __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [] for d in reversed(__lowerCamelCase ): idx.append(flat_idx % d ) SCREAMING_SNAKE_CASE_ = flat_idx // d return tuple(reversed(__lowerCamelCase ) ) @torch.jit.ignore def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = None, __lowerCamelCase = None, ): # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(__lowerCamelCase ) -> None: SCREAMING_SNAKE_CASE_ = True for i in range(len(__lowerCamelCase ) ): SCREAMING_SNAKE_CASE_ = -1 * (i + 1) l[reversed_idx] &= tally SCREAMING_SNAKE_CASE_ = l[reversed_idx] if start_edges is None: SCREAMING_SNAKE_CASE_ = [s == 0 for s in start] reduce_edge_list(__lowerCamelCase ) if end_edges is None: SCREAMING_SNAKE_CASE_ = [e == (d - 1) for e, d in zip(__lowerCamelCase, __lowerCamelCase )] reduce_edge_list(__lowerCamelCase ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(__lowerCamelCase ) == 0: return [()] elif len(__lowerCamelCase ) == 1: return [(slice(start[0], end[0] + 1 ),)] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(__lowerCamelCase, __lowerCamelCase ): if s == e: path_list.append(slice(__lowerCamelCase, s + 1 ) ) else: break SCREAMING_SNAKE_CASE_ = tuple(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = len(__lowerCamelCase ) # start == end, and we're done if divergence_idx == len(__lowerCamelCase ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None SCREAMING_SNAKE_CASE_ = start[divergence_idx] return tuple( path + (slice(__lowerCamelCase, sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :], [d - 1 for d in dims[divergence_idx + 1 :]], dims[divergence_idx + 1 :], start_edges=start_edges[divergence_idx + 1 :], end_edges=[True for _ in end_edges[divergence_idx + 1 :]], ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None SCREAMING_SNAKE_CASE_ = end[divergence_idx] return tuple( path + (slice(__lowerCamelCase, edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]], end[divergence_idx + 1 :], dims[divergence_idx + 1 :], start_edges=[True for _ in start_edges[divergence_idx + 1 :]], end_edges=end_edges[divergence_idx + 1 :], ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx], end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx], end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1, end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) SCREAMING_SNAKE_CASE_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1, end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = t.shape[:no_batch_dims] SCREAMING_SNAKE_CASE_ = list(_flat_idx_to_idx(__lowerCamelCase, __lowerCamelCase ) ) # _get_minimal_slice_set is inclusive SCREAMING_SNAKE_CASE_ = list(_flat_idx_to_idx(flat_end - 1, __lowerCamelCase ) ) # Get an ordered list of slices to perform SCREAMING_SNAKE_CASE_ = _get_minimal_slice_set( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, ) SCREAMING_SNAKE_CASE_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = False, __lowerCamelCase = None, __lowerCamelCase = False, ): if not (len(__lowerCamelCase ) > 0): raise ValueError('''Must provide at least one input''' ) SCREAMING_SNAKE_CASE_ = [shape[:no_batch_dims] for shape in _fetch_dims(__lowerCamelCase )] SCREAMING_SNAKE_CASE_ = tuple([max(__lowerCamelCase ) for s in zip(*__lowerCamelCase )] ) def _prep_inputs(__lowerCamelCase ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: SCREAMING_SNAKE_CASE_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) SCREAMING_SNAKE_CASE_ = t.reshape(-1, *t.shape[no_batch_dims:] ) else: SCREAMING_SNAKE_CASE_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t SCREAMING_SNAKE_CASE_ = tensor_tree_map(_prep_inputs, __lowerCamelCase ) SCREAMING_SNAKE_CASE_ = None if _out is not None: SCREAMING_SNAKE_CASE_ = tensor_tree_map(lambda __lowerCamelCase : t.view([-1] + list(t.shape[no_batch_dims:] ) ), _out ) SCREAMING_SNAKE_CASE_ = 1 for d in orig_batch_dims: flat_batch_dim *= d SCREAMING_SNAKE_CASE_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(__lowerCamelCase ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = prepped_outputs for _ in range(__lowerCamelCase ): # Chunk the input if not low_mem: SCREAMING_SNAKE_CASE_ = _select_chunk else: SCREAMING_SNAKE_CASE_ = partial( _chunk_slice, flat_start=__lowerCamelCase, flat_end=min(__lowerCamelCase, i + chunk_size ), no_batch_dims=len(__lowerCamelCase ), ) SCREAMING_SNAKE_CASE_ = tensor_tree_map(__lowerCamelCase, __lowerCamelCase ) # Run the layer on the chunk SCREAMING_SNAKE_CASE_ = layer(**__lowerCamelCase ) # Allocate space for the output if out is None: SCREAMING_SNAKE_CASE_ = tensor_tree_map(lambda __lowerCamelCase : t.new_zeros((flat_batch_dim,) + t.shape[1:] ), __lowerCamelCase ) # Put the chunk in its pre-allocated space if isinstance(__lowerCamelCase, __lowerCamelCase ): def assign(__lowerCamelCase, __lowerCamelCase ) -> None: for k, v in da.items(): if isinstance(__lowerCamelCase, __lowerCamelCase ): assign(__lowerCamelCase, da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: SCREAMING_SNAKE_CASE_ = da[k] assign(__lowerCamelCase, __lowerCamelCase ) elif isinstance(__lowerCamelCase, __lowerCamelCase ): for xa, xa in zip(__lowerCamelCase, __lowerCamelCase ): if _add_into_out: xa[i : i + chunk_size] += xa else: SCREAMING_SNAKE_CASE_ = xa elif isinstance(__lowerCamelCase, torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: SCREAMING_SNAKE_CASE_ = output_chunk else: raise ValueError('''Not supported''' ) i += chunk_size SCREAMING_SNAKE_CASE_ = tensor_tree_map(lambda __lowerCamelCase : t.view(orig_batch_dims + t.shape[1:] ), __lowerCamelCase ) return out class UpperCamelCase__ : """simple docstring""" def __init__( self , _A = 512 , ) -> Any: SCREAMING_SNAKE_CASE_ = max_chunk_size SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None def _UpperCamelCase ( self , _A , _A , _A ) -> int: logging.info('''Tuning chunk size...''' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size SCREAMING_SNAKE_CASE_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] SCREAMING_SNAKE_CASE_ = [c for c in candidates if c > min_chunk_size] SCREAMING_SNAKE_CASE_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(_A ) -> bool: try: with torch.no_grad(): fn(*_SCREAMING_SNAKE_CASE , chunk_size=_SCREAMING_SNAKE_CASE ) return True except RuntimeError: return False SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i > min_viable_chunk_size_index: SCREAMING_SNAKE_CASE_ = test_chunk_size(candidates[i] ) if not viable: SCREAMING_SNAKE_CASE_ = (min_viable_chunk_size_index + i) // 2 else: SCREAMING_SNAKE_CASE_ = i SCREAMING_SNAKE_CASE_ = (i + len(_SCREAMING_SNAKE_CASE ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _UpperCamelCase ( self , _A , _A ) -> bool: SCREAMING_SNAKE_CASE_ = True for aa, aa in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): assert type(_SCREAMING_SNAKE_CASE ) == type(_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): consistent &= self._compare_arg_caches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): SCREAMING_SNAKE_CASE_ = [v for _, v in sorted(aa.items() , key=lambda _A : x[0] )] SCREAMING_SNAKE_CASE_ = [v for _, v in sorted(aa.items() , key=lambda _A : x[0] )] consistent &= self._compare_arg_caches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: consistent &= aa == aa return consistent def _UpperCamelCase ( self , _A , _A , _A , ) -> int: SCREAMING_SNAKE_CASE_ = True SCREAMING_SNAKE_CASE_ = tree_map(lambda _A : a.shape if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) else a , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE_ = self._compare_arg_caches(self.cached_arg_data , _SCREAMING_SNAKE_CASE ) else: # Otherwise, we can reuse the precomputed value SCREAMING_SNAKE_CASE_ = False if not consistent: SCREAMING_SNAKE_CASE_ = self._determine_favorable_chunk_size( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) SCREAMING_SNAKE_CASE_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
299
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { """vinvino02/glpn-kitti""": """https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json""", # See all GLPN models at https://huggingface.co/models?filter=glpn } class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = "glpn" def __init__( self , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[2, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[8, 4, 2, 1] , _SCREAMING_SNAKE_CASE=[32, 64, 160, 256] , _SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , _SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[1, 2, 5, 8] , _SCREAMING_SNAKE_CASE=[4, 4, 4, 4] , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-6 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=-1 , **_SCREAMING_SNAKE_CASE , )->Any: '''simple docstring''' super().__init__(**_SCREAMING_SNAKE_CASE ) A_ : Optional[int] = num_channels A_ : Union[str, Any] = num_encoder_blocks A_ : int = depths A_ : Dict = sr_ratios A_ : Any = hidden_sizes A_ : int = patch_sizes A_ : Optional[int] = strides A_ : str = mlp_ratios A_ : List[str] = num_attention_heads A_ : str = hidden_act A_ : int = hidden_dropout_prob A_ : List[Any] = attention_probs_dropout_prob A_ : Optional[Any] = initializer_range A_ : Tuple = drop_path_rate A_ : Optional[int] = layer_norm_eps A_ : List[str] = decoder_hidden_size A_ : List[Any] = max_depth A_ : List[Any] = head_in_index
186
0
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path A : List[Any] = [ {"dataset": "wikipedia", "config_name": "20220301.de"}, {"dataset": "wikipedia", "config_name": "20220301.en"}, {"dataset": "wikipedia", "config_name": "20220301.fr"}, {"dataset": "wikipedia", "config_name": "20220301.frr"}, {"dataset": "wikipedia", "config_name": "20220301.it"}, {"dataset": "wikipedia", "config_name": "20220301.simple"}, {"dataset": "snli", "config_name": "plain_text"}, {"dataset": "eli5", "config_name": "LFQA_reddit"}, {"dataset": "wiki40b", "config_name": "en"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.compressed"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.nq.no_index"}, {"dataset": "wiki_dpr", "config_name": "psgs_w100.multiset.no_index"}, {"dataset": "natural_questions", "config_name": "default"}, ] def a__ ( __UpperCamelCase=True ): if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=SCREAMING_SNAKE_CASE__ ) ) class lowerCamelCase (SCREAMING_SNAKE_CASE__ ): """simple docstring""" lowerCamelCase__ = None lowerCamelCase__ = None def __A ( self : Optional[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : List[str] ) -> Optional[Any]: with TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE_ = dataset_module_factory(__magic_name__ , cache_dir=__magic_name__ ) SCREAMING_SNAKE_CASE_ = import_main_class(dataset_module.module_path , dataset=__magic_name__ ) SCREAMING_SNAKE_CASE_ = builder_cls( cache_dir=__magic_name__ , config_name=__magic_name__ , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE_ = "/".join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=__magic_name__ ).replace(os.sep , "/" ), config.DATASET_INFO_FILENAME, ] ) SCREAMING_SNAKE_CASE_ = cached_path(__magic_name__ , cache_dir=__magic_name__ ) self.assertTrue(os.path.exists(__magic_name__ ) ) @pytest.mark.integration def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp("test_hf_gcp" ) / "test_wikipedia_simple" SCREAMING_SNAKE_CASE_ = dataset_module_factory("wikipedia" , cache_dir=__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = import_main_class(dataset_module.module_path ) SCREAMING_SNAKE_CASE_ = builder_cls( cache_dir=__UpperCamelCase , config_name="20220301.frr" , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam SCREAMING_SNAKE_CASE_ = None builder_instance.download_and_prepare() SCREAMING_SNAKE_CASE_ = builder_instance.as_dataset() assert ds @pytest.mark.integration def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = dataset_module_factory("wikipedia" , cache_dir=__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = import_main_class(dataset_module.module_path , dataset=__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = builder_cls( cache_dir=__UpperCamelCase , config_name="20220301.frr" , hash=dataset_module.hash , ) SCREAMING_SNAKE_CASE_ = builder_instance.as_streaming_dataset() assert ds assert isinstance(__UpperCamelCase , __UpperCamelCase ) assert "train" in ds assert isinstance(ds["train"] , __UpperCamelCase ) assert next(iter(ds["train"] ) )
305
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = np.array([[1, item, train_mtch[i]] for i, item in enumerate(__UpperCamelCase )] ) SCREAMING_SNAKE_CASE_ = np.array(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , __UpperCamelCase ) ) , x.transpose() ) , __UpperCamelCase ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = (1, 2, 1) SCREAMING_SNAKE_CASE_ = (1, 1, 0, 7) SCREAMING_SNAKE_CASE_ = SARIMAX( __UpperCamelCase , exog=__UpperCamelCase , order=__UpperCamelCase , seasonal_order=__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = model.fit(disp=__UpperCamelCase , maxiter=6_0_0 , method="nm" ) SCREAMING_SNAKE_CASE_ = model_fit.predict(1 , len(__UpperCamelCase ) , exog=[test_match] ) return result[0] def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = SVR(kernel="rbf" , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(__UpperCamelCase , __UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regressor.predict(__UpperCamelCase ) return y_pred[0] def a__ ( __UpperCamelCase ): train_user.sort() SCREAMING_SNAKE_CASE_ = np.percentile(__UpperCamelCase , 2_5 ) SCREAMING_SNAKE_CASE_ = np.percentile(__UpperCamelCase , 7_5 ) SCREAMING_SNAKE_CASE_ = qa - qa SCREAMING_SNAKE_CASE_ = qa - (iqr * 0.1) return low_lim def a__ ( __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 for i in list_vote: if i > actual_result: SCREAMING_SNAKE_CASE_ = not_safe + 1 else: if abs(abs(__UpperCamelCase ) - abs(__UpperCamelCase ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) A : Dict = [[1_82_31, 0.0, 1], [2_26_21, 1.0, 2], [1_56_75, 0.0, 3], [2_35_83, 1.0, 4]] A : Optional[Any] = pd.DataFrame( data_input, columns=["total_user", "total_even", "days"] ) A : Union[str, Any] = Normalizer().fit_transform(data_input_df.values) # split data A : Optional[int] = normalize_df[:, 2].tolist() A : List[str] = normalize_df[:, 0].tolist() A : int = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) A : int = normalize_df[:, [1, 2]].tolist() A : Tuple = x[: len(x) - 1] A : str = x[len(x) - 1 :] # for linear regression & sarimax A : Tuple = total_date[: len(total_date) - 1] A : Optional[int] = total_user[: len(total_user) - 1] A : str = total_match[: len(total_match) - 1] A : List[Any] = total_date[len(total_date) - 1 :] A : List[Any] = total_user[len(total_user) - 1 :] A : Optional[Any] = total_match[len(total_match) - 1 :] # voting system with forecasting A : Optional[int] = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data A : str = "" if data_safety_checker(res_vote, tst_user) else "not " print("Today's data is {not_str}safe.")
305
1
'''simple docstring''' import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class _lowerCamelCase ( UpperCamelCase_ ): '''simple docstring''' A_ : Optional[int] = ['image_processor', 'tokenizer'] A_ : Optional[int] = 'BlipImageProcessor' A_ : str = 'AutoTokenizer' def __init__( self : Dict , _A : Any , _A : Union[str, Any] , _A : List[str] ) -> str: super().__init__(lowercase_ , lowercase_ ) # add QFormer tokenizer __magic_name__ : Any = qformer_tokenizer def __call__( self : List[str] , _A : ImageInput = None , _A : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _A : bool = True , _A : Union[bool, str, PaddingStrategy] = False , _A : Union[bool, str, TruncationStrategy] = None , _A : Optional[int] = None , _A : int = 0 , _A : Optional[int] = None , _A : Optional[bool] = None , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = False , _A : bool = True , _A : Optional[Union[str, TensorType]] = None , **_A : Union[str, Any] , ) -> BatchFeature: if images is None and text is None: raise ValueError('You have to specify at least images or text.' ) __magic_name__ : str = BatchFeature() if text is not None: __magic_name__ : Dict = self.tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_token_type_ids=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) encoding.update(lowercase_ ) __magic_name__ : Optional[int] = self.qformer_tokenizer( text=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_token_type_ids=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , ) __magic_name__ : Any = qformer_text_encoding.pop('input_ids' ) __magic_name__ : Tuple = qformer_text_encoding.pop('attention_mask' ) if images is not None: __magic_name__ : str = self.image_processor(lowercase_ , return_tensors=lowercase_ ) encoding.update(lowercase_ ) return encoding def __lowerCAmelCase ( self : Optional[Any] , *_A : int , **_A : List[str] ) -> Optional[int]: return self.tokenizer.batch_decode(*lowercase_ , **lowercase_ ) def __lowerCAmelCase ( self : Union[str, Any] , *_A : List[Any] , **_A : Dict ) -> Optional[Any]: return self.tokenizer.decode(*lowercase_ , **lowercase_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def __lowerCAmelCase ( self : Tuple ) -> List[Any]: __magic_name__ : List[Any] = self.tokenizer.model_input_names __magic_name__ : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def __lowerCAmelCase ( self : Optional[Any] , _A : List[Any] , **_A : Optional[int] ) -> List[str]: if os.path.isfile(lowercase_ ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) __magic_name__ : List[Any] = os.path.join(lowercase_ , 'qformer_tokenizer' ) self.qformer_tokenizer.save_pretrained(lowercase_ ) return super().save_pretrained(lowercase_ , **lowercase_ ) @classmethod def __lowerCAmelCase ( cls : str , _A : str , **_A : Optional[Any] ) -> Tuple: __magic_name__ : Optional[int] = AutoTokenizer.from_pretrained(lowercase_ , subfolder='qformer_tokenizer' ) __magic_name__ : Optional[int] = cls._get_arguments_from_pretrained(lowercase_ , **lowercase_ ) args.append(lowercase_ ) return cls(*lowercase_ )
331
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer lowerCamelCase = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast lowerCamelCase = TaTokenizerFast lowerCamelCase = {'configuration_mt5': ['MT5Config', 'MT5OnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ 'MT5EncoderModel', 'MT5ForConditionalGeneration', 'MT5ForQuestionAnswering', 'MT5Model', 'MT5PreTrainedModel', 'MT5Stack', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['TFMT5EncoderModel', 'TFMT5ForConditionalGeneration', 'TFMT5Model'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['FlaxMT5EncoderModel', 'FlaxMT5ForConditionalGeneration', 'FlaxMT5Model'] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys lowerCamelCase = _LazyModule( __name__, globals()['__file__'], _import_structure, extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast}, module_spec=__spec__, )
199
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): """simple docstring""" A_ = 'roberta' def __init__( self: Tuple , __A: Tuple=5_02_65 , __A: List[Any]=7_68 , __A: Dict=12 , __A: Optional[int]=12 , __A: int=30_72 , __A: List[str]="gelu" , __A: Union[str, Any]=0.1 , __A: Tuple=0.1 , __A: List[Any]=5_12 , __A: List[str]=2 , __A: Tuple=0.02 , __A: int=1e-12 , __A: Dict=1 , __A: Tuple=0 , __A: Optional[int]=2 , __A: Union[str, Any]="absolute" , __A: int=True , __A: List[Any]=None , **__A: List[str] , ) -> Optional[int]: super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) _A = vocab_size _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = hidden_act _A = intermediate_size _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = max_position_embeddings _A = type_vocab_size _A = initializer_range _A = layer_norm_eps _A = position_embedding_type _A = use_cache _A = classifier_dropout class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): """simple docstring""" @property def __A ( self: Dict ) -> Union[str, Any]: if self.task == "multiple-choice": _A = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _A = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
358
__A = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] __A = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] __A = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] __A = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] __A = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] __A = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] __A = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] __A = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
75
0
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def UpperCamelCase__ ( lowercase__ : int = 100_0000 , lowercase__ : int = 10 ): snake_case : defaultdict = defaultdict(lowercase__ ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: snake_case : int = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: snake_case : List[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase__ , outer_width - 1 , 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'{solution() = }')
148
"""simple docstring""" import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder __A = "base_with_context" def UpperCamelCase__ ( lowercase__ : Optional[Any] , lowercase__ : List[Any] ): snake_case : Dict = nn.Parameter(torch.FloatTensor(weights["token_embedder"]["embedding"] ) ) snake_case : Tuple = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=lowercase__ ) for lyr_num, lyr in enumerate(model.encoders ): snake_case : Tuple = weights[F'''layers_{lyr_num}'''] snake_case : List[Any] = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) snake_case : List[Any] = ly_weight["attention"] snake_case : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) snake_case : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) snake_case : Any = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) snake_case : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) snake_case : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) snake_case : Dict = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) snake_case : str = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) snake_case : List[Any] = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def UpperCamelCase__ ( lowercase__ : Tuple , lowercase__ : List[Any] ): snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(weights["input_proj"]["kernel"].T ) ) snake_case : Union[str, Any] = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=lowercase__ ) for lyr_num, lyr in enumerate(model.encoders ): snake_case : str = weights[F'''layers_{lyr_num}'''] snake_case : Any = ly_weight["attention"] snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) snake_case : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) snake_case : Dict = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) snake_case : int = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) snake_case : List[Any] = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) snake_case : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) snake_case : str = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) snake_case : int = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def UpperCamelCase__ ( lowercase__ : str , lowercase__ : Union[str, Any] ): snake_case : int = nn.Parameter(torch.FloatTensor(weights["time_emb_dense0"]["kernel"].T ) ) snake_case : List[Any] = nn.Parameter(torch.FloatTensor(weights["time_emb_dense1"]["kernel"].T ) ) snake_case : Tuple = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=lowercase__ ) snake_case : Tuple = nn.Parameter( torch.FloatTensor(weights["continuous_inputs_projection"]["kernel"].T ) ) for lyr_num, lyr in enumerate(model.decoders ): snake_case : Union[str, Any] = weights[F'''layers_{lyr_num}'''] snake_case : List[str] = nn.Parameter( torch.FloatTensor(ly_weight["pre_self_attention_layer_norm"]["scale"] ) ) snake_case : Any = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_0"]["DenseGeneral_0"]["kernel"].T ) ) snake_case : Union[str, Any] = ly_weight["self_attention"] snake_case : List[str] = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) snake_case : Any = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) snake_case : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) snake_case : str = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) snake_case : List[str] = ly_weight["MultiHeadDotProductAttention_0"] snake_case : Tuple = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) snake_case : Dict = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) snake_case : str = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) snake_case : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) snake_case : Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight["pre_cross_attention_layer_norm"]["scale"] ) ) snake_case : Dict = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) snake_case : Tuple = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_1"]["DenseGeneral_0"]["kernel"].T ) ) snake_case : Tuple = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) snake_case : Any = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) snake_case : str = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) snake_case : List[str] = nn.Parameter(torch.FloatTensor(weights["decoder_norm"]["scale"] ) ) snake_case : List[Any] = nn.Parameter(torch.FloatTensor(weights["spec_out_dense"]["kernel"].T ) ) return model def UpperCamelCase__ ( lowercase__ : Any ): snake_case : Union[str, Any] = checkpoints.load_tax_checkpoint(args.checkpoint_path ) snake_case : List[Any] = jnp.tree_util.tree_map(onp.array , lowercase__ ) snake_case : Tuple = [ "from __gin__ import dynamic_registration", "from music_spectrogram_diffusion.models.diffusion import diffusion_utils", "diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0", "diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()", ] snake_case : List[str] = os.path.join(args.checkpoint_path , ".." , "config.gin" ) snake_case : List[str] = inference.parse_training_gin_file(lowercase__ , lowercase__ ) snake_case : List[Any] = inference.InferenceModel(args.checkpoint_path , lowercase__ ) snake_case : str = DDPMScheduler(beta_schedule="squaredcos_cap_v2" , variance_type="fixed_large" ) snake_case : int = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["inputs"] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) snake_case : Tuple = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["targets_context"] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) snake_case : str = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["targets_context"] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) snake_case : Optional[int] = load_notes_encoder(ta_checkpoint["target"]["token_encoder"] , lowercase__ ) snake_case : Any = load_continuous_encoder(ta_checkpoint["target"]["continuous_encoder"] , lowercase__ ) snake_case : List[Any] = load_decoder(ta_checkpoint["target"]["decoder"] , lowercase__ ) snake_case : int = OnnxRuntimeModel.from_pretrained("kashif/soundstream_mel_decoder" ) snake_case : Tuple = SpectrogramDiffusionPipeline( notes_encoder=lowercase__ , continuous_encoder=lowercase__ , decoder=lowercase__ , scheduler=lowercase__ , melgan=lowercase__ , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("--output_path", default=None, type=str, required=True, help="Path to the converted model.") parser.add_argument( "--save", default=True, type=bool, required=False, help="Whether to save the converted model or not." ) parser.add_argument( "--checkpoint_path", default=f'{MODEL}/checkpoint_500000', type=str, required=False, help="Path to the original jax model checkpoint.", ) __A = parser.parse_args() main(args)
148
1
'''simple docstring''' import os from datetime import datetime as dt from github import Github __a = [ "good first issue", "feature request", "wip", ] def __snake_case( ) -> Any: snake_case__ : List[Any] = Github(os.environ["""GITHUB_TOKEN"""] ) snake_case__ : Union[str, Any] = g.get_repo("""huggingface/accelerate""" ) snake_case__ : List[Any] = repo.get_issues(state="""open""" ) for issue in open_issues: snake_case__ : Optional[int] = sorted([comment for comment in issue.get_comments()] , key=lambda _lowerCAmelCase : i.created_at , reverse=_lowerCAmelCase ) snake_case__ : int = comments[0] if len(_lowerCAmelCase ) > 0 else None snake_case__ : Optional[Any] = dt.utcnow() snake_case__ : Union[str, Any] = (current_time - issue.updated_at).days snake_case__ : int = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state="""closed""" ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) if __name__ == "__main__": main()
43
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCAmelCase_ : """simple docstring""" def __init__( self : Dict ): snake_case__ : List[str] = {} def lowerCamelCase ( self : List[Any] , snake_case_ : int , snake_case_ : Union[str, Any] , snake_case_ : Tuple=1 ): if self.graph.get(snake_case_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: snake_case__ : Tuple = [[w, v]] if not self.graph.get(snake_case_ ): snake_case__ : Optional[Any] = [] def lowerCamelCase ( self : List[str] ): return list(self.graph ) def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Optional[int] , snake_case_ : Dict ): if self.graph.get(snake_case_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(snake_case_ ) def lowerCamelCase ( self : Optional[int] , snake_case_ : Tuple=-2 , snake_case_ : Tuple=-1 ): if s == d: return [] snake_case__ : Optional[Any] = [] snake_case__ : List[Any] = [] if s == -2: snake_case__ : Union[str, Any] = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : Optional[int] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : str = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(snake_case_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : Union[str, Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(snake_case_ ) != 0: snake_case__ : Tuple = stack[len(snake_case_ ) - 1] else: snake_case__ : Tuple = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return visited def lowerCamelCase ( self : Optional[Any] , snake_case_ : Any=-1 ): if c == -1: snake_case__ : Union[str, Any] = floor(random() * 10_000 ) + 10 for i in range(snake_case_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): snake_case__ : str = floor(random() * c ) + 1 if n != i: self.add_pair(snake_case_ , snake_case_ , 1 ) def lowerCamelCase ( self : List[Any] , snake_case_ : str=-2 ): snake_case__ : Tuple = deque() snake_case__ : str = [] if s == -2: snake_case__ : str = list(self.graph )[0] d.append(snake_case_ ) visited.append(snake_case_ ) while d: snake_case__ : Dict = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Optional[Any] ): snake_case__ : Optional[int] = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def lowerCamelCase ( self : Optional[Any] , snake_case_ : Any ): return len(self.graph[u] ) def lowerCamelCase ( self : List[str] , snake_case_ : Union[str, Any]=-2 ): snake_case__ : str = [] snake_case__ : Any = [] if s == -2: snake_case__ : Any = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : Dict = s snake_case__ : List[Any] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : List[str] = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(snake_case_ ) != 0: snake_case__ : Optional[int] = stack[len(snake_case_ ) - 1] else: snake_case__ : Union[str, Any] = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return sorted_nodes def lowerCamelCase ( self : int ): snake_case__ : List[str] = [] snake_case__ : Union[str, Any] = [] snake_case__ : Optional[int] = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : List[Any] = -2 snake_case__ : Union[str, Any] = [] snake_case__ : Optional[Any] = s snake_case__ : Optional[Any] = False snake_case__ : Any = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : Tuple = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): snake_case__ : str = len(snake_case_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : Dict = node[1] break # check if all the children are visited if s == ss: stack.pop() snake_case__ : List[str] = True if len(snake_case_ ) != 0: snake_case__ : Any = stack[len(snake_case_ ) - 1] else: snake_case__ : Optional[Any] = False indirect_parents.append(snake_case_ ) snake_case__ : Union[str, Any] = s snake_case__ : str = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return list(snake_case_ ) def lowerCamelCase ( self : Union[str, Any] ): snake_case__ : List[str] = [] snake_case__ : str = [] snake_case__ : Tuple = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : Optional[int] = -2 snake_case__ : List[str] = [] snake_case__ : Optional[int] = s snake_case__ : str = False snake_case__ : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): snake_case__ : Optional[Any] = len(snake_case_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() snake_case__ : List[str] = True if len(snake_case_ ) != 0: snake_case__ : List[str] = stack[len(snake_case_ ) - 1] else: snake_case__ : int = False indirect_parents.append(snake_case_ ) snake_case__ : Any = s snake_case__ : Tuple = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return False def lowerCamelCase ( self : int , snake_case_ : List[Any]=-2 , snake_case_ : List[str]=-1 ): snake_case__ : List[Any] = time() self.dfs(snake_case_ , snake_case_ ) snake_case__ : Optional[Any] = time() return end - begin def lowerCamelCase ( self : int , snake_case_ : List[str]=-2 ): snake_case__ : Any = time() self.bfs(snake_case_ ) snake_case__ : List[str] = time() return end - begin class UpperCAmelCase_ : """simple docstring""" def __init__( self : List[str] ): snake_case__ : List[str] = {} def lowerCamelCase ( self : Union[str, Any] , snake_case_ : str , snake_case_ : int , snake_case_ : Union[str, Any]=1 ): # check if the u exists if self.graph.get(snake_case_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist snake_case__ : Dict = [[w, v]] # add the other way if self.graph.get(snake_case_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist snake_case__ : Any = [[w, u]] def lowerCamelCase ( self : int , snake_case_ : Optional[int] , snake_case_ : Union[str, Any] ): if self.graph.get(snake_case_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(snake_case_ ) # the other way round if self.graph.get(snake_case_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(snake_case_ ) def lowerCamelCase ( self : Any , snake_case_ : Tuple=-2 , snake_case_ : Union[str, Any]=-1 ): if s == d: return [] snake_case__ : Dict = [] snake_case__ : Optional[int] = [] if s == -2: snake_case__ : Any = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : Optional[int] = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : Optional[int] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(snake_case_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(snake_case_ ) != 0: snake_case__ : str = stack[len(snake_case_ ) - 1] else: snake_case__ : Union[str, Any] = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return visited def lowerCamelCase ( self : List[str] , snake_case_ : str=-1 ): if c == -1: snake_case__ : Union[str, Any] = floor(random() * 10_000 ) + 10 for i in range(snake_case_ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): snake_case__ : List[str] = floor(random() * c ) + 1 if n != i: self.add_pair(snake_case_ , snake_case_ , 1 ) def lowerCamelCase ( self : str , snake_case_ : Dict=-2 ): snake_case__ : Union[str, Any] = deque() snake_case__ : Optional[int] = [] if s == -2: snake_case__ : Tuple = list(self.graph )[0] d.append(snake_case_ ) visited.append(snake_case_ ) while d: snake_case__ : str = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def lowerCamelCase ( self : Any , snake_case_ : Union[str, Any] ): return len(self.graph[u] ) def lowerCamelCase ( self : Optional[Any] ): snake_case__ : str = [] snake_case__ : List[str] = [] snake_case__ : str = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : Tuple = -2 snake_case__ : Optional[int] = [] snake_case__ : str = s snake_case__ : int = False snake_case__ : Dict = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : Dict = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): snake_case__ : Tuple = len(snake_case_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() snake_case__ : Optional[Any] = True if len(snake_case_ ) != 0: snake_case__ : Dict = stack[len(snake_case_ ) - 1] else: snake_case__ : int = False indirect_parents.append(snake_case_ ) snake_case__ : int = s snake_case__ : Tuple = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return list(snake_case_ ) def lowerCamelCase ( self : str ): snake_case__ : Tuple = [] snake_case__ : Tuple = [] snake_case__ : Any = list(self.graph )[0] stack.append(snake_case_ ) visited.append(snake_case_ ) snake_case__ : List[Any] = -2 snake_case__ : Dict = [] snake_case__ : str = s snake_case__ : Optional[Any] = False snake_case__ : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: snake_case__ : Dict = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): snake_case__ : Optional[int] = len(snake_case_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) snake_case__ : int = node[1] break # check if all the children are visited if s == ss: stack.pop() snake_case__ : Any = True if len(snake_case_ ) != 0: snake_case__ : Any = stack[len(snake_case_ ) - 1] else: snake_case__ : Tuple = False indirect_parents.append(snake_case_ ) snake_case__ : Optional[int] = s snake_case__ : List[Any] = ss # check if se have reached the starting point if len(snake_case_ ) == 0: return False def lowerCamelCase ( self : Union[str, Any] ): return list(self.graph ) def lowerCamelCase ( self : Union[str, Any] , snake_case_ : int=-2 , snake_case_ : Any=-1 ): snake_case__ : int = time() self.dfs(snake_case_ , snake_case_ ) snake_case__ : List[str] = time() return end - begin def lowerCamelCase ( self : List[Any] , snake_case_ : Union[str, Any]=-2 ): snake_case__ : Optional[int] = time() self.bfs(snake_case_ ) snake_case__ : str = time() return end - begin
43
1
import requests A__ = '''''' # <-- Put your OpenWeatherMap appid here! A__ = '''https://api.openweathermap.org/data/2.5/''' def _lowerCAmelCase ( __lowerCAmelCase = "Chicago" , __lowerCAmelCase = APPID ) -> dict: """simple docstring""" return requests.get(URL_BASE + '''weather''' , params=locals() ).json() def _lowerCAmelCase ( __lowerCAmelCase = "Kolkata, India" , __lowerCAmelCase = APPID ) -> dict: """simple docstring""" return requests.get(URL_BASE + '''forecast''' , params=locals() ).json() def _lowerCAmelCase ( __lowerCAmelCase = 55.68 , __lowerCAmelCase = 12.57 , __lowerCAmelCase = APPID ) -> dict: """simple docstring""" return requests.get(URL_BASE + '''onecall''' , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: A__ = input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
230
from math import ceil, sqrt def _lowerCAmelCase ( __lowerCAmelCase = 1000000 ) -> int: """simple docstring""" snake_case__ : Dict = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: snake_case__ : Any = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: snake_case__ : int = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
230
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class lowerCAmelCase__ ( UpperCAmelCase__ ): lowerCAmelCase : Optional[int] = "t5" lowerCAmelCase : Optional[int] = ["past_key_values"] lowerCAmelCase : str = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self : List[str] , lowerCamelCase__ : List[str]=3_21_28 , lowerCamelCase__ : str=5_12 , lowerCamelCase__ : Union[str, Any]=64 , lowerCamelCase__ : Any=20_48 , lowerCamelCase__ : Any=6 , lowerCamelCase__ : Optional[int]=None , lowerCamelCase__ : str=8 , lowerCamelCase__ : int=32 , lowerCamelCase__ : List[str]=1_28 , lowerCamelCase__ : Union[str, Any]=0.1 , lowerCamelCase__ : Any=1E-6 , lowerCamelCase__ : Optional[int]=1.0 , lowerCamelCase__ : Tuple="relu" , lowerCamelCase__ : str=True , lowerCamelCase__ : Any=True , lowerCamelCase__ : Any=0 , lowerCamelCase__ : Union[str, Any]=1 , **lowerCamelCase__ : Optional[Any] , ) ->str: '''simple docstring''' _UpperCAmelCase : int = vocab_size _UpperCAmelCase : Any = d_model _UpperCAmelCase : int = d_kv _UpperCAmelCase : List[Any] = d_ff _UpperCAmelCase : Union[str, Any] = num_layers _UpperCAmelCase : List[str] = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry _UpperCAmelCase : str = num_heads _UpperCAmelCase : Any = relative_attention_num_buckets _UpperCAmelCase : Optional[Any] = relative_attention_max_distance _UpperCAmelCase : Optional[int] = dropout_rate _UpperCAmelCase : List[str] = layer_norm_epsilon _UpperCAmelCase : Tuple = initializer_factor _UpperCAmelCase : Tuple = feed_forward_proj _UpperCAmelCase : List[Any] = use_cache _UpperCAmelCase : Union[str, Any] = self.feed_forward_proj.split("-" ) _UpperCAmelCase : List[str] = act_info[-1] _UpperCAmelCase : List[str] = act_info[0] == "gated" if len(lowerCamelCase__ ) > 1 and act_info[0] != "gated" or len(lowerCamelCase__ ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": _UpperCAmelCase : str = "gelu_new" super().__init__( pad_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , is_encoder_decoder=lowerCamelCase__ , **lowerCamelCase__ , ) class lowerCAmelCase__ ( UpperCAmelCase__ ): @property def lowerCAmelCase__ ( self : str ) ->Mapping[str, Mapping[int, str]]: '''simple docstring''' _UpperCAmelCase : List[Any] = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: _UpperCAmelCase : Optional[Any] = "past_encoder_sequence + sequence" _UpperCAmelCase : Union[str, Any] = {0: "batch"} _UpperCAmelCase : Any = {0: "batch", 1: "past_decoder_sequence + sequence"} else: _UpperCAmelCase : List[str] = {0: "batch", 1: "decoder_sequence"} _UpperCAmelCase : List[Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase__ , direction="inputs" ) return common_inputs @property def lowerCAmelCase__ ( self : List[Any] ) ->int: '''simple docstring''' return 13
322
'''simple docstring''' import pytest lowerCamelCase__ = '__dummy_dataset1__' lowerCamelCase__ = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def __lowerCAmelCase (): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def __lowerCAmelCase (): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def __lowerCAmelCase (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): _UpperCAmelCase : Optional[Any] = dataset_loading_script_name _UpperCAmelCase : Any = tmp_path / "datasets" / script_name script_dir.mkdir(parents=__lowerCAmelCase ) _UpperCAmelCase : Optional[Any] = script_dir / F"""{script_name}.py""" with open(__lowerCAmelCase , "w" ) as f: f.write(__lowerCAmelCase ) return str(__lowerCAmelCase )
322
1
import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" , [ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(__magic_name__ , i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCamelCase ( __magic_name__ : Any , __magic_name__ : Any ) -> Any: """simple docstring""" lowercase__ = _distribute_shards(**__magic_name__ ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" , [ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] , ) def UpperCamelCase ( __magic_name__ : List[str] , __magic_name__ : List[str] , __magic_name__ : Union[str, Any] ) -> int: """simple docstring""" lowercase__ = _split_gen_kwargs(__magic_name__ , __magic_name__ ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" , [ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] , ) def UpperCamelCase ( __magic_name__ : str , __magic_name__ : Tuple ) -> List[Any]: """simple docstring""" if expected is RuntimeError: with pytest.raises(__magic_name__ ): _number_of_shards_in_gen_kwargs(__magic_name__ ) else: lowercase__ = _number_of_shards_in_gen_kwargs(__magic_name__ ) assert out == expected
305
def UpperCamelCase ( __magic_name__ : str ) -> int: """simple docstring""" assert column_title.isupper() lowercase__ = 0 lowercase__ = len(__magic_name__ ) - 1 lowercase__ = 0 while index >= 0: lowercase__ = (ord(column_title[index] ) - 64) * pow(26 , __magic_name__ ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
305
1
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class a ( unittest.TestCase ): """simple docstring""" @require_torch def UpperCAmelCase ( self ) -> Dict: _A = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) _A = load_dataset("""ashraq/esc50""" ) _A = dataset["""train"""]["""audio"""][-1]["""array"""] _A = audio_classifier(lowerCAmelCase_ , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [{"""score""": 0.501, """label""": """Sound of a dog"""}, {"""score""": 0.499, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def UpperCAmelCase ( self ) -> Tuple: pass @slow @require_torch def UpperCAmelCase ( self ) -> Union[str, Any]: _A = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog _A = load_dataset("""ashraq/esc50""" ) _A = dataset["""train"""]["""audio"""][-1]["""array"""] _A = audio_classifier(lowerCAmelCase_ , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ {"""score""": 0.999, """label""": """Sound of a dog"""}, {"""score""": 0.001, """label""": """Sound of vaccum cleaner"""}, ] , ) _A = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ [ {"""score""": 0.999, """label""": """Sound of a dog"""}, {"""score""": 0.001, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) _A = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(lowerCAmelCase_ ) , [ [ {"""score""": 0.999, """label""": """Sound of a dog"""}, {"""score""": 0.001, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def UpperCAmelCase ( self ) -> Optional[Any]: pass
81
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run _SCREAMING_SNAKE_CASE = True except (ImportError, AttributeError): _SCREAMING_SNAKE_CASE = object def snake_case ( *snake_case__ :Optional[int] , **snake_case__ :Any) -> int: pass _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = logging.get_logger('transformers-cli/serving') def snake_case ( snake_case__ :Namespace) -> Dict: _A = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(snake_case__ , args.host , args.port , args.workers) class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :dict class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :List[str] lowerCamelCase :Optional[List[int]] class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :str class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :Any class a ( __lowerCAmelCase ): """simple docstring""" @staticmethod def UpperCAmelCase ( lowerCAmelCase_ ) -> Any: _A = parser.add_parser( """serve""" , help="""CLI tool to run inference requests through REST and GraphQL endpoints.""" ) serve_parser.add_argument( """--task""" , type=lowerCAmelCase_ , choices=get_supported_tasks() , help="""The task to run the pipeline on""" , ) serve_parser.add_argument("""--host""" , type=lowerCAmelCase_ , default="""localhost""" , help="""Interface the server will listen on.""" ) serve_parser.add_argument("""--port""" , type=lowerCAmelCase_ , default=88_88 , help="""Port the serving will listen to.""" ) serve_parser.add_argument("""--workers""" , type=lowerCAmelCase_ , default=1 , help="""Number of http workers""" ) serve_parser.add_argument("""--model""" , type=lowerCAmelCase_ , help="""Model's name or path to stored model.""" ) serve_parser.add_argument("""--config""" , type=lowerCAmelCase_ , help="""Model's config name or path to stored model.""" ) serve_parser.add_argument("""--tokenizer""" , type=lowerCAmelCase_ , help="""Tokenizer name to use.""" ) serve_parser.add_argument( """--device""" , type=lowerCAmelCase_ , default=-1 , help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" , ) serve_parser.set_defaults(func=lowerCAmelCase_ ) def __init__( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _A = pipeline _A = host _A = port _A = workers if not _serve_dependencies_installed: raise RuntimeError( """Using serve command requires FastAPI and uvicorn. """ """Please install transformers with [serving]: pip install \"transformers[serving]\".""" """Or install FastAPI and uvicorn separately.""" ) else: logger.info(F'''Serving model over {host}:{port}''' ) _A = FastAPI( routes=[ APIRoute( """/""" , self.model_info , response_model=lowerCAmelCase_ , response_class=lowerCAmelCase_ , methods=["""GET"""] , ), APIRoute( """/tokenize""" , self.tokenize , response_model=lowerCAmelCase_ , response_class=lowerCAmelCase_ , methods=["""POST"""] , ), APIRoute( """/detokenize""" , self.detokenize , response_model=lowerCAmelCase_ , response_class=lowerCAmelCase_ , methods=["""POST"""] , ), APIRoute( """/forward""" , self.forward , response_model=lowerCAmelCase_ , response_class=lowerCAmelCase_ , methods=["""POST"""] , ), ] , timeout=6_00 , ) def UpperCAmelCase ( self ) -> str: run(self._app , host=self.host , port=self.port , workers=self.workers ) def UpperCAmelCase ( self ) -> Union[str, Any]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def UpperCAmelCase ( self , lowerCAmelCase_ = Body(lowerCAmelCase_ , embed=lowerCAmelCase_ ) , lowerCAmelCase_ = Body(lowerCAmelCase_ , embed=lowerCAmelCase_ ) ) -> List[Any]: try: _A = self._pipeline.tokenizer.tokenize(lowerCAmelCase_ ) if return_ids: _A = self._pipeline.tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) return ServeTokenizeResult(tokens=lowerCAmelCase_ , tokens_ids=lowerCAmelCase_ ) else: return ServeTokenizeResult(tokens=lowerCAmelCase_ ) except Exception as e: raise HTTPException(status_code=5_00 , detail={"""model""": """""", """error""": str(lowerCAmelCase_ )} ) def UpperCAmelCase ( self , lowerCAmelCase_ = Body(lowerCAmelCase_ , embed=lowerCAmelCase_ ) , lowerCAmelCase_ = Body(lowerCAmelCase_ , embed=lowerCAmelCase_ ) , lowerCAmelCase_ = Body(lowerCAmelCase_ , embed=lowerCAmelCase_ ) , ) -> Dict: try: _A = self._pipeline.tokenizer.decode(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return ServeDeTokenizeResult(model="""""" , text=lowerCAmelCase_ ) except Exception as e: raise HTTPException(status_code=5_00 , detail={"""model""": """""", """error""": str(lowerCAmelCase_ )} ) async def UpperCAmelCase ( self , lowerCAmelCase_=Body(lowerCAmelCase_ , embed=lowerCAmelCase_ ) ) -> Any: # Check we don't have empty string if len(lowerCAmelCase_ ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model _A = self._pipeline(lowerCAmelCase_ ) return ServeForwardResult(output=lowerCAmelCase_ ) except Exception as e: raise HTTPException(5_00 , {"""error""": str(lowerCAmelCase_ )} )
81
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _UpperCAmelCase : int = {"""configuration_speech_encoder_decoder""": ["""SpeechEncoderDecoderConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : Tuple = ["""SpeechEncoderDecoderModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : int = ["""FlaxSpeechEncoderDecoderModel"""] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys _UpperCAmelCase : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
50
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging a_ : Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class __UpperCamelCase ( lowerCamelCase__ ): lowercase : Tuple =['pixel_values'] def __init__( self, lowerCAmelCase = True, lowerCAmelCase = None, lowerCAmelCase = PILImageResampling.BICUBIC, lowerCAmelCase = True, lowerCAmelCase = None, lowerCAmelCase = True, lowerCAmelCase = 1 / 255, lowerCAmelCase = True, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = True, **lowerCAmelCase, ): """simple docstring""" super().__init__(**lowerCAmelCase ) lowerCamelCase_ =size if size is not None else {'''shortest_edge''': 224} lowerCamelCase_ =get_size_dict(lowerCAmelCase, default_to_square=lowerCAmelCase ) lowerCamelCase_ =crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} lowerCamelCase_ =get_size_dict(lowerCAmelCase, default_to_square=lowerCAmelCase, param_name='''crop_size''' ) lowerCamelCase_ =do_resize lowerCamelCase_ =size lowerCamelCase_ =resample lowerCamelCase_ =do_center_crop lowerCamelCase_ =crop_size lowerCamelCase_ =do_rescale lowerCamelCase_ =rescale_factor lowerCamelCase_ =do_normalize lowerCamelCase_ =image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowerCamelCase_ =image_std if image_std is not None else OPENAI_CLIP_STD lowerCamelCase_ =do_convert_rgb def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = PILImageResampling.BICUBIC, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =get_size_dict(lowerCAmelCase, default_to_square=lowerCAmelCase ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) lowerCamelCase_ =get_resize_output_image_size(lowerCAmelCase, size=size['''shortest_edge'''], default_to_square=lowerCAmelCase ) return resize(lowerCAmelCase, size=lowerCAmelCase, resample=lowerCAmelCase, data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =get_size_dict(lowerCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(lowerCAmelCase, size=(size['''height'''], size['''width''']), data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" return rescale(lowerCAmelCase, scale=lowerCAmelCase, data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" return normalize(lowerCAmelCase, mean=lowerCAmelCase, std=lowerCAmelCase, data_format=lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = ChannelDimension.FIRST, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =do_resize if do_resize is not None else self.do_resize lowerCamelCase_ =size if size is not None else self.size lowerCamelCase_ =get_size_dict(lowerCAmelCase, param_name='''size''', default_to_square=lowerCAmelCase ) lowerCamelCase_ =resample if resample is not None else self.resample lowerCamelCase_ =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase_ =crop_size if crop_size is not None else self.crop_size lowerCamelCase_ =get_size_dict(lowerCAmelCase, param_name='''crop_size''', default_to_square=lowerCAmelCase ) lowerCamelCase_ =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase_ =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase_ =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase_ =image_mean if image_mean is not None else self.image_mean lowerCamelCase_ =image_std if image_std is not None else self.image_std lowerCamelCase_ =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowerCamelCase_ =make_list_of_images(lowerCAmelCase ) if not valid_images(lowerCAmelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowerCamelCase_ =[convert_to_rgb(lowerCAmelCase ) for image in images] # All transformations expect numpy arrays. lowerCamelCase_ =[to_numpy_array(lowerCAmelCase ) for image in images] if do_resize: lowerCamelCase_ =[self.resize(image=lowerCAmelCase, size=lowerCAmelCase, resample=lowerCAmelCase ) for image in images] if do_center_crop: lowerCamelCase_ =[self.center_crop(image=lowerCAmelCase, size=lowerCAmelCase ) for image in images] if do_rescale: lowerCamelCase_ =[self.rescale(image=lowerCAmelCase, scale=lowerCAmelCase ) for image in images] if do_normalize: lowerCamelCase_ =[self.normalize(image=lowerCAmelCase, mean=lowerCAmelCase, std=lowerCAmelCase ) for image in images] lowerCamelCase_ =[to_channel_dimension_format(lowerCAmelCase, lowerCAmelCase ) for image in images] lowerCamelCase_ ={'''pixel_values''': images} return BatchFeature(data=lowerCAmelCase, tensor_type=lowerCAmelCase )
75
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''facebook/vit-mae-base''': '''https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json''', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCAmelCase_ ( UpperCAmelCase_ ): '''simple docstring''' UpperCamelCase_ : Optional[int] = """vit_mae""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : Any=7_68 , SCREAMING_SNAKE_CASE_ : Dict=12 , SCREAMING_SNAKE_CASE_ : int=12 , SCREAMING_SNAKE_CASE_ : Dict=30_72 , SCREAMING_SNAKE_CASE_ : Tuple="gelu" , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=0.0 , SCREAMING_SNAKE_CASE_ : Any=0.02 , SCREAMING_SNAKE_CASE_ : Optional[int]=1E-12 , SCREAMING_SNAKE_CASE_ : Dict=2_24 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE_ : Dict=3 , SCREAMING_SNAKE_CASE_ : List[Any]=True , SCREAMING_SNAKE_CASE_ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE_ : Optional[Any]=5_12 , SCREAMING_SNAKE_CASE_ : Optional[int]=8 , SCREAMING_SNAKE_CASE_ : Optional[int]=20_48 , SCREAMING_SNAKE_CASE_ : int=0.75 , SCREAMING_SNAKE_CASE_ : Optional[Any]=False , **SCREAMING_SNAKE_CASE_ : List[Any] , ) -> Tuple: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) A: List[Any] = hidden_size A: Tuple = num_hidden_layers A: int = num_attention_heads A: Union[str, Any] = intermediate_size A: str = hidden_act A: Optional[Any] = hidden_dropout_prob A: Tuple = attention_probs_dropout_prob A: Optional[Any] = initializer_range A: Tuple = layer_norm_eps A: Union[str, Any] = image_size A: Tuple = patch_size A: int = num_channels A: List[str] = qkv_bias A: Dict = decoder_num_attention_heads A: List[str] = decoder_hidden_size A: Any = decoder_num_hidden_layers A: str = decoder_intermediate_size A: Union[str, Any] = mask_ratio A: Any = norm_pix_loss
334
'''simple docstring''' from collections import deque class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> None: '''simple docstring''' A: Union[str, Any] = process_name # process name A: List[str] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time A: Dict = arrival_time A: Optional[Any] = burst_time # remaining burst time A: Any = 0 # total time of the process wait in ready queue A: Any = 0 # time from arrival time to completion time class lowerCAmelCase_ : '''simple docstring''' def __init__( self : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : list[int] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int , ) -> None: '''simple docstring''' A: Dict = number_of_queues # time slice of queues that round robin algorithm applied A: int = time_slices # unfinished process is in this ready_queue A: Tuple = queue # current time A: int = current_time # finished process is in this sequence queue A: deque[Process] = deque() def _snake_case ( self : List[Any] ) -> list[str]: '''simple docstring''' A: str = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Optional[int] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _snake_case ( self : Any , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: Any = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _snake_case ( self : str , SCREAMING_SNAKE_CASE_ : list[Process] ) -> list[int]: '''simple docstring''' A: List[Any] = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): completion_times.append(queue[i].stop_time ) return completion_times def _snake_case ( self : Tuple , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> list[int]: '''simple docstring''' return [q.burst_time for q in queue] def _snake_case ( self : int , SCREAMING_SNAKE_CASE_ : Process ) -> int: '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _snake_case ( self : List[str] , SCREAMING_SNAKE_CASE_ : deque[Process] ) -> deque[Process]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of finished process while len(SCREAMING_SNAKE_CASE_ ) != 0: A: Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 A: Any = 0 # set the process's turnaround time because it is finished A: int = self.current_time - cp.arrival_time # set the completion time A: List[str] = self.current_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _snake_case ( self : List[Any] , SCREAMING_SNAKE_CASE_ : deque[Process] , SCREAMING_SNAKE_CASE_ : int ) -> tuple[deque[Process], deque[Process]]: '''simple docstring''' A: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(SCREAMING_SNAKE_CASE_ ) ): A: Dict = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(SCREAMING_SNAKE_CASE_ ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time A: Optional[Any] = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(SCREAMING_SNAKE_CASE_ ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished A: int = 0 # set the finish time A: Union[str, Any] = self.current_time # update the process' turnaround time because it is finished A: Tuple = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(SCREAMING_SNAKE_CASE_ ) self.finish_queue.extend(SCREAMING_SNAKE_CASE_ ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _snake_case ( self : Optional[Any] ) -> deque[Process]: '''simple docstring''' for i in range(self.number_of_queues - 1 ): A , A: Optional[Any] = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])}) UpperCamelCase = Process('''P1''', 0, 53) UpperCamelCase = Process('''P2''', 0, 17) UpperCamelCase = Process('''P3''', 0, 68) UpperCamelCase = Process('''P4''', 0, 24) UpperCamelCase = 3 UpperCamelCase = [17, 25] UpperCamelCase = deque([Pa, Pa, Pa, Pa]) UpperCamelCase = MLFQ(number_of_queues, time_slices, queue, 0) UpperCamelCase = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print completion times of processes(P1, P2, P3, P4) print( f'completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print sequence of finished processes print( f'sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}' )
334
1
import os import jsonlines import numpy as np from tqdm import tqdm __lowercase = 2048 __lowercase = 4096 __lowercase = 42 __lowercase = os.environ.pop('''PROCESS_TRAIN''', '''false''') __lowercase = {'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4} def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def choose_first(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ): assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) == 1: __UpperCamelCase :str = answer[0] return {k: [answer[k]] for k in answer} if is_long_answer else answer for a in answer: if is_long_answer: __UpperCamelCase :List[Any] = {k: [a[k]] for k in a} if len(a['''start_token'''] ) > 0: break return a __UpperCamelCase :Union[str, Any] = {'''id''': example['''id''']} __UpperCamelCase :Optional[Any] = example['''annotations'''] __UpperCamelCase :Tuple = annotation['''yes_no_answer'''] if 0 in yes_no_answer or 1 in yes_no_answer: __UpperCamelCase :List[Any] = ['''yes'''] if 1 in yes_no_answer else ['''no'''] __UpperCamelCase :Tuple = [] __UpperCamelCase :List[Any] = [] __UpperCamelCase :Tuple = ['''<cls>'''] else: __UpperCamelCase :Optional[Any] = ['''short'''] __UpperCamelCase :Union[str, Any] = choose_first(annotation['''short_answers'''] ) if len(out['''start_token'''] ) == 0: # answer will be long if short is not available __UpperCamelCase :int = ['''long'''] __UpperCamelCase :List[Any] = choose_first(annotation['''long_answer'''] , is_long_answer=SCREAMING_SNAKE_CASE ) __UpperCamelCase :str = [] answer.update(SCREAMING_SNAKE_CASE ) # disregard some samples if len(answer['''start_token'''] ) > 1 or answer["start_token"] == answer["end_token"]: __UpperCamelCase :Any = True else: __UpperCamelCase :str = False __UpperCamelCase :Tuple = ['''start_token''', '''end_token''', '''start_byte''', '''end_byte''', '''text'''] if not all(isinstance(answer[k] , SCREAMING_SNAKE_CASE ) for k in cols ): raise ValueError('''Issue in ID''' , example['''id'''] ) return answer def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ): '''simple docstring''' __UpperCamelCase :Tuple = _get_single_answer(SCREAMING_SNAKE_CASE ) # bytes are of no use del answer["start_byte"] del answer["end_byte"] # handle yes_no answers explicitly if answer["category"][0] in ["yes", "no"]: # category is list with one element __UpperCamelCase :str = example['''document''']['''tokens'''] __UpperCamelCase :Any = [] for i in range(len(doc['''token'''] ) ): if not doc["is_html"][i]: context.append(doc['''token'''][i] ) return { "context": " ".join(SCREAMING_SNAKE_CASE ), "answer": { "start_token": -100, # ignore index in cross-entropy "end_token": -100, # ignore index in cross-entropy "category": answer["category"], "span": answer["category"], # extra }, } # later, help in removing all no answers if answer["start_token"] == [-1]: return { "context": "None", "answer": { "start_token": -1, "end_token": -1, "category": "null", "span": "None", # extra }, } # handling normal samples __UpperCamelCase :Optional[int] = ['''start_token''', '''end_token'''] answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} ) # e.g. [10] == 10 __UpperCamelCase :Optional[Any] = example['''document''']['''tokens'''] __UpperCamelCase :List[Any] = answer['''start_token'''] __UpperCamelCase :Dict = answer['''end_token'''] __UpperCamelCase :Tuple = [] for i in range(len(doc['''token'''] ) ): if not doc["is_html"][i]: context.append(doc['''token'''][i] ) else: if answer["start_token"] > i: start_token -= 1 if answer["end_token"] > i: end_token -= 1 __UpperCamelCase :Optional[int] = ''' '''.join(context[start_token:end_token] ) # checking above code if assertion: __UpperCamelCase :str = doc['''is_html'''][answer['''start_token'''] : answer['''end_token''']] __UpperCamelCase :Union[str, Any] = doc['''token'''][answer['''start_token'''] : answer['''end_token''']] __UpperCamelCase :Dict = ''' '''.join([old[i] for i in range(len(SCREAMING_SNAKE_CASE ) ) if not is_html[i]] ) if new != old: print('''ID:''' , example['''id'''] ) print('''New:''' , SCREAMING_SNAKE_CASE , end='''\n''' ) print('''Old:''' , SCREAMING_SNAKE_CASE , end='''\n\n''' ) return { "context": " ".join(SCREAMING_SNAKE_CASE ), "answer": { "start_token": start_token, "end_token": end_token - 1, # this makes it inclusive "category": answer["category"], # either long or short "span": new, # extra }, } def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2_048 , SCREAMING_SNAKE_CASE=4_096 , SCREAMING_SNAKE_CASE=True ): '''simple docstring''' __UpperCamelCase :Optional[Any] = get_context_and_ans(SCREAMING_SNAKE_CASE , assertion=SCREAMING_SNAKE_CASE ) __UpperCamelCase :List[str] = out['''answer'''] # later, removing these samples if answer["start_token"] == -1: return { "example_id": example["id"], "input_ids": [[-1]], "labels": { "start_token": [-1], "end_token": [-1], "category": ["null"], }, } __UpperCamelCase :Optional[int] = tokenizer(example['''question''']['''text'''] , out['''context'''] ).input_ids __UpperCamelCase :Optional[int] = input_ids.index(tokenizer.sep_token_id ) + 1 # return yes/no if answer["category"][0] in ["yes", "no"]: # category is list with one element __UpperCamelCase :int = [] __UpperCamelCase :Any = [] __UpperCamelCase :Tuple = input_ids[:q_len] __UpperCamelCase :Any = range(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) , max_length - doc_stride ) for i in doc_start_indices: __UpperCamelCase :Tuple = i + max_length - q_len __UpperCamelCase :Any = input_ids[i:end_index] inputs.append(q_indices + slice ) category.append(answer['''category'''][0] ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": [-100] * len(SCREAMING_SNAKE_CASE ), "end_token": [-100] * len(SCREAMING_SNAKE_CASE ), "category": category, }, } __UpperCamelCase :Tuple = out['''context'''].split() __UpperCamelCase :Optional[Any] = splitted_context[answer['''end_token''']] __UpperCamelCase :List[str] = len( tokenizer( ''' '''.join(splitted_context[: answer['''start_token''']] ) , add_special_tokens=SCREAMING_SNAKE_CASE , ).input_ids ) __UpperCamelCase :Dict = len( tokenizer(''' '''.join(splitted_context[: answer['''end_token''']] ) , add_special_tokens=SCREAMING_SNAKE_CASE ).input_ids ) answer["start_token"] += q_len answer["end_token"] += q_len # fixing end token __UpperCamelCase :Any = len(tokenizer(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ).input_ids ) if num_sub_tokens > 1: answer["end_token"] += num_sub_tokens - 1 __UpperCamelCase :Optional[Any] = input_ids[answer['''start_token'''] : answer['''end_token'''] + 1] # right & left are inclusive __UpperCamelCase :List[Any] = answer['''start_token'''] __UpperCamelCase :Optional[Any] = answer['''end_token'''] if assertion: __UpperCamelCase :Optional[int] = tokenizer.decode(SCREAMING_SNAKE_CASE ) if answer["span"] != new: print('''ISSUE IN TOKENIZATION''' ) print('''OLD:''' , answer['''span'''] ) print('''NEW:''' , SCREAMING_SNAKE_CASE , end='''\n\n''' ) if len(SCREAMING_SNAKE_CASE ) <= max_length: return { "example_id": example["id"], "input_ids": [input_ids], "labels": { "start_token": [answer["start_token"]], "end_token": [answer["end_token"]], "category": answer["category"], }, } __UpperCamelCase :List[str] = input_ids[:q_len] __UpperCamelCase :Optional[Any] = range(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) , max_length - doc_stride ) __UpperCamelCase :str = [] __UpperCamelCase :List[str] = [] __UpperCamelCase :str = [] __UpperCamelCase :List[Any] = [] # null, yes, no, long, short for i in doc_start_indices: __UpperCamelCase :str = i + max_length - q_len __UpperCamelCase :str = input_ids[i:end_index] inputs.append(q_indices + slice ) assert len(inputs[-1] ) <= max_length, "Issue in truncating length" if start_token >= i and end_token <= end_index - 1: __UpperCamelCase :Tuple = start_token - i + q_len __UpperCamelCase :List[str] = end_token - i + q_len answers_category.append(answer['''category'''][0] ) # ["short"] -> "short" else: __UpperCamelCase :Any = -100 __UpperCamelCase :Union[str, Any] = -100 answers_category.append('''null''' ) __UpperCamelCase :str = inputs[-1][start_token : end_token + 1] answers_start_token.append(SCREAMING_SNAKE_CASE ) answers_end_token.append(SCREAMING_SNAKE_CASE ) if assertion: if new != old and new != [tokenizer.cls_token_id]: print('''ISSUE in strided for ID:''' , example['''id'''] ) print('''New:''' , tokenizer.decode(SCREAMING_SNAKE_CASE ) ) print('''Old:''' , tokenizer.decode(SCREAMING_SNAKE_CASE ) , end='''\n\n''' ) if slice[-1] == tokenizer.sep_token_id: break return { "example_id": example["id"], "input_ids": inputs, "labels": { "start_token": answers_start_token, "end_token": answers_end_token, "category": answers_category, }, } def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=2_048 , SCREAMING_SNAKE_CASE=4_096 , SCREAMING_SNAKE_CASE=False ): '''simple docstring''' __UpperCamelCase :Any = get_strided_contexts_and_ans( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , doc_stride=SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , assertion=SCREAMING_SNAKE_CASE , ) return example def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' with jsonlines.open(SCREAMING_SNAKE_CASE , '''a''' ) as writer: for example in tqdm(SCREAMING_SNAKE_CASE , total=len(SCREAMING_SNAKE_CASE ) , desc='''Saving samples ... ''' ): __UpperCamelCase :Union[str, Any] = example['''labels'''] for ids, start, end, cat in zip( example['''input_ids'''] , labels['''start_token'''] , labels['''end_token'''] , labels['''category'''] , ): if start == -1 and end == -1: continue # leave waste samples with no answer if cat == "null" and np.random.rand() < 0.6: continue # removing 50 % samples writer.write( { '''input_ids''': ids, '''start_token''': start, '''end_token''': end, '''category''': CATEGORY_MAPPING[cat], } ) if __name__ == "__main__": from datasets import load_dataset from transformers import BigBirdTokenizer __lowercase = load_dataset('''natural_questions''') __lowercase = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''') __lowercase = data['''train''' if PROCESS_TRAIN == '''true''' else '''validation'''] __lowercase = { '''tokenizer''': tokenizer, '''doc_stride''': DOC_STRIDE, '''max_length''': MAX_LENGTH, '''assertion''': False, } __lowercase = data.map(prepare_inputs, fn_kwargs=fn_kwargs) __lowercase = data.remove_columns(['''annotations''', '''document''', '''id''', '''question''']) print(data) np.random.seed(SEED) __lowercase = '''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl''' save_to_disk(data, file_name=cache_file_name)
43
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { '''facebook/wav2vec2-base-960h''': '''https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json''', # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : Union[str, Any] = """wav2vec2""" def __init__( self , __lowercase=32 , __lowercase=768 , __lowercase=12 , __lowercase=12 , __lowercase=3_072 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.0 , __lowercase=0.0 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.02 , __lowercase=1E-5 , __lowercase="group" , __lowercase="gelu" , __lowercase=(512, 512, 512, 512, 512, 512, 512) , __lowercase=(5, 2, 2, 2, 2, 2, 2) , __lowercase=(10, 3, 3, 3, 3, 2, 2) , __lowercase=False , __lowercase=128 , __lowercase=16 , __lowercase=False , __lowercase=True , __lowercase=0.05 , __lowercase=10 , __lowercase=2 , __lowercase=0.0 , __lowercase=10 , __lowercase=0 , __lowercase=320 , __lowercase=2 , __lowercase=0.1 , __lowercase=100 , __lowercase=256 , __lowercase=256 , __lowercase=0.1 , __lowercase="sum" , __lowercase=False , __lowercase=False , __lowercase=256 , __lowercase=(512, 512, 512, 512, 1_500) , __lowercase=(5, 3, 3, 1, 1) , __lowercase=(1, 2, 3, 1, 1) , __lowercase=512 , __lowercase=0 , __lowercase=1 , __lowercase=2 , __lowercase=False , __lowercase=3 , __lowercase=2 , __lowercase=3 , __lowercase=None , __lowercase=None , **__lowercase , ) -> int: super().__init__(**__lowercase , pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase) __UpperCamelCase :Any = hidden_size __UpperCamelCase :int = feat_extract_norm __UpperCamelCase :Tuple = feat_extract_activation __UpperCamelCase :Union[str, Any] = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :int = list(__lowercase) __UpperCamelCase :List[Any] = conv_bias __UpperCamelCase :Optional[int] = num_conv_pos_embeddings __UpperCamelCase :Dict = num_conv_pos_embedding_groups __UpperCamelCase :Any = len(self.conv_dim) __UpperCamelCase :List[str] = num_hidden_layers __UpperCamelCase :int = intermediate_size __UpperCamelCase :str = hidden_act __UpperCamelCase :Any = num_attention_heads __UpperCamelCase :int = hidden_dropout __UpperCamelCase :Tuple = attention_dropout __UpperCamelCase :List[str] = activation_dropout __UpperCamelCase :Optional[Any] = feat_proj_dropout __UpperCamelCase :Any = final_dropout __UpperCamelCase :Any = layerdrop __UpperCamelCase :str = layer_norm_eps __UpperCamelCase :Optional[Any] = initializer_range __UpperCamelCase :List[str] = vocab_size __UpperCamelCase :str = do_stable_layer_norm __UpperCamelCase :Union[str, Any] = use_weighted_layer_sum if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,""" f""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __UpperCamelCase :List[Any] = apply_spec_augment __UpperCamelCase :Tuple = mask_time_prob __UpperCamelCase :int = mask_time_length __UpperCamelCase :Dict = mask_time_min_masks __UpperCamelCase :str = mask_feature_prob __UpperCamelCase :List[str] = mask_feature_length __UpperCamelCase :Union[str, Any] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations __UpperCamelCase :Optional[Any] = num_codevectors_per_group __UpperCamelCase :List[Any] = num_codevector_groups __UpperCamelCase :Tuple = contrastive_logits_temperature __UpperCamelCase :Optional[int] = feat_quantizer_dropout __UpperCamelCase :Optional[int] = num_negatives __UpperCamelCase :List[Any] = codevector_dim __UpperCamelCase :str = proj_codevector_dim __UpperCamelCase :List[str] = diversity_loss_weight # ctc loss __UpperCamelCase :Tuple = ctc_loss_reduction __UpperCamelCase :Tuple = ctc_zero_infinity # adapter __UpperCamelCase :List[str] = add_adapter __UpperCamelCase :Tuple = adapter_kernel_size __UpperCamelCase :str = adapter_stride __UpperCamelCase :Tuple = num_adapter_layers __UpperCamelCase :Tuple = output_hidden_size or hidden_size __UpperCamelCase :Optional[Any] = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. __UpperCamelCase :Optional[Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __UpperCamelCase :Optional[int] = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :str = xvector_output_dim @property def UpperCamelCase__ ( self) -> List[str]: return functools.reduce(operator.mul , self.conv_stride , 1)
43
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Union[str, Any] = { "configuration_data2vec_audio": ["DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecAudioConfig"], "configuration_data2vec_text": [ "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecTextConfig", "Data2VecTextOnnxConfig", ], "configuration_data2vec_vision": [ "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecVisionConfig", "Data2VecVisionOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ "DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecAudioForAudioFrameClassification", "Data2VecAudioForCTC", "Data2VecAudioForSequenceClassification", "Data2VecAudioForXVector", "Data2VecAudioModel", "Data2VecAudioPreTrainedModel", ] UpperCAmelCase : Optional[int] = [ "DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecTextForCausalLM", "Data2VecTextForMaskedLM", "Data2VecTextForMultipleChoice", "Data2VecTextForQuestionAnswering", "Data2VecTextForSequenceClassification", "Data2VecTextForTokenClassification", "Data2VecTextModel", "Data2VecTextPreTrainedModel", ] UpperCAmelCase : Optional[int] = [ "DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecVisionForImageClassification", "Data2VecVisionForMaskedImageModeling", "Data2VecVisionForSemanticSegmentation", "Data2VecVisionModel", "Data2VecVisionPreTrainedModel", ] if is_tf_available(): UpperCAmelCase : List[str] = [ "TFData2VecVisionForImageClassification", "TFData2VecVisionForSemanticSegmentation", "TFData2VecVisionModel", "TFData2VecVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
369
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase=False ) -> Union[str, Any]: '''simple docstring''' lowercase_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''module.blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''module.blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''module.blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''module.blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''module.blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''module.blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowercase_ = [(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 _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=False ) -> Any: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: lowercase_ = """""" else: lowercase_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowercase_ = state_dict.pop(F'''module.blocks.{i}.attn.qkv.weight''' ) lowercase_ = state_dict.pop(F'''module.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowercase_ = in_proj_weight[ : config.hidden_size, : ] lowercase_ = in_proj_bias[: config.hidden_size] lowercase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowercase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowercase_ = in_proj_weight[ -config.hidden_size :, : ] lowercase_ = in_proj_bias[-config.hidden_size :] def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> List[str]: '''simple docstring''' lowercase_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> str: '''simple docstring''' lowercase_ = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(__lowerCAmelCase , __lowerCAmelCase ) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Tuple: '''simple docstring''' lowercase_ = dct.pop(__lowerCAmelCase ) lowercase_ = val def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> Tuple: '''simple docstring''' lowercase_ = ViTMSNConfig() lowercase_ = 10_00 lowercase_ = """datasets/huggingface/label-files""" lowercase_ = """imagenet-1k-id2label.json""" lowercase_ = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase ) , """r""" ) ) lowercase_ = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} lowercase_ = idalabel lowercase_ = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: lowercase_ = 3_84 lowercase_ = 15_36 lowercase_ = 6 elif "l16" in checkpoint_url: lowercase_ = 10_24 lowercase_ = 40_96 lowercase_ = 24 lowercase_ = 16 lowercase_ = 0.1 elif "b4" in checkpoint_url: lowercase_ = 4 elif "l7" in checkpoint_url: lowercase_ = 7 lowercase_ = 10_24 lowercase_ = 40_96 lowercase_ = 24 lowercase_ = 16 lowercase_ = 0.1 lowercase_ = ViTMSNModel(__lowerCAmelCase ) lowercase_ = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" )["""target_encoder"""] lowercase_ = ViTImageProcessor(size=config.image_size ) remove_projection_head(__lowerCAmelCase ) lowercase_ = create_rename_keys(__lowerCAmelCase , base_model=__lowerCAmelCase ) for src, dest in rename_keys: rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) read_in_q_k_v(__lowerCAmelCase , __lowerCAmelCase , base_model=__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() lowercase_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowercase_ = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) lowercase_ = ViTImageProcessor( size=config.image_size , image_mean=__lowerCAmelCase , image_std=__lowerCAmelCase ) lowercase_ = image_processor(images=__lowerCAmelCase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) lowercase_ = model(**__lowerCAmelCase ) lowercase_ = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: lowercase_ = torch.tensor([[-1.0_915, -1.4_876, -1.1_809]] ) elif "b16" in checkpoint_url: lowercase_ = torch.tensor([[14.2_889, -18.9_045, 11.7_281]] ) elif "l16" in checkpoint_url: lowercase_ = torch.tensor([[41.5_028, -22.8_681, 45.6_475]] ) elif "b4" in checkpoint_url: lowercase_ = torch.tensor([[-4.3_868, 5.2_932, -0.4_137]] ) else: lowercase_ = torch.tensor([[-0.1_792, -0.6_465, 2.4_263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , __lowerCAmelCase , atol=1E-4 ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(__lowerCAmelCase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": UpperCAmelCase : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase : Tuple = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
313
0
'''simple docstring''' class __lowerCAmelCase : """simple docstring""" def __init__( self : Optional[int] , lowerCAmelCase__ : int ) -> None: '''simple docstring''' _UpperCamelCase = size _UpperCamelCase = [0] * size _UpperCamelCase = [0] * size @staticmethod def snake_case__ ( lowerCAmelCase__ : int ) -> int: '''simple docstring''' return index | (index + 1) @staticmethod def snake_case__ ( lowerCAmelCase__ : int ) -> int: '''simple docstring''' return (index & (index + 1)) - 1 def snake_case__ ( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> None: '''simple docstring''' _UpperCamelCase = value while index < self.size: _UpperCamelCase = self.get_prev(_A ) + 1 if current_left_border == index: _UpperCamelCase = value else: _UpperCamelCase = max(_A , _A , _A ) _UpperCamelCase = self.get_next(_A ) def snake_case__ ( self : str , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> int: '''simple docstring''' right -= 1 # Because of right is exclusive _UpperCamelCase = 0 while left <= right: _UpperCamelCase = self.get_prev(_A ) if left <= current_left: _UpperCamelCase = max(_A , self.tree[right] ) _UpperCamelCase = current_left else: _UpperCamelCase = max(_A , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
324
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class _lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Optional[int] ) -> List[Any]: # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. __magic_name__ : Any = [[1, 2, 4], [1, 2, 3, 4]] __magic_name__ : Dict = DisjunctiveConstraint(_A ) self.assertTrue(isinstance(dc.token_ids , _A ) ) with self.assertRaises(_A ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_A ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). __magic_name__ : Optional[int] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_A ): DisjunctiveConstraint(_A ) # fails here def __lowerCAmelCase ( self : List[Any] ) -> Tuple: __magic_name__ : Dict = [[1, 2, 3], [1, 2, 4]] __magic_name__ : List[Any] = DisjunctiveConstraint(_A ) __magic_name__ , __magic_name__ , __magic_name__ : Tuple = dc.update(1 ) __magic_name__ : Optional[int] = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ : Optional[int] = dc.update(2 ) __magic_name__ : List[Any] = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ : int = dc.update(3 ) __magic_name__ : Any = stepped is True and completed is True and reset is False self.assertTrue(_A ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: __magic_name__ : Union[str, Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __magic_name__ : Union[str, Any] = DisjunctiveConstraint(_A ) __magic_name__ , __magic_name__ , __magic_name__ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ : Any = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ : Optional[int] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __magic_name__ , __magic_name__ , __magic_name__ : Any = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __magic_name__ , __magic_name__ , __magic_name__ : int = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __magic_name__ , __magic_name__ , __magic_name__ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __magic_name__ , __magic_name__ , __magic_name__ : int = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
331
0
'''simple docstring''' from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class __lowerCAmelCase ( __a ): def snake_case_ (self , lowerCAmelCase__ ): return 0.0 def __A ( lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : Tuple = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) _UpperCAmelCase : List[str] = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def __A ( lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : List[str] = 512 _UpperCAmelCase : Any = [1] + [0] * (size - 1) _UpperCAmelCase : Union[str, Any] = [filter_type.process(lowerCAmelCase_ ) for item in inputs] _UpperCAmelCase : List[Any] = [0] * (samplerate - size) # zero-padding outputs += filler _UpperCAmelCase : Optional[Any] = np.abs(np.fft.fft(lowerCAmelCase_ ) ) _UpperCAmelCase : List[str] = 20 * np.logaa(lowerCAmelCase_ ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("""Frequency (Hz)""" ) plt.xscale("""log""" ) # Display within reasonable bounds _UpperCAmelCase : Union[str, Any] = get_bounds(lowerCAmelCase_ , lowerCAmelCase_ ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel("""Gain (dB)""" ) plt.plot(lowerCAmelCase_ ) plt.show() def __A ( lowerCAmelCase_ , lowerCAmelCase_ ): _UpperCAmelCase : int = 512 _UpperCAmelCase : Any = [1] + [0] * (size - 1) _UpperCAmelCase : Dict = [filter_type.process(lowerCAmelCase_ ) for item in inputs] _UpperCAmelCase : Dict = [0] * (samplerate - size) # zero-padding outputs += filler _UpperCAmelCase : Any = np.angle(np.fft.fft(lowerCAmelCase_ ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel("""Frequency (Hz)""" ) plt.xscale("""log""" ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel("""Phase shift (Radians)""" ) plt.plot(np.unwrap(lowerCAmelCase_ , -2 * pi ) ) plt.show()
170
'''simple docstring''' import numpy as np def __A ( lowerCAmelCase_ ): return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
170
1
"""simple docstring""" import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class __A : """simple docstring""" @staticmethod def SCREAMING_SNAKE_CASE ( *__A , **__A ) -> Tuple: pass def _A ( lowercase ): """simple docstring""" a =hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class __A ( unittest.TestCase ): """simple docstring""" __lowerCAmelCase = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def SCREAMING_SNAKE_CASE ( self , __A , __A , __A ) -> Union[str, Any]: a =DepthEstimationPipeline(model=__A , image_processor=__A ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def SCREAMING_SNAKE_CASE ( self , __A , __A ) -> Union[str, Any]: a =depth_estimator('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) self.assertEqual({'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )} , __A ) import datasets a =datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''' , '''image''' , split='''test''' ) a =depth_estimator( [ Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ), '''http://images.cocodataset.org/val2017/000000039769.jpg''', # RGBA dataset[0]['''file'''], # LA dataset[1]['''file'''], # L dataset[2]['''file'''], ] ) self.assertEqual( [ {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, {'''predicted_depth''': ANY(torch.Tensor ), '''depth''': ANY(Image.Image )}, ] , __A , ) @require_tf @unittest.skip('''Depth estimation is not implemented in TF''' ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a ='''Intel/dpt-large''' a =pipeline('''depth-estimation''' , model=__A ) a =depth_estimator('''http://images.cocodataset.org/val2017/000000039769.jpg''' ) a =hashimage(outputs['''depth'''] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['''predicted_depth'''].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['''predicted_depth'''].min().item() ) , 2.662 ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: # This is highly irregular to have no small tests. self.skipTest('''There is not hf-internal-testing tiny model for either GLPN nor DPT''' )
81
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name if "attn.proj" in name: a =name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a =name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a =name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a =name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a =name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a =name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Any: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Dict: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Any: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Any: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> str: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Optional[int]: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Dict: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> str: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> List[Any]: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Any: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Dict: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> int: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> List[str]: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> int: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> List[str]: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> List[str]: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> int: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> int: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> int: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> str: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Dict: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> List[Any]: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Any: '''simple docstring''' requires_backends(cls , ['flax']) class __magic_name__ ( metaclass=lowerCAmelCase ): UpperCAmelCase =["flax"] def __init__( self , *snake_case , **snake_case) -> Optional[Any]: '''simple docstring''' requires_backends(self , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Tuple: '''simple docstring''' requires_backends(cls , ['flax']) @classmethod def lowerCAmelCase ( cls , *snake_case , **snake_case) -> Union[str, Any]: '''simple docstring''' requires_backends(cls , ['flax'])
242
'''simple docstring''' from __future__ import annotations import bisect def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int , __lowerCamelCase : int = 0 , __lowerCamelCase : int = -1 ): '''simple docstring''' if hi < 0: _UpperCAmelCase : int =len(__lowerCamelCase ) while lo < hi: _UpperCAmelCase : Dict =lo + (hi - lo) // 2 if sorted_collection[mid] < item: _UpperCAmelCase : int =mid + 1 else: _UpperCAmelCase : Union[str, Any] =mid return lo def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int , __lowerCamelCase : int = 0 , __lowerCamelCase : int = -1 ): '''simple docstring''' if hi < 0: _UpperCAmelCase : str =len(__lowerCamelCase ) while lo < hi: _UpperCAmelCase : List[Any] =lo + (hi - lo) // 2 if sorted_collection[mid] <= item: _UpperCAmelCase : Dict =mid + 1 else: _UpperCAmelCase : Tuple =mid return lo def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int , __lowerCamelCase : int = 0 , __lowerCamelCase : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_left(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , __lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int , __lowerCamelCase : int = 0 , __lowerCamelCase : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_right(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , __lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : Optional[int] =0 _UpperCAmelCase : Any =len(__lowerCamelCase ) - 1 while left <= right: _UpperCAmelCase : int =left + (right - left) // 2 _UpperCAmelCase : Union[str, Any] =sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: _UpperCAmelCase : Optional[Any] =midpoint - 1 else: _UpperCAmelCase : int =midpoint + 1 return None def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : Any =bisect.bisect_left(__lowerCamelCase , __lowerCamelCase ) if index != len(__lowerCamelCase ) and sorted_collection[index] == item: return index return None def lowerCamelCase__ ( __lowerCamelCase : list[int] , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ): '''simple docstring''' if right < left: return None _UpperCAmelCase : str =left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , midpoint - 1 ) else: return binary_search_by_recursion(__lowerCamelCase , __lowerCamelCase , midpoint + 1 , __lowerCamelCase ) if __name__ == "__main__": lowercase =input('Enter numbers separated by comma:\n').strip() lowercase =sorted(int(item) for item in user_input.split(',')) lowercase =int(input('Enter a single number to be found in the list:\n')) lowercase =binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
242
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =intermediate_size SCREAMING_SNAKE_CASE =hidden_act SCREAMING_SNAKE_CASE =hidden_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def _a ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): # Initialise PyTorch model __lowerCAmelCase = AlbertConfig.from_json_file(SCREAMING_SNAKE_CASE_ ) print(F"""Building PyTorch model from configuration: {config}""" ) __lowerCAmelCase = AlbertForPreTraining(SCREAMING_SNAKE_CASE_ ) # Load weights from tf checkpoint load_tf_weights_in_albert(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__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--albert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained ALBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) UpperCamelCase__ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
102
def _a ( SCREAMING_SNAKE_CASE_ : List[Any] ): __lowerCAmelCase , __lowerCAmelCase = [], [] while len(SCREAMING_SNAKE_CASE_ ) > 1: __lowerCAmelCase , __lowerCAmelCase = 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__": UpperCamelCase__ = input("""Enter numbers separated by a comma:\n""").strip() UpperCamelCase__ = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
102
1
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets _A : Union[str, Any] ='''\ @inproceedings{wang2019glue, title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding}, author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.}, note={In the Proceedings of ICLR.}, year={2019} } ''' _A : Optional[Any] ='''\ GLUE, the General Language Understanding Evaluation benchmark (https://gluebenchmark.com/) is a collection of resources for training, evaluating, and analyzing natural language understanding systems. ''' _A : Optional[int] =''' Compute GLUE evaluation metric associated to each GLUE dataset. Args: predictions: list of predictions to score. Each translation should be tokenized into a list of tokens. references: list of lists of references for each translation. Each reference should be tokenized into a list of tokens. Returns: depending on the GLUE subset, one or several of: "accuracy": Accuracy "f1": F1 score "pearson": Pearson Correlation "spearmanr": Spearman Correlation "matthews_correlation": Matthew Correlation Examples: >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\' >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\') >>> references = [0., 1., 2., 3., 4., 5.] >>> predictions = [0., 1., 2., 3., 4., 5.] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)}) {\'pearson\': 1.0, \'spearmanr\': 1.0} >>> glue_metric = datasets.load_metric(\'glue\', \'cola\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Optional[int] = simple_accuracy(UpperCamelCase , UpperCamelCase ) lowerCamelCase__ : Any = float(fa_score(y_true=UpperCamelCase , y_pred=UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> str: lowerCamelCase__ : int = float(pearsonr(UpperCamelCase , UpperCamelCase )[0] ) lowerCamelCase__ : Tuple = float(spearmanr(UpperCamelCase , UpperCamelCase )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def lowerCamelCase_ ( self: Optional[Any] ): if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """ """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ), """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ), } ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" , ) def lowerCamelCase_ ( self: List[str] , UpperCamelCase__: str , UpperCamelCase__: Optional[Any] ): if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(UpperCamelCase__ , UpperCamelCase__ )} elif self.config_name == "stsb": return pearson_and_spearman(UpperCamelCase__ , UpperCamelCase__ ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(UpperCamelCase__ , UpperCamelCase__ ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(UpperCamelCase__ , UpperCamelCase__ )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """ """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
41
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase_( a__ , a__=False ): """simple docstring""" SCREAMING_SNAKE_CASE : int = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('''module.cls_token''', '''vit.embeddings.cls_token'''), ('''module.patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''module.patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''module.pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''module.norm.weight''', '''layernorm.weight'''), ('''module.norm.bias''', '''layernorm.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE : 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 UpperCAmelCase_( a__ , a__ , a__=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE : Any = '''''' else: SCREAMING_SNAKE_CASE : Optional[int] = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" ) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : List[str] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE : Any = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(a__ , a__ ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [ '''module.fc.fc1.weight''', '''module.fc.fc1.bias''', '''module.fc.bn1.weight''', '''module.fc.bn1.bias''', '''module.fc.bn1.running_mean''', '''module.fc.bn1.running_var''', '''module.fc.bn1.num_batches_tracked''', '''module.fc.fc2.weight''', '''module.fc.fc2.bias''', '''module.fc.bn2.weight''', '''module.fc.bn2.bias''', '''module.fc.bn2.running_mean''', '''module.fc.bn2.running_var''', '''module.fc.bn2.num_batches_tracked''', '''module.fc.fc3.weight''', '''module.fc.fc3.bias''', ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = dct.pop(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = val def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = ViTMSNConfig() SCREAMING_SNAKE_CASE : Optional[int] = 1_000 SCREAMING_SNAKE_CASE : str = '''datasets/huggingface/label-files''' SCREAMING_SNAKE_CASE : List[str] = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(open(hf_hub_download(a__ , a__ ) , '''r''' ) ) SCREAMING_SNAKE_CASE : List[Any] = {int(a__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = idalabel SCREAMING_SNAKE_CASE : int = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = 384 SCREAMING_SNAKE_CASE : Any = 1_536 SCREAMING_SNAKE_CASE : List[str] = 6 elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE : Optional[int] = 1_024 SCREAMING_SNAKE_CASE : Optional[int] = 4_096 SCREAMING_SNAKE_CASE : Tuple = 24 SCREAMING_SNAKE_CASE : Union[str, Any] = 16 SCREAMING_SNAKE_CASE : Dict = 0.1 elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE : str = 4 elif "l7" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = 7 SCREAMING_SNAKE_CASE : Union[str, Any] = 1_024 SCREAMING_SNAKE_CASE : List[Any] = 4_096 SCREAMING_SNAKE_CASE : List[Any] = 24 SCREAMING_SNAKE_CASE : Tuple = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 0.1 SCREAMING_SNAKE_CASE : Union[str, Any] = ViTMSNModel(a__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load_state_dict_from_url(a__ , map_location='''cpu''' )['''target_encoder'''] SCREAMING_SNAKE_CASE : Any = ViTImageProcessor(size=config.image_size ) remove_projection_head(a__ ) SCREAMING_SNAKE_CASE : Any = create_rename_keys(a__ , base_model=a__ ) for src, dest in rename_keys: rename_key(a__ , a__ , a__ ) read_in_q_k_v(a__ , a__ , base_model=a__ ) model.load_state_dict(a__ ) model.eval() SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : Dict = Image.open(requests.get(a__ , stream=a__ ).raw ) SCREAMING_SNAKE_CASE : Optional[int] = ViTImageProcessor( size=config.image_size , image_mean=a__ , image_std=a__ ) SCREAMING_SNAKE_CASE : int = image_processor(images=a__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE : Tuple = model(**a__ ) SCREAMING_SNAKE_CASE : str = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[-1.0_915, -1.4_876, -1.1_809]] ) elif "b16" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[14.2_889, -18.9_045, 11.7_281]] ) elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[41.5_028, -22.8_681, 45.6_475]] ) elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE : str = torch.tensor([[-4.3_868, 5.2_932, -0.4_137]] ) else: SCREAMING_SNAKE_CASE : List[str] = torch.tensor([[-0.1_792, -0.6_465, 2.4_263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , a__ , atol=1e-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(a__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) a__ : Any = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
313
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'BridgeTower/bridgetower-base': 'https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json', 'BridgeTower/bridgetower-base-itm-mlm': ( 'https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json' ), } class lowerCamelCase (_snake_case ): '''simple docstring''' _snake_case : List[str] = '''bridgetower_vision_model''' def __init__( self , _UpperCamelCase=7_6_8 , _UpperCamelCase=1_2 , _UpperCamelCase=3 , _UpperCamelCase=1_6 , _UpperCamelCase=2_8_8 , _UpperCamelCase=1 , _UpperCamelCase=1E-05 , _UpperCamelCase=False , _UpperCamelCase=True , _UpperCamelCase=False , **_UpperCamelCase , ) -> Optional[int]: super().__init__(**_UpperCamelCase ) UpperCAmelCase_ : Union[str, Any] = hidden_size UpperCAmelCase_ : int = num_hidden_layers UpperCAmelCase_ : List[Any] = num_channels UpperCAmelCase_ : str = patch_size UpperCAmelCase_ : Tuple = image_size UpperCAmelCase_ : str = initializer_factor UpperCAmelCase_ : int = layer_norm_eps UpperCAmelCase_ : Tuple = stop_gradient UpperCAmelCase_ : Union[str, Any] = share_layernorm UpperCAmelCase_ : Any = remove_last_layer @classmethod def __UpperCAmelCase ( cls , _UpperCamelCase , **_UpperCamelCase ) -> "PretrainedConfig": UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = cls.get_config_dict(_UpperCamelCase , **_UpperCamelCase ) if config_dict.get('model_type' ) == "bridgetower": UpperCAmelCase_ : List[Any] = config_dict['text_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(_UpperCamelCase , **_UpperCamelCase ) class lowerCamelCase (_snake_case ): '''simple docstring''' _snake_case : Any = '''bridgetower_text_model''' def __init__( self , _UpperCamelCase=5_0_2_6_5 , _UpperCamelCase=7_6_8 , _UpperCamelCase=1_2 , _UpperCamelCase=1_2 , _UpperCamelCase=1 , _UpperCamelCase=3_0_7_2 , _UpperCamelCase="gelu" , _UpperCamelCase=0.1 , _UpperCamelCase=0.1 , _UpperCamelCase=5_1_4 , _UpperCamelCase=1 , _UpperCamelCase=1E-05 , _UpperCamelCase=1 , _UpperCamelCase=0 , _UpperCamelCase=2 , _UpperCamelCase="absolute" , _UpperCamelCase=True , **_UpperCamelCase , ) -> Optional[int]: super().__init__(**_UpperCamelCase ) UpperCAmelCase_ : Union[str, Any] = vocab_size UpperCAmelCase_ : Optional[Any] = hidden_size UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : str = num_attention_heads UpperCAmelCase_ : str = hidden_act UpperCAmelCase_ : Optional[int] = initializer_factor UpperCAmelCase_ : str = intermediate_size UpperCAmelCase_ : Tuple = hidden_dropout_prob UpperCAmelCase_ : str = attention_probs_dropout_prob UpperCAmelCase_ : List[str] = max_position_embeddings UpperCAmelCase_ : Tuple = type_vocab_size UpperCAmelCase_ : Optional[int] = layer_norm_eps UpperCAmelCase_ : Any = position_embedding_type UpperCAmelCase_ : Tuple = use_cache UpperCAmelCase_ : Dict = pad_token_id UpperCAmelCase_ : Optional[Any] = bos_token_id UpperCAmelCase_ : int = eos_token_id @classmethod def __UpperCAmelCase ( cls , _UpperCamelCase , **_UpperCamelCase ) -> "PretrainedConfig": UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = cls.get_config_dict(_UpperCamelCase , **_UpperCamelCase ) if config_dict.get('model_type' ) == "bridgetower": UpperCAmelCase_ : Any = config_dict['text_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(_UpperCamelCase , **_UpperCamelCase ) class lowerCamelCase (_snake_case ): '''simple docstring''' _snake_case : str = '''bridgetower''' def __init__( self , _UpperCamelCase=True , _UpperCamelCase="gelu" , _UpperCamelCase=7_6_8 , _UpperCamelCase=1 , _UpperCamelCase=1E-05 , _UpperCamelCase=False , _UpperCamelCase="add" , _UpperCamelCase=1_2 , _UpperCamelCase=6 , _UpperCamelCase=False , _UpperCamelCase=False , _UpperCamelCase=None , _UpperCamelCase=None , **_UpperCamelCase , ) -> Union[str, Any]: # TODO: remove this once the Hub files are updated. UpperCAmelCase_ : Dict = kwargs.pop('text_config_dict' , _UpperCamelCase ) UpperCAmelCase_ : Union[str, Any] = kwargs.pop('vision_config_dict' , _UpperCamelCase ) super().__init__(**_UpperCamelCase ) UpperCAmelCase_ : int = share_cross_modal_transformer_layers UpperCAmelCase_ : Tuple = hidden_act UpperCAmelCase_ : Any = hidden_size UpperCAmelCase_ : Optional[Any] = initializer_factor UpperCAmelCase_ : Union[str, Any] = layer_norm_eps UpperCAmelCase_ : Optional[Any] = share_link_tower_layers UpperCAmelCase_ : Dict = link_tower_type UpperCAmelCase_ : Union[str, Any] = num_attention_heads UpperCAmelCase_ : int = num_hidden_layers UpperCAmelCase_ : int = tie_word_embeddings UpperCAmelCase_ : int = init_layernorm_from_vision_encoder if text_config is None: UpperCAmelCase_ : Optional[int] = {} logger.info('`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.' ) if vision_config is None: UpperCAmelCase_ : List[str] = {} logger.info('`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.' ) UpperCAmelCase_ : Any = BridgeTowerTextConfig(**_UpperCamelCase ) UpperCAmelCase_ : Any = BridgeTowerVisionConfig(**_UpperCamelCase ) @classmethod def __UpperCAmelCase ( cls , _UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[Any]: UpperCAmelCase_ : Union[str, Any] = copy.deepcopy(self.__dict__ ) UpperCAmelCase_ : Any = self.text_config.to_dict() UpperCAmelCase_ : Union[str, Any] = self.vision_config.to_dict() UpperCAmelCase_ : Any = self.__class__.model_type return output
145
def lowercase__ ( __snake_case : str , __snake_case : int , __snake_case : List[str] ): '''simple docstring''' if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__snake_case , n - 1 , __snake_case ) * a) % mod else: UpperCAmelCase_ : Optional[int] = binary_exponentiation(__snake_case , n / 2 , __snake_case ) return (b * b) % mod # a prime number __UpperCAmelCase = 701 __UpperCAmelCase = 1000000000 __UpperCAmelCase = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
145
1
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCAmelCase_ ( _lowercase : bool = True , *_lowercase : List[str] , **_lowercase : Tuple) -> Any: """simple docstring""" if not is_tqdm_available(): raise ImportError("""Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.""") a__ : Optional[Any] = False if main_process_only: a__ : Dict = PartialState().local_process_index == 0 return _tqdm(*_lowercase , **_lowercase , disable=_lowercase)
170
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def lowerCAmelCase_ ( _lowercase : str , _lowercase : str , **_lowercase : Optional[Any]) -> Optional[int]: """simple docstring""" a__ : List[Any] = AutoConfig.from_pretrained(_lowercase , **_lowercase) a__ : Dict = AutoModelForSeqaSeqLM.from_config(_lowercase) model.save_pretrained(_lowercase) AutoTokenizer.from_pretrained(_lowercase).save_pretrained(_lowercase) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
170
1
from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __UpperCamelCase = """efficientformer""" def __init__( self :List[str] , lowercase_ :List[int] = [3, 2, 6, 4] , lowercase_ :List[int] = [48, 96, 2_24, 4_48] , lowercase_ :List[bool] = [True, True, True, True] , lowercase_ :int = 4_48 , lowercase_ :int = 32 , lowercase_ :int = 4 , lowercase_ :int = 7 , lowercase_ :int = 5 , lowercase_ :int = 8 , lowercase_ :int = 4 , lowercase_ :float = 0.0 , lowercase_ :int = 16 , lowercase_ :int = 3 , lowercase_ :int = 3 , lowercase_ :int = 3 , lowercase_ :int = 2 , lowercase_ :int = 1 , lowercase_ :float = 0.0 , lowercase_ :int = 1 , lowercase_ :bool = True , lowercase_ :bool = True , lowercase_ :float = 1E-5 , lowercase_ :str = "gelu" , lowercase_ :float = 0.02 , lowercase_ :float = 1E-12 , lowercase_ :int = 2_24 , lowercase_ :float = 1E-05 , **lowercase_ :Optional[Any] , ) -> None: super().__init__(**lowercase_ ) UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = hidden_sizes UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = patch_size UpperCAmelCase = num_channels UpperCAmelCase = depths UpperCAmelCase = mlp_expansion_ratio UpperCAmelCase = downsamples UpperCAmelCase = dim UpperCAmelCase = key_dim UpperCAmelCase = attention_ratio UpperCAmelCase = resolution UpperCAmelCase = pool_size UpperCAmelCase = downsample_patch_size UpperCAmelCase = downsample_stride UpperCAmelCase = downsample_pad UpperCAmelCase = drop_path_rate UpperCAmelCase = num_metaad_blocks UpperCAmelCase = distillation UpperCAmelCase = use_layer_scale UpperCAmelCase = layer_scale_init_value UpperCAmelCase = image_size UpperCAmelCase = batch_norm_eps
351
"""simple docstring""" def _lowerCAmelCase ( lowercase_ ): if not isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = F"""Input value of [number={number}] must be an integer""" raise TypeError(lowercase_ ) if number < 1: UpperCAmelCase = F"""Input value of [number={number}] must be > 0""" raise ValueError(lowercase_ ) UpperCAmelCase = 1 for i in range(1 , lowercase_ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
181
0